1 //===-- ConvertExpr.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/Lower/ConvertExpr.h"
14 #include "flang/Evaluate/fold.h"
15 #include "flang/Evaluate/traverse.h"
16 #include "flang/Lower/AbstractConverter.h"
17 #include "flang/Lower/CallInterface.h"
18 #include "flang/Lower/ComponentPath.h"
19 #include "flang/Lower/ConvertType.h"
20 #include "flang/Lower/ConvertVariable.h"
21 #include "flang/Lower/DumpEvaluateExpr.h"
22 #include "flang/Lower/IntrinsicCall.h"
23 #include "flang/Lower/StatementContext.h"
24 #include "flang/Lower/SymbolMap.h"
25 #include "flang/Lower/Todo.h"
26 #include "flang/Optimizer/Builder/Character.h"
27 #include "flang/Optimizer/Builder/Complex.h"
28 #include "flang/Optimizer/Builder/Factory.h"
29 #include "flang/Optimizer/Builder/MutableBox.h"
30 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
31 #include "flang/Semantics/expression.h"
32 #include "flang/Semantics/symbol.h"
33 #include "flang/Semantics/tools.h"
34 #include "flang/Semantics/type.h"
35 #include "mlir/Dialect/Func/IR/FuncOps.h"
36 #include "llvm/Support/Debug.h"
37 
38 #define DEBUG_TYPE "flang-lower-expr"
39 
40 //===----------------------------------------------------------------------===//
41 // The composition and structure of Fortran::evaluate::Expr is defined in
42 // the various header files in include/flang/Evaluate. You are referred
43 // there for more information on these data structures. Generally speaking,
44 // these data structures are a strongly typed family of abstract data types
45 // that, composed as trees, describe the syntax of Fortran expressions.
46 //
47 // This part of the bridge can traverse these tree structures and lower them
48 // to the correct FIR representation in SSA form.
49 //===----------------------------------------------------------------------===//
50 
51 /// The various semantics of a program constituent (or a part thereof) as it may
52 /// appear in an expression.
53 ///
54 /// Given the following Fortran declarations.
55 /// ```fortran
56 ///   REAL :: v1, v2, v3
57 ///   REAL, POINTER :: vp1
58 ///   REAL :: a1(c), a2(c)
59 ///   REAL ELEMENTAL FUNCTION f1(arg) ! array -> array
60 ///   FUNCTION f2(arg)                ! array -> array
61 ///   vp1 => v3       ! 1
62 ///   v1 = v2 * vp1   ! 2
63 ///   a1 = a1 + a2    ! 3
64 ///   a1 = f1(a2)     ! 4
65 ///   a1 = f2(a2)     ! 5
66 /// ```
67 ///
68 /// In line 1, `vp1` is a BoxAddr to copy a box value into. The box value is
69 /// constructed from the DataAddr of `v3`.
70 /// In line 2, `v1` is a DataAddr to copy a value into. The value is constructed
71 /// from the DataValue of `v2` and `vp1`. DataValue is implicitly a double
72 /// dereference in the `vp1` case.
73 /// In line 3, `a1` and `a2` on the rhs are RefTransparent. The `a1` on the lhs
74 /// is CopyInCopyOut as `a1` is replaced elementally by the additions.
75 /// In line 4, `a2` can be RefTransparent, ByValueArg, RefOpaque, or BoxAddr if
76 /// `arg` is declared as C-like pass-by-value, VALUE, INTENT(?), or ALLOCATABLE/
77 /// POINTER, respectively. `a1` on the lhs is CopyInCopyOut.
78 ///  In line 5, `a2` may be DataAddr or BoxAddr assuming f2 is transformational.
79 ///  `a1` on the lhs is again CopyInCopyOut.
80 enum class ConstituentSemantics {
81   // Scalar data reference semantics.
82   //
83   // For these let `v` be the location in memory of a variable with value `x`
84   DataValue, // refers to the value `x`
85   DataAddr,  // refers to the address `v`
86   BoxValue,  // refers to a box value containing `v`
87   BoxAddr,   // refers to the address of a box value containing `v`
88 
89   // Array data reference semantics.
90   //
91   // For these let `a` be the location in memory of a sequence of value `[xs]`.
92   // Let `x_i` be the `i`-th value in the sequence `[xs]`.
93 
94   // Referentially transparent. Refers to the array's value, `[xs]`.
95   RefTransparent,
96   // Refers to an ephemeral address `tmp` containing value `x_i` (15.5.2.3.p7
97   // note 2). (Passing a copy by reference to simulate pass-by-value.)
98   ByValueArg,
99   // Refers to the merge of array value `[xs]` with another array value `[ys]`.
100   // This merged array value will be written into memory location `a`.
101   CopyInCopyOut,
102   // Similar to CopyInCopyOut but `a` may be a transient projection (rather than
103   // a whole array).
104   ProjectedCopyInCopyOut,
105   // Similar to ProjectedCopyInCopyOut, except the merge value is not assigned
106   // automatically by the framework. Instead, and address for `[xs]` is made
107   // accessible so that custom assignments to `[xs]` can be implemented.
108   CustomCopyInCopyOut,
109   // Referentially opaque. Refers to the address of `x_i`.
110   RefOpaque
111 };
112 
113 /// Convert parser's INTEGER relational operators to MLIR.  TODO: using
114 /// unordered, but we may want to cons ordered in certain situation.
115 static mlir::arith::CmpIPredicate
116 translateRelational(Fortran::common::RelationalOperator rop) {
117   switch (rop) {
118   case Fortran::common::RelationalOperator::LT:
119     return mlir::arith::CmpIPredicate::slt;
120   case Fortran::common::RelationalOperator::LE:
121     return mlir::arith::CmpIPredicate::sle;
122   case Fortran::common::RelationalOperator::EQ:
123     return mlir::arith::CmpIPredicate::eq;
124   case Fortran::common::RelationalOperator::NE:
125     return mlir::arith::CmpIPredicate::ne;
126   case Fortran::common::RelationalOperator::GT:
127     return mlir::arith::CmpIPredicate::sgt;
128   case Fortran::common::RelationalOperator::GE:
129     return mlir::arith::CmpIPredicate::sge;
130   }
131   llvm_unreachable("unhandled INTEGER relational operator");
132 }
133 
134 /// Convert parser's REAL relational operators to MLIR.
135 /// The choice of order (O prefix) vs unorder (U prefix) follows Fortran 2018
136 /// requirements in the IEEE context (table 17.1 of F2018). This choice is
137 /// also applied in other contexts because it is easier and in line with
138 /// other Fortran compilers.
139 /// FIXME: The signaling/quiet aspect of the table 17.1 requirement is not
140 /// fully enforced. FIR and LLVM `fcmp` instructions do not give any guarantee
141 /// whether the comparison will signal or not in case of quiet NaN argument.
142 static mlir::arith::CmpFPredicate
143 translateFloatRelational(Fortran::common::RelationalOperator rop) {
144   switch (rop) {
145   case Fortran::common::RelationalOperator::LT:
146     return mlir::arith::CmpFPredicate::OLT;
147   case Fortran::common::RelationalOperator::LE:
148     return mlir::arith::CmpFPredicate::OLE;
149   case Fortran::common::RelationalOperator::EQ:
150     return mlir::arith::CmpFPredicate::OEQ;
151   case Fortran::common::RelationalOperator::NE:
152     return mlir::arith::CmpFPredicate::UNE;
153   case Fortran::common::RelationalOperator::GT:
154     return mlir::arith::CmpFPredicate::OGT;
155   case Fortran::common::RelationalOperator::GE:
156     return mlir::arith::CmpFPredicate::OGE;
157   }
158   llvm_unreachable("unhandled REAL relational operator");
159 }
160 
161 /// Place \p exv in memory if it is not already a memory reference. If
162 /// \p forceValueType is provided, the value is first casted to the provided
163 /// type before being stored (this is mainly intended for logicals whose value
164 /// may be `i1` but needed to be stored as Fortran logicals).
165 static fir::ExtendedValue
166 placeScalarValueInMemory(fir::FirOpBuilder &builder, mlir::Location loc,
167                          const fir::ExtendedValue &exv,
168                          mlir::Type storageType) {
169   mlir::Value valBase = fir::getBase(exv);
170   if (fir::conformsWithPassByRef(valBase.getType()))
171     return exv;
172 
173   assert(!fir::hasDynamicSize(storageType) &&
174          "only expect statically sized scalars to be by value");
175 
176   // Since `a` is not itself a valid referent, determine its value and
177   // create a temporary location at the beginning of the function for
178   // referencing.
179   mlir::Value val = builder.createConvert(loc, storageType, valBase);
180   mlir::Value temp = builder.createTemporary(
181       loc, storageType,
182       llvm::ArrayRef<mlir::NamedAttribute>{
183           Fortran::lower::getAdaptToByRefAttr(builder)});
184   builder.create<fir::StoreOp>(loc, val, temp);
185   return fir::substBase(exv, temp);
186 }
187 
188 /// Is this a variable wrapped in parentheses?
189 template <typename A>
190 static bool isParenthesizedVariable(const A &) {
191   return false;
192 }
193 template <typename T>
194 static bool isParenthesizedVariable(const Fortran::evaluate::Expr<T> &expr) {
195   using ExprVariant = decltype(Fortran::evaluate::Expr<T>::u);
196   using Parentheses = Fortran::evaluate::Parentheses<T>;
197   if constexpr (Fortran::common::HasMember<Parentheses, ExprVariant>) {
198     if (const auto *parentheses = std::get_if<Parentheses>(&expr.u))
199       return Fortran::evaluate::IsVariable(parentheses->left());
200     return false;
201   } else {
202     return std::visit([&](const auto &x) { return isParenthesizedVariable(x); },
203                       expr.u);
204   }
205 }
206 
207 /// Generate a load of a value from an address. Beware that this will lose
208 /// any dynamic type information for polymorphic entities (note that unlimited
209 /// polymorphic cannot be loaded and must not be provided here).
210 static fir::ExtendedValue genLoad(fir::FirOpBuilder &builder,
211                                   mlir::Location loc,
212                                   const fir::ExtendedValue &addr) {
213   return addr.match(
214       [](const fir::CharBoxValue &box) -> fir::ExtendedValue { return box; },
215       [&](const fir::UnboxedValue &v) -> fir::ExtendedValue {
216         if (fir::unwrapRefType(fir::getBase(v).getType())
217                 .isa<fir::RecordType>())
218           return v;
219         return builder.create<fir::LoadOp>(loc, fir::getBase(v));
220       },
221       [&](const fir::MutableBoxValue &box) -> fir::ExtendedValue {
222         TODO(loc, "genLoad for MutableBoxValue");
223       },
224       [&](const fir::BoxValue &box) -> fir::ExtendedValue {
225         TODO(loc, "genLoad for BoxValue");
226       },
227       [&](const auto &) -> fir::ExtendedValue {
228         fir::emitFatalError(
229             loc, "attempting to load whole array or procedure address");
230       });
231 }
232 
233 /// Is this a call to an elemental procedure with at least one array argument?
234 static bool
235 isElementalProcWithArrayArgs(const Fortran::evaluate::ProcedureRef &procRef) {
236   if (procRef.IsElemental())
237     for (const std::optional<Fortran::evaluate::ActualArgument> &arg :
238          procRef.arguments())
239       if (arg && arg->Rank() != 0)
240         return true;
241   return false;
242 }
243 template <typename T>
244 static bool isElementalProcWithArrayArgs(const Fortran::evaluate::Expr<T> &) {
245   return false;
246 }
247 template <>
248 bool isElementalProcWithArrayArgs(const Fortran::lower::SomeExpr &x) {
249   if (const auto *procRef = std::get_if<Fortran::evaluate::ProcedureRef>(&x.u))
250     return isElementalProcWithArrayArgs(*procRef);
251   return false;
252 }
253 
254 /// Some auxiliary data for processing initialization in ScalarExprLowering
255 /// below. This is currently used for generating dense attributed global
256 /// arrays.
257 struct InitializerData {
258   explicit InitializerData(bool getRawVals = false) : genRawVals{getRawVals} {}
259   llvm::SmallVector<mlir::Attribute> rawVals; // initialization raw values
260   mlir::Type rawType; // Type of elements processed for rawVals vector.
261   bool genRawVals;    // generate the rawVals vector if set.
262 };
263 
264 /// If \p arg is the address of a function with a denoted host-association tuple
265 /// argument, then return the host-associations tuple value of the current
266 /// procedure. Otherwise, return nullptr.
267 static mlir::Value
268 argumentHostAssocs(Fortran::lower::AbstractConverter &converter,
269                    mlir::Value arg) {
270   if (auto addr = mlir::dyn_cast_or_null<fir::AddrOfOp>(arg.getDefiningOp())) {
271     auto &builder = converter.getFirOpBuilder();
272     if (auto funcOp = builder.getNamedFunction(addr.getSymbol()))
273       if (fir::anyFuncArgsHaveAttr(funcOp, fir::getHostAssocAttrName()))
274         return converter.hostAssocTupleValue();
275   }
276   return {};
277 }
278 
279 namespace {
280 
281 /// Lowering of Fortran::evaluate::Expr<T> expressions
282 class ScalarExprLowering {
283 public:
284   using ExtValue = fir::ExtendedValue;
285 
286   explicit ScalarExprLowering(mlir::Location loc,
287                               Fortran::lower::AbstractConverter &converter,
288                               Fortran::lower::SymMap &symMap,
289                               Fortran::lower::StatementContext &stmtCtx,
290                               InitializerData *initializer = nullptr)
291       : location{loc}, converter{converter},
292         builder{converter.getFirOpBuilder()}, stmtCtx{stmtCtx}, symMap{symMap} {
293   }
294 
295   ExtValue genExtAddr(const Fortran::lower::SomeExpr &expr) {
296     return gen(expr);
297   }
298 
299   /// Lower `expr` to be passed as a fir.box argument. Do not create a temp
300   /// for the expr if it is a variable that can be described as a fir.box.
301   ExtValue genBoxArg(const Fortran::lower::SomeExpr &expr) {
302     bool saveUseBoxArg = useBoxArg;
303     useBoxArg = true;
304     ExtValue result = gen(expr);
305     useBoxArg = saveUseBoxArg;
306     return result;
307   }
308 
309   ExtValue genExtValue(const Fortran::lower::SomeExpr &expr) {
310     return genval(expr);
311   }
312 
313   /// Lower an expression that is a pointer or an allocatable to a
314   /// MutableBoxValue.
315   fir::MutableBoxValue
316   genMutableBoxValue(const Fortran::lower::SomeExpr &expr) {
317     // Pointers and allocatables can only be:
318     //    - a simple designator "x"
319     //    - a component designator "a%b(i,j)%x"
320     //    - a function reference "foo()"
321     //    - result of NULL() or NULL(MOLD) intrinsic.
322     //    NULL() requires some context to be lowered, so it is not handled
323     //    here and must be lowered according to the context where it appears.
324     ExtValue exv = std::visit(
325         [&](const auto &x) { return genMutableBoxValueImpl(x); }, expr.u);
326     const fir::MutableBoxValue *mutableBox =
327         exv.getBoxOf<fir::MutableBoxValue>();
328     if (!mutableBox)
329       fir::emitFatalError(getLoc(), "expr was not lowered to MutableBoxValue");
330     return *mutableBox;
331   }
332 
333   template <typename T>
334   ExtValue genMutableBoxValueImpl(const T &) {
335     // NULL() case should not be handled here.
336     fir::emitFatalError(getLoc(), "NULL() must be lowered in its context");
337   }
338 
339   template <typename T>
340   ExtValue
341   genMutableBoxValueImpl(const Fortran::evaluate::FunctionRef<T> &funRef) {
342     return genRawProcedureRef(funRef, converter.genType(toEvExpr(funRef)));
343   }
344 
345   template <typename T>
346   ExtValue
347   genMutableBoxValueImpl(const Fortran::evaluate::Designator<T> &designator) {
348     return std::visit(
349         Fortran::common::visitors{
350             [&](const Fortran::evaluate::SymbolRef &sym) -> ExtValue {
351               return symMap.lookupSymbol(*sym).toExtendedValue();
352             },
353             [&](const Fortran::evaluate::Component &comp) -> ExtValue {
354               return genComponent(comp);
355             },
356             [&](const auto &) -> ExtValue {
357               fir::emitFatalError(getLoc(),
358                                   "not an allocatable or pointer designator");
359             }},
360         designator.u);
361   }
362 
363   template <typename T>
364   ExtValue genMutableBoxValueImpl(const Fortran::evaluate::Expr<T> &expr) {
365     return std::visit([&](const auto &x) { return genMutableBoxValueImpl(x); },
366                       expr.u);
367   }
368 
369   mlir::Location getLoc() { return location; }
370 
371   template <typename A>
372   mlir::Value genunbox(const A &expr) {
373     ExtValue e = genval(expr);
374     if (const fir::UnboxedValue *r = e.getUnboxed())
375       return *r;
376     fir::emitFatalError(getLoc(), "unboxed expression expected");
377   }
378 
379   /// Generate an integral constant of `value`
380   template <int KIND>
381   mlir::Value genIntegerConstant(mlir::MLIRContext *context,
382                                  std::int64_t value) {
383     mlir::Type type =
384         converter.genType(Fortran::common::TypeCategory::Integer, KIND);
385     return builder.createIntegerConstant(getLoc(), type, value);
386   }
387 
388   /// Generate a logical/boolean constant of `value`
389   mlir::Value genBoolConstant(bool value) {
390     return builder.createBool(getLoc(), value);
391   }
392 
393   /// Generate a real constant with a value `value`.
394   template <int KIND>
395   mlir::Value genRealConstant(mlir::MLIRContext *context,
396                               const llvm::APFloat &value) {
397     mlir::Type fltTy = Fortran::lower::convertReal(context, KIND);
398     return builder.createRealConstant(getLoc(), fltTy, value);
399   }
400 
401   template <typename OpTy>
402   mlir::Value createCompareOp(mlir::arith::CmpIPredicate pred,
403                               const ExtValue &left, const ExtValue &right) {
404     if (const fir::UnboxedValue *lhs = left.getUnboxed())
405       if (const fir::UnboxedValue *rhs = right.getUnboxed())
406         return builder.create<OpTy>(getLoc(), pred, *lhs, *rhs);
407     fir::emitFatalError(getLoc(), "array compare should be handled in genarr");
408   }
409   template <typename OpTy, typename A>
410   mlir::Value createCompareOp(const A &ex, mlir::arith::CmpIPredicate pred) {
411     ExtValue left = genval(ex.left());
412     return createCompareOp<OpTy>(pred, left, genval(ex.right()));
413   }
414 
415   template <typename OpTy>
416   mlir::Value createFltCmpOp(mlir::arith::CmpFPredicate pred,
417                              const ExtValue &left, const ExtValue &right) {
418     if (const fir::UnboxedValue *lhs = left.getUnboxed())
419       if (const fir::UnboxedValue *rhs = right.getUnboxed())
420         return builder.create<OpTy>(getLoc(), pred, *lhs, *rhs);
421     fir::emitFatalError(getLoc(), "array compare should be handled in genarr");
422   }
423   template <typename OpTy, typename A>
424   mlir::Value createFltCmpOp(const A &ex, mlir::arith::CmpFPredicate pred) {
425     ExtValue left = genval(ex.left());
426     return createFltCmpOp<OpTy>(pred, left, genval(ex.right()));
427   }
428 
429   /// Returns a reference to a symbol or its box/boxChar descriptor if it has
430   /// one.
431   ExtValue gen(Fortran::semantics::SymbolRef sym) {
432     if (Fortran::lower::SymbolBox val = symMap.lookupSymbol(sym))
433       return val.match(
434           [&](const Fortran::lower::SymbolBox::PointerOrAllocatable &boxAddr) {
435             return fir::factory::genMutableBoxRead(builder, getLoc(), boxAddr);
436           },
437           [&val](auto &) { return val.toExtendedValue(); });
438     LLVM_DEBUG(llvm::dbgs()
439                << "unknown symbol: " << sym << "\nmap: " << symMap << '\n');
440     fir::emitFatalError(getLoc(), "symbol is not mapped to any IR value");
441   }
442 
443   ExtValue genLoad(const ExtValue &exv) {
444     return ::genLoad(builder, getLoc(), exv);
445   }
446 
447   ExtValue genval(Fortran::semantics::SymbolRef sym) {
448     ExtValue var = gen(sym);
449     if (const fir::UnboxedValue *s = var.getUnboxed())
450       if (fir::isReferenceLike(s->getType()))
451         return genLoad(*s);
452     return var;
453   }
454 
455   ExtValue genval(const Fortran::evaluate::BOZLiteralConstant &) {
456     TODO(getLoc(), "genval BOZ");
457   }
458 
459   /// Return indirection to function designated in ProcedureDesignator.
460   /// The type of the function indirection is not guaranteed to match the one
461   /// of the ProcedureDesignator due to Fortran implicit typing rules.
462   ExtValue genval(const Fortran::evaluate::ProcedureDesignator &proc) {
463     TODO(getLoc(), "genval ProcedureDesignator");
464   }
465 
466   ExtValue genval(const Fortran::evaluate::NullPointer &) {
467     TODO(getLoc(), "genval NullPointer");
468   }
469 
470   ExtValue genval(const Fortran::evaluate::StructureConstructor &ctor) {
471     TODO(getLoc(), "genval StructureConstructor");
472   }
473 
474   /// Lowering of an <i>ac-do-variable</i>, which is not a Symbol.
475   ExtValue genval(const Fortran::evaluate::ImpliedDoIndex &var) {
476     TODO(getLoc(), "genval ImpliedDoIndex");
477   }
478 
479   ExtValue genval(const Fortran::evaluate::DescriptorInquiry &desc) {
480     TODO(getLoc(), "genval DescriptorInquiry");
481   }
482 
483   ExtValue genval(const Fortran::evaluate::TypeParamInquiry &) {
484     TODO(getLoc(), "genval TypeParamInquiry");
485   }
486 
487   template <int KIND>
488   ExtValue genval(const Fortran::evaluate::ComplexComponent<KIND> &part) {
489     TODO(getLoc(), "genval ComplexComponent");
490   }
491 
492   template <int KIND>
493   ExtValue genval(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
494                       Fortran::common::TypeCategory::Integer, KIND>> &op) {
495     mlir::Value input = genunbox(op.left());
496     // Like LLVM, integer negation is the binary op "0 - value"
497     mlir::Value zero = genIntegerConstant<KIND>(builder.getContext(), 0);
498     return builder.create<mlir::arith::SubIOp>(getLoc(), zero, input);
499   }
500 
501   template <int KIND>
502   ExtValue genval(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
503                       Fortran::common::TypeCategory::Real, KIND>> &op) {
504     return builder.create<mlir::arith::NegFOp>(getLoc(), genunbox(op.left()));
505   }
506   template <int KIND>
507   ExtValue genval(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
508                       Fortran::common::TypeCategory::Complex, KIND>> &op) {
509     return builder.create<fir::NegcOp>(getLoc(), genunbox(op.left()));
510   }
511 
512   template <typename OpTy>
513   mlir::Value createBinaryOp(const ExtValue &left, const ExtValue &right) {
514     assert(fir::isUnboxedValue(left) && fir::isUnboxedValue(right));
515     mlir::Value lhs = fir::getBase(left);
516     mlir::Value rhs = fir::getBase(right);
517     assert(lhs.getType() == rhs.getType() && "types must be the same");
518     return builder.create<OpTy>(getLoc(), lhs, rhs);
519   }
520 
521   template <typename OpTy, typename A>
522   mlir::Value createBinaryOp(const A &ex) {
523     ExtValue left = genval(ex.left());
524     return createBinaryOp<OpTy>(left, genval(ex.right()));
525   }
526 
527 #undef GENBIN
528 #define GENBIN(GenBinEvOp, GenBinTyCat, GenBinFirOp)                           \
529   template <int KIND>                                                          \
530   ExtValue genval(const Fortran::evaluate::GenBinEvOp<Fortran::evaluate::Type< \
531                       Fortran::common::TypeCategory::GenBinTyCat, KIND>> &x) { \
532     return createBinaryOp<GenBinFirOp>(x);                                     \
533   }
534 
535   GENBIN(Add, Integer, mlir::arith::AddIOp)
536   GENBIN(Add, Real, mlir::arith::AddFOp)
537   GENBIN(Add, Complex, fir::AddcOp)
538   GENBIN(Subtract, Integer, mlir::arith::SubIOp)
539   GENBIN(Subtract, Real, mlir::arith::SubFOp)
540   GENBIN(Subtract, Complex, fir::SubcOp)
541   GENBIN(Multiply, Integer, mlir::arith::MulIOp)
542   GENBIN(Multiply, Real, mlir::arith::MulFOp)
543   GENBIN(Multiply, Complex, fir::MulcOp)
544   GENBIN(Divide, Integer, mlir::arith::DivSIOp)
545   GENBIN(Divide, Real, mlir::arith::DivFOp)
546   GENBIN(Divide, Complex, fir::DivcOp)
547 
548   template <Fortran::common::TypeCategory TC, int KIND>
549   ExtValue genval(
550       const Fortran::evaluate::Power<Fortran::evaluate::Type<TC, KIND>> &op) {
551     mlir::Type ty = converter.genType(TC, KIND);
552     mlir::Value lhs = genunbox(op.left());
553     mlir::Value rhs = genunbox(op.right());
554     return Fortran::lower::genPow(builder, getLoc(), ty, lhs, rhs);
555   }
556 
557   template <Fortran::common::TypeCategory TC, int KIND>
558   ExtValue genval(
559       const Fortran::evaluate::RealToIntPower<Fortran::evaluate::Type<TC, KIND>>
560           &op) {
561     mlir::Type ty = converter.genType(TC, KIND);
562     mlir::Value lhs = genunbox(op.left());
563     mlir::Value rhs = genunbox(op.right());
564     return Fortran::lower::genPow(builder, getLoc(), ty, lhs, rhs);
565   }
566 
567   template <int KIND>
568   ExtValue genval(const Fortran::evaluate::ComplexConstructor<KIND> &op) {
569     mlir::Value realPartValue = genunbox(op.left());
570     return fir::factory::Complex{builder, getLoc()}.createComplex(
571         KIND, realPartValue, genunbox(op.right()));
572   }
573 
574   template <int KIND>
575   ExtValue genval(const Fortran::evaluate::Concat<KIND> &op) {
576     TODO(getLoc(), "genval Concat<KIND>");
577   }
578 
579   /// MIN and MAX operations
580   template <Fortran::common::TypeCategory TC, int KIND>
581   ExtValue
582   genval(const Fortran::evaluate::Extremum<Fortran::evaluate::Type<TC, KIND>>
583              &op) {
584     TODO(getLoc(), "genval Extremum<TC, KIND>");
585   }
586 
587   template <int KIND>
588   ExtValue genval(const Fortran::evaluate::SetLength<KIND> &x) {
589     TODO(getLoc(), "genval SetLength<KIND>");
590   }
591 
592   template <int KIND>
593   ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
594                       Fortran::common::TypeCategory::Integer, KIND>> &op) {
595     return createCompareOp<mlir::arith::CmpIOp>(op,
596                                                 translateRelational(op.opr));
597   }
598   template <int KIND>
599   ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
600                       Fortran::common::TypeCategory::Real, KIND>> &op) {
601     return createFltCmpOp<mlir::arith::CmpFOp>(
602         op, translateFloatRelational(op.opr));
603   }
604   template <int KIND>
605   ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
606                       Fortran::common::TypeCategory::Complex, KIND>> &op) {
607     TODO(getLoc(), "genval complex comparison");
608   }
609   template <int KIND>
610   ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
611                       Fortran::common::TypeCategory::Character, KIND>> &op) {
612     TODO(getLoc(), "genval char comparison");
613   }
614 
615   ExtValue
616   genval(const Fortran::evaluate::Relational<Fortran::evaluate::SomeType> &op) {
617     return std::visit([&](const auto &x) { return genval(x); }, op.u);
618   }
619 
620   template <Fortran::common::TypeCategory TC1, int KIND,
621             Fortran::common::TypeCategory TC2>
622   ExtValue
623   genval(const Fortran::evaluate::Convert<Fortran::evaluate::Type<TC1, KIND>,
624                                           TC2> &convert) {
625     mlir::Type ty = converter.genType(TC1, KIND);
626     mlir::Value operand = genunbox(convert.left());
627     return builder.convertWithSemantics(getLoc(), ty, operand);
628   }
629 
630   template <typename A>
631   ExtValue genval(const Fortran::evaluate::Parentheses<A> &op) {
632     TODO(getLoc(), "genval parentheses<A>");
633   }
634 
635   template <int KIND>
636   ExtValue genval(const Fortran::evaluate::Not<KIND> &op) {
637     mlir::Value logical = genunbox(op.left());
638     mlir::Value one = genBoolConstant(true);
639     mlir::Value val =
640         builder.createConvert(getLoc(), builder.getI1Type(), logical);
641     return builder.create<mlir::arith::XOrIOp>(getLoc(), val, one);
642   }
643 
644   template <int KIND>
645   ExtValue genval(const Fortran::evaluate::LogicalOperation<KIND> &op) {
646     mlir::IntegerType i1Type = builder.getI1Type();
647     mlir::Value slhs = genunbox(op.left());
648     mlir::Value srhs = genunbox(op.right());
649     mlir::Value lhs = builder.createConvert(getLoc(), i1Type, slhs);
650     mlir::Value rhs = builder.createConvert(getLoc(), i1Type, srhs);
651     switch (op.logicalOperator) {
652     case Fortran::evaluate::LogicalOperator::And:
653       return createBinaryOp<mlir::arith::AndIOp>(lhs, rhs);
654     case Fortran::evaluate::LogicalOperator::Or:
655       return createBinaryOp<mlir::arith::OrIOp>(lhs, rhs);
656     case Fortran::evaluate::LogicalOperator::Eqv:
657       return createCompareOp<mlir::arith::CmpIOp>(
658           mlir::arith::CmpIPredicate::eq, lhs, rhs);
659     case Fortran::evaluate::LogicalOperator::Neqv:
660       return createCompareOp<mlir::arith::CmpIOp>(
661           mlir::arith::CmpIPredicate::ne, lhs, rhs);
662     case Fortran::evaluate::LogicalOperator::Not:
663       // lib/evaluate expression for .NOT. is Fortran::evaluate::Not<KIND>.
664       llvm_unreachable(".NOT. is not a binary operator");
665     }
666     llvm_unreachable("unhandled logical operation");
667   }
668 
669   /// Convert a scalar literal constant to IR.
670   template <Fortran::common::TypeCategory TC, int KIND>
671   ExtValue genScalarLit(
672       const Fortran::evaluate::Scalar<Fortran::evaluate::Type<TC, KIND>>
673           &value) {
674     if constexpr (TC == Fortran::common::TypeCategory::Integer) {
675       return genIntegerConstant<KIND>(builder.getContext(), value.ToInt64());
676     } else if constexpr (TC == Fortran::common::TypeCategory::Logical) {
677       return genBoolConstant(value.IsTrue());
678     } else if constexpr (TC == Fortran::common::TypeCategory::Real) {
679       std::string str = value.DumpHexadecimal();
680       if constexpr (KIND == 2) {
681         llvm::APFloat floatVal{llvm::APFloatBase::IEEEhalf(), str};
682         return genRealConstant<KIND>(builder.getContext(), floatVal);
683       } else if constexpr (KIND == 3) {
684         llvm::APFloat floatVal{llvm::APFloatBase::BFloat(), str};
685         return genRealConstant<KIND>(builder.getContext(), floatVal);
686       } else if constexpr (KIND == 4) {
687         llvm::APFloat floatVal{llvm::APFloatBase::IEEEsingle(), str};
688         return genRealConstant<KIND>(builder.getContext(), floatVal);
689       } else if constexpr (KIND == 10) {
690         llvm::APFloat floatVal{llvm::APFloatBase::x87DoubleExtended(), str};
691         return genRealConstant<KIND>(builder.getContext(), floatVal);
692       } else if constexpr (KIND == 16) {
693         llvm::APFloat floatVal{llvm::APFloatBase::IEEEquad(), str};
694         return genRealConstant<KIND>(builder.getContext(), floatVal);
695       } else {
696         // convert everything else to double
697         llvm::APFloat floatVal{llvm::APFloatBase::IEEEdouble(), str};
698         return genRealConstant<KIND>(builder.getContext(), floatVal);
699       }
700     } else if constexpr (TC == Fortran::common::TypeCategory::Complex) {
701       using TR =
702           Fortran::evaluate::Type<Fortran::common::TypeCategory::Real, KIND>;
703       Fortran::evaluate::ComplexConstructor<KIND> ctor(
704           Fortran::evaluate::Expr<TR>{
705               Fortran::evaluate::Constant<TR>{value.REAL()}},
706           Fortran::evaluate::Expr<TR>{
707               Fortran::evaluate::Constant<TR>{value.AIMAG()}});
708       return genunbox(ctor);
709     } else /*constexpr*/ {
710       llvm_unreachable("unhandled constant");
711     }
712   }
713 
714   /// Convert a ascii scalar literal CHARACTER to IR. (specialization)
715   ExtValue
716   genAsciiScalarLit(const Fortran::evaluate::Scalar<Fortran::evaluate::Type<
717                         Fortran::common::TypeCategory::Character, 1>> &value,
718                     int64_t len) {
719     assert(value.size() == static_cast<std::uint64_t>(len) &&
720            "value.size() doesn't match with len");
721     return fir::factory::createStringLiteral(builder, getLoc(), value);
722   }
723 
724   template <Fortran::common::TypeCategory TC, int KIND>
725   ExtValue
726   genval(const Fortran::evaluate::Constant<Fortran::evaluate::Type<TC, KIND>>
727              &con) {
728     if (con.Rank() > 0)
729       TODO(getLoc(), "genval array constant");
730     std::optional<Fortran::evaluate::Scalar<Fortran::evaluate::Type<TC, KIND>>>
731         opt = con.GetScalarValue();
732     assert(opt.has_value() && "constant has no value");
733     if constexpr (TC == Fortran::common::TypeCategory::Character) {
734       if constexpr (KIND == 1)
735         return genAsciiScalarLit(opt.value(), con.LEN());
736       TODO(getLoc(), "genval for Character with KIND != 1");
737     } else {
738       return genScalarLit<TC, KIND>(opt.value());
739     }
740   }
741 
742   fir::ExtendedValue genval(
743       const Fortran::evaluate::Constant<Fortran::evaluate::SomeDerived> &con) {
744     TODO(getLoc(), "genval constant derived");
745   }
746 
747   template <typename A>
748   ExtValue genval(const Fortran::evaluate::ArrayConstructor<A> &) {
749     TODO(getLoc(), "genval ArrayConstructor<A>");
750   }
751 
752   ExtValue gen(const Fortran::evaluate::ComplexPart &x) {
753     TODO(getLoc(), "gen ComplexPart");
754   }
755   ExtValue genval(const Fortran::evaluate::ComplexPart &x) {
756     TODO(getLoc(), "genval ComplexPart");
757   }
758 
759   ExtValue gen(const Fortran::evaluate::Substring &s) {
760     TODO(getLoc(), "gen Substring");
761   }
762   ExtValue genval(const Fortran::evaluate::Substring &ss) {
763     TODO(getLoc(), "genval Substring");
764   }
765 
766   ExtValue genval(const Fortran::evaluate::Subscript &subs) {
767     if (auto *s = std::get_if<Fortran::evaluate::IndirectSubscriptIntegerExpr>(
768             &subs.u)) {
769       if (s->value().Rank() > 0)
770         fir::emitFatalError(getLoc(), "vector subscript is not scalar");
771       return {genval(s->value())};
772     }
773     fir::emitFatalError(getLoc(), "subscript triple notation is not scalar");
774   }
775 
776   ExtValue genSubscript(const Fortran::evaluate::Subscript &subs) {
777     return genval(subs);
778   }
779 
780   ExtValue gen(const Fortran::evaluate::DataRef &dref) {
781     TODO(getLoc(), "gen DataRef");
782   }
783   ExtValue genval(const Fortran::evaluate::DataRef &dref) {
784     TODO(getLoc(), "genval DataRef");
785   }
786 
787   // Helper function to turn the Component structure into a list of nested
788   // components, ordered from largest/leftmost to smallest/rightmost:
789   //  - where only the smallest/rightmost item may be allocatable or a pointer
790   //    (nested allocatable/pointer components require nested coordinate_of ops)
791   //  - that does not contain any parent components
792   //    (the front end places parent components directly in the object)
793   // Return the object used as the base coordinate for the component chain.
794   static Fortran::evaluate::DataRef const *
795   reverseComponents(const Fortran::evaluate::Component &cmpt,
796                     std::list<const Fortran::evaluate::Component *> &list) {
797     if (!cmpt.GetLastSymbol().test(
798             Fortran::semantics::Symbol::Flag::ParentComp))
799       list.push_front(&cmpt);
800     return std::visit(
801         Fortran::common::visitors{
802             [&](const Fortran::evaluate::Component &x) {
803               if (Fortran::semantics::IsAllocatableOrPointer(x.GetLastSymbol()))
804                 return &cmpt.base();
805               return reverseComponents(x, list);
806             },
807             [&](auto &) { return &cmpt.base(); },
808         },
809         cmpt.base().u);
810   }
811 
812   // Return the coordinate of the component reference
813   ExtValue genComponent(const Fortran::evaluate::Component &cmpt) {
814     std::list<const Fortran::evaluate::Component *> list;
815     const Fortran::evaluate::DataRef *base = reverseComponents(cmpt, list);
816     llvm::SmallVector<mlir::Value> coorArgs;
817     ExtValue obj = gen(*base);
818     mlir::Type ty = fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(obj).getType());
819     mlir::Location loc = getLoc();
820     auto fldTy = fir::FieldType::get(&converter.getMLIRContext());
821     // FIXME: need to thread the LEN type parameters here.
822     for (const Fortran::evaluate::Component *field : list) {
823       auto recTy = ty.cast<fir::RecordType>();
824       const Fortran::semantics::Symbol &sym = field->GetLastSymbol();
825       llvm::StringRef name = toStringRef(sym.name());
826       coorArgs.push_back(builder.create<fir::FieldIndexOp>(
827           loc, fldTy, name, recTy, fir::getTypeParams(obj)));
828       ty = recTy.getType(name);
829     }
830     ty = builder.getRefType(ty);
831     return fir::factory::componentToExtendedValue(
832         builder, loc,
833         builder.create<fir::CoordinateOp>(loc, ty, fir::getBase(obj),
834                                           coorArgs));
835   }
836 
837   ExtValue gen(const Fortran::evaluate::Component &cmpt) {
838     TODO(getLoc(), "gen Component");
839   }
840   ExtValue genval(const Fortran::evaluate::Component &cmpt) {
841     TODO(getLoc(), "genval Component");
842   }
843 
844   ExtValue genval(const Fortran::semantics::Bound &bound) {
845     TODO(getLoc(), "genval Bound");
846   }
847 
848   /// Return lower bounds of \p box in dimension \p dim. The returned value
849   /// has type \ty.
850   mlir::Value getLBound(const ExtValue &box, unsigned dim, mlir::Type ty) {
851     assert(box.rank() > 0 && "must be an array");
852     mlir::Location loc = getLoc();
853     mlir::Value one = builder.createIntegerConstant(loc, ty, 1);
854     mlir::Value lb = fir::factory::readLowerBound(builder, loc, box, dim, one);
855     return builder.createConvert(loc, ty, lb);
856   }
857 
858   static bool isSlice(const Fortran::evaluate::ArrayRef &aref) {
859     for (const Fortran::evaluate::Subscript &sub : aref.subscript())
860       if (std::holds_alternative<Fortran::evaluate::Triplet>(sub.u))
861         return true;
862     return false;
863   }
864 
865   /// Lower an ArrayRef to a fir.coordinate_of given its lowered base.
866   ExtValue genCoordinateOp(const ExtValue &array,
867                            const Fortran::evaluate::ArrayRef &aref) {
868     mlir::Location loc = getLoc();
869     // References to array of rank > 1 with non constant shape that are not
870     // fir.box must be collapsed into an offset computation in lowering already.
871     // The same is needed with dynamic length character arrays of all ranks.
872     mlir::Type baseType =
873         fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(array).getType());
874     if ((array.rank() > 1 && fir::hasDynamicSize(baseType)) ||
875         fir::characterWithDynamicLen(fir::unwrapSequenceType(baseType)))
876       if (!array.getBoxOf<fir::BoxValue>())
877         return genOffsetAndCoordinateOp(array, aref);
878     // Generate a fir.coordinate_of with zero based array indexes.
879     llvm::SmallVector<mlir::Value> args;
880     for (const auto &subsc : llvm::enumerate(aref.subscript())) {
881       ExtValue subVal = genSubscript(subsc.value());
882       assert(fir::isUnboxedValue(subVal) && "subscript must be simple scalar");
883       mlir::Value val = fir::getBase(subVal);
884       mlir::Type ty = val.getType();
885       mlir::Value lb = getLBound(array, subsc.index(), ty);
886       args.push_back(builder.create<mlir::arith::SubIOp>(loc, ty, val, lb));
887     }
888 
889     mlir::Value base = fir::getBase(array);
890     auto seqTy =
891         fir::dyn_cast_ptrOrBoxEleTy(base.getType()).cast<fir::SequenceType>();
892     assert(args.size() == seqTy.getDimension());
893     mlir::Type ty = builder.getRefType(seqTy.getEleTy());
894     auto addr = builder.create<fir::CoordinateOp>(loc, ty, base, args);
895     return fir::factory::arrayElementToExtendedValue(builder, loc, array, addr);
896   }
897 
898   /// Lower an ArrayRef to a fir.coordinate_of using an element offset instead
899   /// of array indexes.
900   /// This generates offset computation from the indexes and length parameters,
901   /// and use the offset to access the element with a fir.coordinate_of. This
902   /// must only be used if it is not possible to generate a normal
903   /// fir.coordinate_of using array indexes (i.e. when the shape information is
904   /// unavailable in the IR).
905   ExtValue genOffsetAndCoordinateOp(const ExtValue &array,
906                                     const Fortran::evaluate::ArrayRef &aref) {
907     mlir::Location loc = getLoc();
908     mlir::Value addr = fir::getBase(array);
909     mlir::Type arrTy = fir::dyn_cast_ptrEleTy(addr.getType());
910     auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy();
911     mlir::Type seqTy = builder.getRefType(builder.getVarLenSeqTy(eleTy));
912     mlir::Type refTy = builder.getRefType(eleTy);
913     mlir::Value base = builder.createConvert(loc, seqTy, addr);
914     mlir::IndexType idxTy = builder.getIndexType();
915     mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
916     mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
917     auto getLB = [&](const auto &arr, unsigned dim) -> mlir::Value {
918       return arr.getLBounds().empty() ? one : arr.getLBounds()[dim];
919     };
920     auto genFullDim = [&](const auto &arr, mlir::Value delta) -> mlir::Value {
921       mlir::Value total = zero;
922       assert(arr.getExtents().size() == aref.subscript().size());
923       delta = builder.createConvert(loc, idxTy, delta);
924       unsigned dim = 0;
925       for (auto [ext, sub] : llvm::zip(arr.getExtents(), aref.subscript())) {
926         ExtValue subVal = genSubscript(sub);
927         assert(fir::isUnboxedValue(subVal));
928         mlir::Value val =
929             builder.createConvert(loc, idxTy, fir::getBase(subVal));
930         mlir::Value lb = builder.createConvert(loc, idxTy, getLB(arr, dim));
931         mlir::Value diff = builder.create<mlir::arith::SubIOp>(loc, val, lb);
932         mlir::Value prod =
933             builder.create<mlir::arith::MulIOp>(loc, delta, diff);
934         total = builder.create<mlir::arith::AddIOp>(loc, prod, total);
935         if (ext)
936           delta = builder.create<mlir::arith::MulIOp>(loc, delta, ext);
937         ++dim;
938       }
939       mlir::Type origRefTy = refTy;
940       if (fir::factory::CharacterExprHelper::isCharacterScalar(refTy)) {
941         fir::CharacterType chTy =
942             fir::factory::CharacterExprHelper::getCharacterType(refTy);
943         if (fir::characterWithDynamicLen(chTy)) {
944           mlir::MLIRContext *ctx = builder.getContext();
945           fir::KindTy kind =
946               fir::factory::CharacterExprHelper::getCharacterKind(chTy);
947           fir::CharacterType singleTy =
948               fir::CharacterType::getSingleton(ctx, kind);
949           refTy = builder.getRefType(singleTy);
950           mlir::Type seqRefTy =
951               builder.getRefType(builder.getVarLenSeqTy(singleTy));
952           base = builder.createConvert(loc, seqRefTy, base);
953         }
954       }
955       auto coor = builder.create<fir::CoordinateOp>(
956           loc, refTy, base, llvm::ArrayRef<mlir::Value>{total});
957       // Convert to expected, original type after address arithmetic.
958       return builder.createConvert(loc, origRefTy, coor);
959     };
960     return array.match(
961         [&](const fir::ArrayBoxValue &arr) -> ExtValue {
962           // FIXME: this check can be removed when slicing is implemented
963           if (isSlice(aref))
964             fir::emitFatalError(
965                 getLoc(),
966                 "slice should be handled in array expression context");
967           return genFullDim(arr, one);
968         },
969         [&](const fir::CharArrayBoxValue &arr) -> ExtValue {
970           mlir::Value delta = arr.getLen();
971           // If the length is known in the type, fir.coordinate_of will
972           // already take the length into account.
973           if (fir::factory::CharacterExprHelper::hasConstantLengthInType(arr))
974             delta = one;
975           return fir::CharBoxValue(genFullDim(arr, delta), arr.getLen());
976         },
977         [&](const fir::BoxValue &arr) -> ExtValue {
978           // CoordinateOp for BoxValue is not generated here. The dimensions
979           // must be kept in the fir.coordinate_op so that potential fir.box
980           // strides can be applied by codegen.
981           fir::emitFatalError(
982               loc, "internal: BoxValue in dim-collapsed fir.coordinate_of");
983         },
984         [&](const auto &) -> ExtValue {
985           fir::emitFatalError(loc, "internal: array lowering failed");
986         });
987   }
988 
989   ExtValue gen(const Fortran::evaluate::ArrayRef &aref) {
990     ExtValue base = aref.base().IsSymbol() ? gen(aref.base().GetFirstSymbol())
991                                            : gen(aref.base().GetComponent());
992     return genCoordinateOp(base, aref);
993   }
994   ExtValue genval(const Fortran::evaluate::ArrayRef &aref) {
995     return genLoad(gen(aref));
996   }
997 
998   ExtValue gen(const Fortran::evaluate::CoarrayRef &coref) {
999     TODO(getLoc(), "gen CoarrayRef");
1000   }
1001   ExtValue genval(const Fortran::evaluate::CoarrayRef &coref) {
1002     TODO(getLoc(), "genval CoarrayRef");
1003   }
1004 
1005   template <typename A>
1006   ExtValue gen(const Fortran::evaluate::Designator<A> &des) {
1007     return std::visit([&](const auto &x) { return gen(x); }, des.u);
1008   }
1009   template <typename A>
1010   ExtValue genval(const Fortran::evaluate::Designator<A> &des) {
1011     return std::visit([&](const auto &x) { return genval(x); }, des.u);
1012   }
1013 
1014   mlir::Type genType(const Fortran::evaluate::DynamicType &dt) {
1015     if (dt.category() != Fortran::common::TypeCategory::Derived)
1016       return converter.genType(dt.category(), dt.kind());
1017     TODO(getLoc(), "genType Derived Type");
1018   }
1019 
1020   /// Lower a function reference
1021   template <typename A>
1022   ExtValue genFunctionRef(const Fortran::evaluate::FunctionRef<A> &funcRef) {
1023     if (!funcRef.GetType().has_value())
1024       fir::emitFatalError(getLoc(), "internal: a function must have a type");
1025     mlir::Type resTy = genType(*funcRef.GetType());
1026     return genProcedureRef(funcRef, {resTy});
1027   }
1028 
1029   /// Lower function call `funcRef` and return a reference to the resultant
1030   /// value. This is required for lowering expressions such as `f1(f2(v))`.
1031   template <typename A>
1032   ExtValue gen(const Fortran::evaluate::FunctionRef<A> &funcRef) {
1033     TODO(getLoc(), "gen FunctionRef<A>");
1034   }
1035 
1036   /// helper to detect statement functions
1037   static bool
1038   isStatementFunctionCall(const Fortran::evaluate::ProcedureRef &procRef) {
1039     if (const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol())
1040       if (const auto *details =
1041               symbol->detailsIf<Fortran::semantics::SubprogramDetails>())
1042         return details->stmtFunction().has_value();
1043     return false;
1044   }
1045 
1046   /// Helper to package a Value and its properties into an ExtendedValue.
1047   static ExtValue toExtendedValue(mlir::Location loc, mlir::Value base,
1048                                   llvm::ArrayRef<mlir::Value> extents,
1049                                   llvm::ArrayRef<mlir::Value> lengths) {
1050     mlir::Type type = base.getType();
1051     if (type.isa<fir::BoxType>())
1052       return fir::BoxValue(base, /*lbounds=*/{}, lengths, extents);
1053     type = fir::unwrapRefType(type);
1054     if (type.isa<fir::BoxType>())
1055       return fir::MutableBoxValue(base, lengths, /*mutableProperties*/ {});
1056     if (auto seqTy = type.dyn_cast<fir::SequenceType>()) {
1057       if (seqTy.getDimension() != extents.size())
1058         fir::emitFatalError(loc, "incorrect number of extents for array");
1059       if (seqTy.getEleTy().isa<fir::CharacterType>()) {
1060         if (lengths.empty())
1061           fir::emitFatalError(loc, "missing length for character");
1062         assert(lengths.size() == 1);
1063         return fir::CharArrayBoxValue(base, lengths[0], extents);
1064       }
1065       return fir::ArrayBoxValue(base, extents);
1066     }
1067     if (type.isa<fir::CharacterType>()) {
1068       if (lengths.empty())
1069         fir::emitFatalError(loc, "missing length for character");
1070       assert(lengths.size() == 1);
1071       return fir::CharBoxValue(base, lengths[0]);
1072     }
1073     return base;
1074   }
1075 
1076   // Find the argument that corresponds to the host associations.
1077   // Verify some assumptions about how the signature was built here.
1078   [[maybe_unused]] static unsigned findHostAssocTuplePos(mlir::FuncOp fn) {
1079     // Scan the argument list from last to first as the host associations are
1080     // appended for now.
1081     for (unsigned i = fn.getNumArguments(); i > 0; --i)
1082       if (fn.getArgAttr(i - 1, fir::getHostAssocAttrName())) {
1083         // Host assoc tuple must be last argument (for now).
1084         assert(i == fn.getNumArguments() && "tuple must be last");
1085         return i - 1;
1086       }
1087     llvm_unreachable("anyFuncArgsHaveAttr failed");
1088   }
1089 
1090   /// Lower a non-elemental procedure reference and read allocatable and pointer
1091   /// results into normal values.
1092   ExtValue genProcedureRef(const Fortran::evaluate::ProcedureRef &procRef,
1093                            llvm::Optional<mlir::Type> resultType) {
1094     ExtValue res = genRawProcedureRef(procRef, resultType);
1095     return res;
1096   }
1097 
1098   /// Given a call site for which the arguments were already lowered, generate
1099   /// the call and return the result. This function deals with explicit result
1100   /// allocation and lowering if needed. It also deals with passing the host
1101   /// link to internal procedures.
1102   ExtValue genCallOpAndResult(Fortran::lower::CallerInterface &caller,
1103                               mlir::FunctionType callSiteType,
1104                               llvm::Optional<mlir::Type> resultType) {
1105     mlir::Location loc = getLoc();
1106     using PassBy = Fortran::lower::CallerInterface::PassEntityBy;
1107     // Handle cases where caller must allocate the result or a fir.box for it.
1108     bool mustPopSymMap = false;
1109     if (caller.mustMapInterfaceSymbols()) {
1110       symMap.pushScope();
1111       mustPopSymMap = true;
1112       Fortran::lower::mapCallInterfaceSymbols(converter, caller, symMap);
1113     }
1114     // If this is an indirect call, retrieve the function address. Also retrieve
1115     // the result length if this is a character function (note that this length
1116     // will be used only if there is no explicit length in the local interface).
1117     mlir::Value funcPointer;
1118     mlir::Value charFuncPointerLength;
1119     if (caller.getIfIndirectCallSymbol()) {
1120       TODO(loc, "genCallOpAndResult indirect call");
1121     }
1122 
1123     mlir::IndexType idxTy = builder.getIndexType();
1124     auto lowerSpecExpr = [&](const auto &expr) -> mlir::Value {
1125       return builder.createConvert(
1126           loc, idxTy, fir::getBase(converter.genExprValue(expr, stmtCtx)));
1127     };
1128     llvm::SmallVector<mlir::Value> resultLengths;
1129     auto allocatedResult = [&]() -> llvm::Optional<ExtValue> {
1130       llvm::SmallVector<mlir::Value> extents;
1131       llvm::SmallVector<mlir::Value> lengths;
1132       if (!caller.callerAllocateResult())
1133         return {};
1134       mlir::Type type = caller.getResultStorageType();
1135       if (type.isa<fir::SequenceType>())
1136         caller.walkResultExtents([&](const Fortran::lower::SomeExpr &e) {
1137           extents.emplace_back(lowerSpecExpr(e));
1138         });
1139       caller.walkResultLengths([&](const Fortran::lower::SomeExpr &e) {
1140         lengths.emplace_back(lowerSpecExpr(e));
1141       });
1142 
1143       // Result length parameters should not be provided to box storage
1144       // allocation and save_results, but they are still useful information to
1145       // keep in the ExtendedValue if non-deferred.
1146       if (!type.isa<fir::BoxType>()) {
1147         if (fir::isa_char(fir::unwrapSequenceType(type)) && lengths.empty()) {
1148           // Calling an assumed length function. This is only possible if this
1149           // is a call to a character dummy procedure.
1150           if (!charFuncPointerLength)
1151             fir::emitFatalError(loc, "failed to retrieve character function "
1152                                      "length while calling it");
1153           lengths.push_back(charFuncPointerLength);
1154         }
1155         resultLengths = lengths;
1156       }
1157 
1158       if (!extents.empty() || !lengths.empty()) {
1159         TODO(loc, "genCallOpResult extents and length");
1160       }
1161       mlir::Value temp =
1162           builder.createTemporary(loc, type, ".result", extents, resultLengths);
1163       return toExtendedValue(loc, temp, extents, lengths);
1164     }();
1165 
1166     if (mustPopSymMap)
1167       symMap.popScope();
1168 
1169     // Place allocated result or prepare the fir.save_result arguments.
1170     mlir::Value arrayResultShape;
1171     if (allocatedResult) {
1172       if (std::optional<Fortran::lower::CallInterface<
1173               Fortran::lower::CallerInterface>::PassedEntity>
1174               resultArg = caller.getPassedResult()) {
1175         if (resultArg->passBy == PassBy::AddressAndLength)
1176           caller.placeAddressAndLengthInput(*resultArg,
1177                                             fir::getBase(*allocatedResult),
1178                                             fir::getLen(*allocatedResult));
1179         else if (resultArg->passBy == PassBy::BaseAddress)
1180           caller.placeInput(*resultArg, fir::getBase(*allocatedResult));
1181         else
1182           fir::emitFatalError(
1183               loc, "only expect character scalar result to be passed by ref");
1184       } else {
1185         assert(caller.mustSaveResult());
1186         arrayResultShape = allocatedResult->match(
1187             [&](const fir::CharArrayBoxValue &) {
1188               return builder.createShape(loc, *allocatedResult);
1189             },
1190             [&](const fir::ArrayBoxValue &) {
1191               return builder.createShape(loc, *allocatedResult);
1192             },
1193             [&](const auto &) { return mlir::Value{}; });
1194       }
1195     }
1196 
1197     // In older Fortran, procedure argument types are inferred. This may lead
1198     // different view of what the function signature is in different locations.
1199     // Casts are inserted as needed below to accommodate this.
1200 
1201     // The mlir::FuncOp type prevails, unless it has a different number of
1202     // arguments which can happen in legal program if it was passed as a dummy
1203     // procedure argument earlier with no further type information.
1204     mlir::SymbolRefAttr funcSymbolAttr;
1205     bool addHostAssociations = false;
1206     if (!funcPointer) {
1207       mlir::FunctionType funcOpType = caller.getFuncOp().getType();
1208       mlir::SymbolRefAttr symbolAttr =
1209           builder.getSymbolRefAttr(caller.getMangledName());
1210       if (callSiteType.getNumResults() == funcOpType.getNumResults() &&
1211           callSiteType.getNumInputs() + 1 == funcOpType.getNumInputs() &&
1212           fir::anyFuncArgsHaveAttr(caller.getFuncOp(),
1213                                    fir::getHostAssocAttrName())) {
1214         // The number of arguments is off by one, and we're lowering a function
1215         // with host associations. Modify call to include host associations
1216         // argument by appending the value at the end of the operands.
1217         assert(funcOpType.getInput(findHostAssocTuplePos(caller.getFuncOp())) ==
1218                converter.hostAssocTupleValue().getType());
1219         addHostAssociations = true;
1220       }
1221       if (!addHostAssociations &&
1222           (callSiteType.getNumResults() != funcOpType.getNumResults() ||
1223            callSiteType.getNumInputs() != funcOpType.getNumInputs())) {
1224         // Deal with argument number mismatch by making a function pointer so
1225         // that function type cast can be inserted. Do not emit a warning here
1226         // because this can happen in legal program if the function is not
1227         // defined here and it was first passed as an argument without any more
1228         // information.
1229         funcPointer =
1230             builder.create<fir::AddrOfOp>(loc, funcOpType, symbolAttr);
1231       } else if (callSiteType.getResults() != funcOpType.getResults()) {
1232         // Implicit interface result type mismatch are not standard Fortran, but
1233         // some compilers are not complaining about it.  The front end is not
1234         // protecting lowering from this currently. Support this with a
1235         // discouraging warning.
1236         LLVM_DEBUG(mlir::emitWarning(
1237             loc, "a return type mismatch is not standard compliant and may "
1238                  "lead to undefined behavior."));
1239         // Cast the actual function to the current caller implicit type because
1240         // that is the behavior we would get if we could not see the definition.
1241         funcPointer =
1242             builder.create<fir::AddrOfOp>(loc, funcOpType, symbolAttr);
1243       } else {
1244         funcSymbolAttr = symbolAttr;
1245       }
1246     }
1247 
1248     mlir::FunctionType funcType =
1249         funcPointer ? callSiteType : caller.getFuncOp().getType();
1250     llvm::SmallVector<mlir::Value> operands;
1251     // First operand of indirect call is the function pointer. Cast it to
1252     // required function type for the call to handle procedures that have a
1253     // compatible interface in Fortran, but that have different signatures in
1254     // FIR.
1255     if (funcPointer) {
1256       operands.push_back(
1257           funcPointer.getType().isa<fir::BoxProcType>()
1258               ? builder.create<fir::BoxAddrOp>(loc, funcType, funcPointer)
1259               : builder.createConvert(loc, funcType, funcPointer));
1260     }
1261 
1262     // Deal with potential mismatches in arguments types. Passing an array to a
1263     // scalar argument should for instance be tolerated here.
1264     bool callingImplicitInterface = caller.canBeCalledViaImplicitInterface();
1265     for (auto [fst, snd] :
1266          llvm::zip(caller.getInputs(), funcType.getInputs())) {
1267       // When passing arguments to a procedure that can be called an implicit
1268       // interface, allow character actual arguments to be passed to dummy
1269       // arguments of any type and vice versa
1270       mlir::Value cast;
1271       auto *context = builder.getContext();
1272       if (snd.isa<fir::BoxProcType>() &&
1273           fst.getType().isa<mlir::FunctionType>()) {
1274         auto funcTy = mlir::FunctionType::get(context, llvm::None, llvm::None);
1275         auto boxProcTy = builder.getBoxProcType(funcTy);
1276         if (mlir::Value host = argumentHostAssocs(converter, fst)) {
1277           cast = builder.create<fir::EmboxProcOp>(
1278               loc, boxProcTy, llvm::ArrayRef<mlir::Value>{fst, host});
1279         } else {
1280           cast = builder.create<fir::EmboxProcOp>(loc, boxProcTy, fst);
1281         }
1282       } else {
1283         cast = builder.convertWithSemantics(loc, snd, fst,
1284                                             callingImplicitInterface);
1285       }
1286       operands.push_back(cast);
1287     }
1288 
1289     // Add host associations as necessary.
1290     if (addHostAssociations)
1291       operands.push_back(converter.hostAssocTupleValue());
1292 
1293     auto call = builder.create<fir::CallOp>(loc, funcType.getResults(),
1294                                             funcSymbolAttr, operands);
1295 
1296     if (caller.mustSaveResult())
1297       builder.create<fir::SaveResultOp>(
1298           loc, call.getResult(0), fir::getBase(allocatedResult.getValue()),
1299           arrayResultShape, resultLengths);
1300 
1301     if (allocatedResult) {
1302       allocatedResult->match(
1303           [&](const fir::MutableBoxValue &box) {
1304             if (box.isAllocatable()) {
1305               TODO(loc, "allocatedResult for allocatable");
1306             }
1307           },
1308           [](const auto &) {});
1309       return *allocatedResult;
1310     }
1311 
1312     if (!resultType.hasValue())
1313       return mlir::Value{}; // subroutine call
1314     // For now, Fortran return values are implemented with a single MLIR
1315     // function return value.
1316     assert(call.getNumResults() == 1 &&
1317            "Expected exactly one result in FUNCTION call");
1318     return call.getResult(0);
1319   }
1320 
1321   /// Like genExtAddr, but ensure the address returned is a temporary even if \p
1322   /// expr is variable inside parentheses.
1323   ExtValue genTempExtAddr(const Fortran::lower::SomeExpr &expr) {
1324     // In general, genExtAddr might not create a temp for variable inside
1325     // parentheses to avoid creating array temporary in sub-expressions. It only
1326     // ensures the sub-expression is not re-associated with other parts of the
1327     // expression. In the call semantics, there is a difference between expr and
1328     // variable (see R1524). For expressions, a variable storage must not be
1329     // argument associated since it could be modified inside the call, or the
1330     // variable could also be modified by other means during the call.
1331     if (!isParenthesizedVariable(expr))
1332       return genExtAddr(expr);
1333     mlir::Location loc = getLoc();
1334     if (expr.Rank() > 0)
1335       TODO(loc, "genTempExtAddr array");
1336     return genExtValue(expr).match(
1337         [&](const fir::CharBoxValue &boxChar) -> ExtValue {
1338           TODO(loc, "genTempExtAddr CharBoxValue");
1339         },
1340         [&](const fir::UnboxedValue &v) -> ExtValue {
1341           mlir::Type type = v.getType();
1342           mlir::Value value = v;
1343           if (fir::isa_ref_type(type))
1344             value = builder.create<fir::LoadOp>(loc, value);
1345           mlir::Value temp = builder.createTemporary(loc, value.getType());
1346           builder.create<fir::StoreOp>(loc, value, temp);
1347           return temp;
1348         },
1349         [&](const fir::BoxValue &x) -> ExtValue {
1350           // Derived type scalar that may be polymorphic.
1351           assert(!x.hasRank() && x.isDerived());
1352           if (x.isDerivedWithLengthParameters())
1353             fir::emitFatalError(
1354                 loc, "making temps for derived type with length parameters");
1355           // TODO: polymorphic aspects should be kept but for now the temp
1356           // created always has the declared type.
1357           mlir::Value var =
1358               fir::getBase(fir::factory::readBoxValue(builder, loc, x));
1359           auto value = builder.create<fir::LoadOp>(loc, var);
1360           mlir::Value temp = builder.createTemporary(loc, value.getType());
1361           builder.create<fir::StoreOp>(loc, value, temp);
1362           return temp;
1363         },
1364         [&](const auto &) -> ExtValue {
1365           fir::emitFatalError(loc, "expr is not a scalar value");
1366         });
1367   }
1368 
1369   /// Helper structure to track potential copy-in of non contiguous variable
1370   /// argument into a contiguous temp. It is used to deallocate the temp that
1371   /// may have been created as well as to the copy-out from the temp to the
1372   /// variable after the call.
1373   struct CopyOutPair {
1374     ExtValue var;
1375     ExtValue temp;
1376     // Flag to indicate if the argument may have been modified by the
1377     // callee, in which case it must be copied-out to the variable.
1378     bool argMayBeModifiedByCall;
1379     // Optional boolean value that, if present and false, prevents
1380     // the copy-out and temp deallocation.
1381     llvm::Optional<mlir::Value> restrictCopyAndFreeAtRuntime;
1382   };
1383   using CopyOutPairs = llvm::SmallVector<CopyOutPair, 4>;
1384 
1385   /// Helper to read any fir::BoxValue into other fir::ExtendedValue categories
1386   /// not based on fir.box.
1387   /// This will lose any non contiguous stride information and dynamic type and
1388   /// should only be called if \p exv is known to be contiguous or if its base
1389   /// address will be replaced by a contiguous one. If \p exv is not a
1390   /// fir::BoxValue, this is a no-op.
1391   ExtValue readIfBoxValue(const ExtValue &exv) {
1392     if (const auto *box = exv.getBoxOf<fir::BoxValue>())
1393       return fir::factory::readBoxValue(builder, getLoc(), *box);
1394     return exv;
1395   }
1396 
1397   /// Lower a non-elemental procedure reference.
1398   ExtValue genRawProcedureRef(const Fortran::evaluate::ProcedureRef &procRef,
1399                               llvm::Optional<mlir::Type> resultType) {
1400     mlir::Location loc = getLoc();
1401     if (isElementalProcWithArrayArgs(procRef))
1402       fir::emitFatalError(loc, "trying to lower elemental procedure with array "
1403                                "arguments as normal procedure");
1404     if (const Fortran::evaluate::SpecificIntrinsic *intrinsic =
1405             procRef.proc().GetSpecificIntrinsic())
1406       return genIntrinsicRef(procRef, *intrinsic, resultType);
1407 
1408     if (isStatementFunctionCall(procRef))
1409       TODO(loc, "Lower statement function call");
1410 
1411     Fortran::lower::CallerInterface caller(procRef, converter);
1412     using PassBy = Fortran::lower::CallerInterface::PassEntityBy;
1413 
1414     llvm::SmallVector<fir::MutableBoxValue> mutableModifiedByCall;
1415     // List of <var, temp> where temp must be copied into var after the call.
1416     CopyOutPairs copyOutPairs;
1417 
1418     mlir::FunctionType callSiteType = caller.genFunctionType();
1419 
1420     // Lower the actual arguments and map the lowered values to the dummy
1421     // arguments.
1422     for (const Fortran::lower::CallInterface<
1423              Fortran::lower::CallerInterface>::PassedEntity &arg :
1424          caller.getPassedArguments()) {
1425       const auto *actual = arg.entity;
1426       mlir::Type argTy = callSiteType.getInput(arg.firArgument);
1427       if (!actual) {
1428         // Optional dummy argument for which there is no actual argument.
1429         caller.placeInput(arg, builder.create<fir::AbsentOp>(loc, argTy));
1430         continue;
1431       }
1432       const auto *expr = actual->UnwrapExpr();
1433       if (!expr)
1434         TODO(loc, "assumed type actual argument lowering");
1435 
1436       if (arg.passBy == PassBy::Value) {
1437         ExtValue argVal = genval(*expr);
1438         if (!fir::isUnboxedValue(argVal))
1439           fir::emitFatalError(
1440               loc, "internal error: passing non trivial value by value");
1441         caller.placeInput(arg, fir::getBase(argVal));
1442         continue;
1443       }
1444 
1445       if (arg.passBy == PassBy::MutableBox) {
1446         TODO(loc, "arg passby MutableBox");
1447       }
1448       const bool actualArgIsVariable = Fortran::evaluate::IsVariable(*expr);
1449       if (arg.passBy == PassBy::BaseAddress || arg.passBy == PassBy::BoxChar) {
1450         auto argAddr = [&]() -> ExtValue {
1451           ExtValue baseAddr;
1452           if (actualArgIsVariable && arg.isOptional()) {
1453             if (Fortran::evaluate::IsAllocatableOrPointerObject(
1454                     *expr, converter.getFoldingContext())) {
1455               TODO(loc, "Allocatable or pointer argument");
1456             }
1457             if (const Fortran::semantics::Symbol *wholeSymbol =
1458                     Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(
1459                         *expr))
1460               if (Fortran::semantics::IsOptional(*wholeSymbol)) {
1461                 TODO(loc, "procedureref optional arg");
1462               }
1463             // Fall through: The actual argument can safely be
1464             // copied-in/copied-out without any care if needed.
1465           }
1466           if (actualArgIsVariable && expr->Rank() > 0) {
1467             TODO(loc, "procedureref arrays");
1468           }
1469           // Actual argument is a non optional/non pointer/non allocatable
1470           // scalar.
1471           if (actualArgIsVariable)
1472             return genExtAddr(*expr);
1473           // Actual argument is not a variable. Make sure a variable address is
1474           // not passed.
1475           return genTempExtAddr(*expr);
1476         }();
1477         // Scalar and contiguous expressions may be lowered to a fir.box,
1478         // either to account for potential polymorphism, or because lowering
1479         // did not account for some contiguity hints.
1480         // Here, polymorphism does not matter (an entity of the declared type
1481         // is passed, not one of the dynamic type), and the expr is known to
1482         // be simply contiguous, so it is safe to unbox it and pass the
1483         // address without making a copy.
1484         argAddr = readIfBoxValue(argAddr);
1485 
1486         if (arg.passBy == PassBy::BaseAddress) {
1487           caller.placeInput(arg, fir::getBase(argAddr));
1488         } else {
1489           assert(arg.passBy == PassBy::BoxChar);
1490           auto helper = fir::factory::CharacterExprHelper{builder, loc};
1491           auto boxChar = argAddr.match(
1492               [&](const fir::CharBoxValue &x) { return helper.createEmbox(x); },
1493               [&](const fir::CharArrayBoxValue &x) {
1494                 return helper.createEmbox(x);
1495               },
1496               [&](const auto &x) -> mlir::Value {
1497                 // Fortran allows an actual argument of a completely different
1498                 // type to be passed to a procedure expecting a CHARACTER in the
1499                 // dummy argument position. When this happens, the data pointer
1500                 // argument is simply assumed to point to CHARACTER data and the
1501                 // LEN argument used is garbage. Simulate this behavior by
1502                 // free-casting the base address to be a !fir.char reference and
1503                 // setting the LEN argument to undefined. What could go wrong?
1504                 auto dataPtr = fir::getBase(x);
1505                 assert(!dataPtr.getType().template isa<fir::BoxType>());
1506                 return builder.convertWithSemantics(
1507                     loc, argTy, dataPtr,
1508                     /*allowCharacterConversion=*/true);
1509               });
1510           caller.placeInput(arg, boxChar);
1511         }
1512       } else if (arg.passBy == PassBy::Box) {
1513         // Before lowering to an address, handle the allocatable/pointer actual
1514         // argument to optional fir.box dummy. It is legal to pass
1515         // unallocated/disassociated entity to an optional. In this case, an
1516         // absent fir.box must be created instead of a fir.box with a null value
1517         // (Fortran 2018 15.5.2.12 point 1).
1518         if (arg.isOptional() && Fortran::evaluate::IsAllocatableOrPointerObject(
1519                                     *expr, converter.getFoldingContext())) {
1520           TODO(loc, "optional allocatable or pointer argument");
1521         } else {
1522           // Make sure a variable address is only passed if the expression is
1523           // actually a variable.
1524           mlir::Value box =
1525               actualArgIsVariable
1526                   ? builder.createBox(loc, genBoxArg(*expr))
1527                   : builder.createBox(getLoc(), genTempExtAddr(*expr));
1528           caller.placeInput(arg, box);
1529         }
1530       } else if (arg.passBy == PassBy::AddressAndLength) {
1531         ExtValue argRef = genExtAddr(*expr);
1532         caller.placeAddressAndLengthInput(arg, fir::getBase(argRef),
1533                                           fir::getLen(argRef));
1534       } else if (arg.passBy == PassBy::CharProcTuple) {
1535         TODO(loc, "procedureref CharProcTuple");
1536       } else {
1537         TODO(loc, "pass by value in non elemental function call");
1538       }
1539     }
1540 
1541     ExtValue result = genCallOpAndResult(caller, callSiteType, resultType);
1542 
1543     // // Copy-out temps that were created for non contiguous variable arguments
1544     // if
1545     // // needed.
1546     // for (const auto &copyOutPair : copyOutPairs)
1547     //   genCopyOut(copyOutPair);
1548 
1549     return result;
1550   }
1551 
1552   template <typename A>
1553   ExtValue genval(const Fortran::evaluate::FunctionRef<A> &funcRef) {
1554     ExtValue result = genFunctionRef(funcRef);
1555     if (result.rank() == 0 && fir::isa_ref_type(fir::getBase(result).getType()))
1556       return genLoad(result);
1557     return result;
1558   }
1559 
1560   ExtValue genval(const Fortran::evaluate::ProcedureRef &procRef) {
1561     llvm::Optional<mlir::Type> resTy;
1562     if (procRef.hasAlternateReturns())
1563       resTy = builder.getIndexType();
1564     return genProcedureRef(procRef, resTy);
1565   }
1566 
1567   /// Generate a call to an intrinsic function.
1568   ExtValue
1569   genIntrinsicRef(const Fortran::evaluate::ProcedureRef &procRef,
1570                   const Fortran::evaluate::SpecificIntrinsic &intrinsic,
1571                   llvm::Optional<mlir::Type> resultType) {
1572     llvm::SmallVector<ExtValue> operands;
1573 
1574     llvm::StringRef name = intrinsic.name;
1575     mlir::Location loc = getLoc();
1576 
1577     const Fortran::lower::IntrinsicArgumentLoweringRules *argLowering =
1578         Fortran::lower::getIntrinsicArgumentLowering(name);
1579     for (const auto &[arg, dummy] :
1580          llvm::zip(procRef.arguments(),
1581                    intrinsic.characteristics.value().dummyArguments)) {
1582       auto *expr = Fortran::evaluate::UnwrapExpr<Fortran::lower::SomeExpr>(arg);
1583       if (!expr) {
1584         // Absent optional.
1585         operands.emplace_back(Fortran::lower::getAbsentIntrinsicArgument());
1586         continue;
1587       }
1588       if (!argLowering) {
1589         // No argument lowering instruction, lower by value.
1590         operands.emplace_back(genval(*expr));
1591         continue;
1592       }
1593       // Ad-hoc argument lowering handling.
1594       Fortran::lower::ArgLoweringRule argRules =
1595           Fortran::lower::lowerIntrinsicArgumentAs(loc, *argLowering,
1596                                                    dummy.name);
1597       switch (argRules.lowerAs) {
1598       case Fortran::lower::LowerIntrinsicArgAs::Value:
1599         operands.emplace_back(genval(*expr));
1600         continue;
1601       case Fortran::lower::LowerIntrinsicArgAs::Addr:
1602         TODO(getLoc(), "argument lowering for Addr");
1603         continue;
1604       case Fortran::lower::LowerIntrinsicArgAs::Box:
1605         TODO(getLoc(), "argument lowering for Box");
1606         continue;
1607       case Fortran::lower::LowerIntrinsicArgAs::Inquired:
1608         TODO(getLoc(), "argument lowering for Inquired");
1609         continue;
1610       }
1611       llvm_unreachable("bad switch");
1612     }
1613     // Let the intrinsic library lower the intrinsic procedure call
1614     return Fortran::lower::genIntrinsicCall(builder, getLoc(), name, resultType,
1615                                             operands);
1616   }
1617 
1618   template <typename A>
1619   ExtValue genval(const Fortran::evaluate::Expr<A> &x) {
1620     if (isScalar(x))
1621       return std::visit([&](const auto &e) { return genval(e); }, x.u);
1622     TODO(getLoc(), "genval Expr<A> arrays");
1623   }
1624 
1625   /// Helper to detect Transformational function reference.
1626   template <typename T>
1627   bool isTransformationalRef(const T &) {
1628     return false;
1629   }
1630   template <typename T>
1631   bool isTransformationalRef(const Fortran::evaluate::FunctionRef<T> &funcRef) {
1632     return !funcRef.IsElemental() && funcRef.Rank();
1633   }
1634   template <typename T>
1635   bool isTransformationalRef(Fortran::evaluate::Expr<T> expr) {
1636     return std::visit([&](const auto &e) { return isTransformationalRef(e); },
1637                       expr.u);
1638   }
1639 
1640   template <typename A>
1641   ExtValue gen(const Fortran::evaluate::Expr<A> &x) {
1642     // Whole array symbols or components, and results of transformational
1643     // functions already have a storage and the scalar expression lowering path
1644     // is used to not create a new temporary storage.
1645     if (isScalar(x) ||
1646         Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(x) ||
1647         isTransformationalRef(x))
1648       return std::visit([&](const auto &e) { return genref(e); }, x.u);
1649     TODO(getLoc(), "gen Expr non-scalar");
1650   }
1651 
1652   template <typename A>
1653   bool isScalar(const A &x) {
1654     return x.Rank() == 0;
1655   }
1656 
1657   template <int KIND>
1658   ExtValue genval(const Fortran::evaluate::Expr<Fortran::evaluate::Type<
1659                       Fortran::common::TypeCategory::Logical, KIND>> &exp) {
1660     return std::visit([&](const auto &e) { return genval(e); }, exp.u);
1661   }
1662 
1663   using RefSet =
1664       std::tuple<Fortran::evaluate::ComplexPart, Fortran::evaluate::Substring,
1665                  Fortran::evaluate::DataRef, Fortran::evaluate::Component,
1666                  Fortran::evaluate::ArrayRef, Fortran::evaluate::CoarrayRef,
1667                  Fortran::semantics::SymbolRef>;
1668   template <typename A>
1669   static constexpr bool inRefSet = Fortran::common::HasMember<A, RefSet>;
1670 
1671   template <typename A, typename = std::enable_if_t<inRefSet<A>>>
1672   ExtValue genref(const A &a) {
1673     return gen(a);
1674   }
1675   template <typename A>
1676   ExtValue genref(const A &a) {
1677     mlir::Type storageType = converter.genType(toEvExpr(a));
1678     return placeScalarValueInMemory(builder, getLoc(), genval(a), storageType);
1679   }
1680 
1681   template <typename A, template <typename> typename T,
1682             typename B = std::decay_t<T<A>>,
1683             std::enable_if_t<
1684                 std::is_same_v<B, Fortran::evaluate::Expr<A>> ||
1685                     std::is_same_v<B, Fortran::evaluate::Designator<A>> ||
1686                     std::is_same_v<B, Fortran::evaluate::FunctionRef<A>>,
1687                 bool> = true>
1688   ExtValue genref(const T<A> &x) {
1689     return gen(x);
1690   }
1691 
1692 private:
1693   mlir::Location location;
1694   Fortran::lower::AbstractConverter &converter;
1695   fir::FirOpBuilder &builder;
1696   Fortran::lower::StatementContext &stmtCtx;
1697   Fortran::lower::SymMap &symMap;
1698   bool useBoxArg = false; // expression lowered as argument
1699 };
1700 } // namespace
1701 
1702 // Helper for changing the semantics in a given context. Preserves the current
1703 // semantics which is resumed when the "push" goes out of scope.
1704 #define PushSemantics(PushVal)                                                 \
1705   [[maybe_unused]] auto pushSemanticsLocalVariable##__LINE__ =                 \
1706       Fortran::common::ScopedSet(semant, PushVal);
1707 
1708 static bool isAdjustedArrayElementType(mlir::Type t) {
1709   return fir::isa_char(t) || fir::isa_derived(t) || t.isa<fir::SequenceType>();
1710 }
1711 
1712 /// Build an ExtendedValue from a fir.array<?x...?xT> without actually setting
1713 /// the actual extents and lengths. This is only to allow their propagation as
1714 /// ExtendedValue without triggering verifier failures when propagating
1715 /// character/arrays as unboxed values. Only the base of the resulting
1716 /// ExtendedValue should be used, it is undefined to use the length or extents
1717 /// of the extended value returned,
1718 inline static fir::ExtendedValue
1719 convertToArrayBoxValue(mlir::Location loc, fir::FirOpBuilder &builder,
1720                        mlir::Value val, mlir::Value len) {
1721   mlir::Type ty = fir::unwrapRefType(val.getType());
1722   mlir::IndexType idxTy = builder.getIndexType();
1723   auto seqTy = ty.cast<fir::SequenceType>();
1724   auto undef = builder.create<fir::UndefOp>(loc, idxTy);
1725   llvm::SmallVector<mlir::Value> extents(seqTy.getDimension(), undef);
1726   if (fir::isa_char(seqTy.getEleTy()))
1727     return fir::CharArrayBoxValue(val, len ? len : undef, extents);
1728   return fir::ArrayBoxValue(val, extents);
1729 }
1730 
1731 //===----------------------------------------------------------------------===//
1732 //
1733 // Lowering of array expressions.
1734 //
1735 //===----------------------------------------------------------------------===//
1736 
1737 namespace {
1738 class ArrayExprLowering {
1739   using ExtValue = fir::ExtendedValue;
1740 
1741   /// Structure to keep track of lowered array operands in the
1742   /// array expression. Useful to later deduce the shape of the
1743   /// array expression.
1744   struct ArrayOperand {
1745     /// Array base (can be a fir.box).
1746     mlir::Value memref;
1747     /// ShapeOp, ShapeShiftOp or ShiftOp
1748     mlir::Value shape;
1749     /// SliceOp
1750     mlir::Value slice;
1751     /// Can this operand be absent ?
1752     bool mayBeAbsent = false;
1753   };
1754 
1755   using ImplicitSubscripts = Fortran::lower::details::ImplicitSubscripts;
1756   using PathComponent = Fortran::lower::PathComponent;
1757 
1758   /// Active iteration space.
1759   using IterationSpace = Fortran::lower::IterationSpace;
1760   using IterSpace = const Fortran::lower::IterationSpace &;
1761 
1762   /// Current continuation. Function that will generate IR for a single
1763   /// iteration of the pending iterative loop structure.
1764   using CC = Fortran::lower::GenerateElementalArrayFunc;
1765 
1766   /// Projection continuation. Function that will project one iteration space
1767   /// into another.
1768   using PC = std::function<IterationSpace(IterSpace)>;
1769   using ArrayBaseTy =
1770       std::variant<std::monostate, const Fortran::evaluate::ArrayRef *,
1771                    const Fortran::evaluate::DataRef *>;
1772   using ComponentPath = Fortran::lower::ComponentPath;
1773 
1774 public:
1775   //===--------------------------------------------------------------------===//
1776   // Regular array assignment
1777   //===--------------------------------------------------------------------===//
1778 
1779   /// Entry point for array assignments. Both the left-hand and right-hand sides
1780   /// can either be ExtendedValue or evaluate::Expr.
1781   template <typename TL, typename TR>
1782   static void lowerArrayAssignment(Fortran::lower::AbstractConverter &converter,
1783                                    Fortran::lower::SymMap &symMap,
1784                                    Fortran::lower::StatementContext &stmtCtx,
1785                                    const TL &lhs, const TR &rhs) {
1786     ArrayExprLowering ael{converter, stmtCtx, symMap,
1787                           ConstituentSemantics::CopyInCopyOut};
1788     ael.lowerArrayAssignment(lhs, rhs);
1789   }
1790 
1791   template <typename TL, typename TR>
1792   void lowerArrayAssignment(const TL &lhs, const TR &rhs) {
1793     mlir::Location loc = getLoc();
1794     /// Here the target subspace is not necessarily contiguous. The ArrayUpdate
1795     /// continuation is implicitly returned in `ccStoreToDest` and the ArrayLoad
1796     /// in `destination`.
1797     PushSemantics(ConstituentSemantics::ProjectedCopyInCopyOut);
1798     ccStoreToDest = genarr(lhs);
1799     determineShapeOfDest(lhs);
1800     semant = ConstituentSemantics::RefTransparent;
1801     ExtValue exv = lowerArrayExpression(rhs);
1802     if (explicitSpaceIsActive()) {
1803       explicitSpace->finalizeContext();
1804       builder.create<fir::ResultOp>(loc, fir::getBase(exv));
1805     } else {
1806       builder.create<fir::ArrayMergeStoreOp>(
1807           loc, destination, fir::getBase(exv), destination.getMemref(),
1808           destination.getSlice(), destination.getTypeparams());
1809     }
1810   }
1811 
1812   //===--------------------------------------------------------------------===//
1813   // Array assignment to allocatable array
1814   //===--------------------------------------------------------------------===//
1815 
1816   /// Entry point for assignment to allocatable array.
1817   static void lowerAllocatableArrayAssignment(
1818       Fortran::lower::AbstractConverter &converter,
1819       Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
1820       const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
1821       Fortran::lower::ExplicitIterSpace &explicitSpace,
1822       Fortran::lower::ImplicitIterSpace &implicitSpace) {
1823     ArrayExprLowering ael(converter, stmtCtx, symMap,
1824                           ConstituentSemantics::CopyInCopyOut, &explicitSpace,
1825                           &implicitSpace);
1826     ael.lowerAllocatableArrayAssignment(lhs, rhs);
1827   }
1828 
1829   /// Assignment to allocatable array.
1830   ///
1831   /// The semantics are reverse that of a "regular" array assignment. The rhs
1832   /// defines the iteration space of the computation and the lhs is
1833   /// resized/reallocated to fit if necessary.
1834   void lowerAllocatableArrayAssignment(const Fortran::lower::SomeExpr &lhs,
1835                                        const Fortran::lower::SomeExpr &rhs) {
1836     // With assignment to allocatable, we want to lower the rhs first and use
1837     // its shape to determine if we need to reallocate, etc.
1838     mlir::Location loc = getLoc();
1839     // FIXME: If the lhs is in an explicit iteration space, the assignment may
1840     // be to an array of allocatable arrays rather than a single allocatable
1841     // array.
1842     fir::MutableBoxValue mutableBox =
1843         createMutableBox(loc, converter, lhs, symMap);
1844     mlir::Type resultTy = converter.genType(rhs);
1845     if (rhs.Rank() > 0)
1846       determineShapeOfDest(rhs);
1847     auto rhsCC = [&]() {
1848       PushSemantics(ConstituentSemantics::RefTransparent);
1849       return genarr(rhs);
1850     }();
1851 
1852     llvm::SmallVector<mlir::Value> lengthParams;
1853     // Currently no safe way to gather length from rhs (at least for
1854     // character, it cannot be taken from array_loads since it may be
1855     // changed by concatenations).
1856     if ((mutableBox.isCharacter() && !mutableBox.hasNonDeferredLenParams()) ||
1857         mutableBox.isDerivedWithLengthParameters())
1858       TODO(loc, "gather rhs length parameters in assignment to allocatable");
1859 
1860     // The allocatable must take lower bounds from the expr if it is
1861     // reallocated and the right hand side is not a scalar.
1862     const bool takeLboundsIfRealloc = rhs.Rank() > 0;
1863     llvm::SmallVector<mlir::Value> lbounds;
1864     // When the reallocated LHS takes its lower bounds from the RHS,
1865     // they will be non default only if the RHS is a whole array
1866     // variable. Otherwise, lbounds is left empty and default lower bounds
1867     // will be used.
1868     if (takeLboundsIfRealloc &&
1869         Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(rhs)) {
1870       assert(arrayOperands.size() == 1 &&
1871              "lbounds can only come from one array");
1872       std::vector<mlir::Value> lbs =
1873           fir::factory::getOrigins(arrayOperands[0].shape);
1874       lbounds.append(lbs.begin(), lbs.end());
1875     }
1876     fir::factory::MutableBoxReallocation realloc =
1877         fir::factory::genReallocIfNeeded(builder, loc, mutableBox, destShape,
1878                                          lengthParams);
1879     // Create ArrayLoad for the mutable box and save it into `destination`.
1880     PushSemantics(ConstituentSemantics::ProjectedCopyInCopyOut);
1881     ccStoreToDest = genarr(realloc.newValue);
1882     // If the rhs is scalar, get shape from the allocatable ArrayLoad.
1883     if (destShape.empty())
1884       destShape = getShape(destination);
1885     // Finish lowering the loop nest.
1886     assert(destination && "destination must have been set");
1887     ExtValue exv = lowerArrayExpression(rhsCC, resultTy);
1888     if (explicitSpaceIsActive()) {
1889       explicitSpace->finalizeContext();
1890       builder.create<fir::ResultOp>(loc, fir::getBase(exv));
1891     } else {
1892       builder.create<fir::ArrayMergeStoreOp>(
1893           loc, destination, fir::getBase(exv), destination.getMemref(),
1894           destination.getSlice(), destination.getTypeparams());
1895     }
1896     fir::factory::finalizeRealloc(builder, loc, mutableBox, lbounds,
1897                                   takeLboundsIfRealloc, realloc);
1898   }
1899 
1900   /// Entry point for when an array expression appears in a context where the
1901   /// result must be boxed. (BoxValue semantics.)
1902   static ExtValue
1903   lowerBoxedArrayExpression(Fortran::lower::AbstractConverter &converter,
1904                             Fortran::lower::SymMap &symMap,
1905                             Fortran::lower::StatementContext &stmtCtx,
1906                             const Fortran::lower::SomeExpr &expr) {
1907     ArrayExprLowering ael{converter, stmtCtx, symMap,
1908                           ConstituentSemantics::BoxValue};
1909     return ael.lowerBoxedArrayExpr(expr);
1910   }
1911 
1912   ExtValue lowerBoxedArrayExpr(const Fortran::lower::SomeExpr &exp) {
1913     return std::visit(
1914         [&](const auto &e) {
1915           auto f = genarr(e);
1916           ExtValue exv = f(IterationSpace{});
1917           if (fir::getBase(exv).getType().template isa<fir::BoxType>())
1918             return exv;
1919           fir::emitFatalError(getLoc(), "array must be emboxed");
1920         },
1921         exp.u);
1922   }
1923 
1924   /// Entry point into lowering an expression with rank. This entry point is for
1925   /// lowering a rhs expression, for example. (RefTransparent semantics.)
1926   static ExtValue
1927   lowerNewArrayExpression(Fortran::lower::AbstractConverter &converter,
1928                           Fortran::lower::SymMap &symMap,
1929                           Fortran::lower::StatementContext &stmtCtx,
1930                           const Fortran::lower::SomeExpr &expr) {
1931     ArrayExprLowering ael{converter, stmtCtx, symMap};
1932     ael.determineShapeOfDest(expr);
1933     ExtValue loopRes = ael.lowerArrayExpression(expr);
1934     fir::ArrayLoadOp dest = ael.destination;
1935     mlir::Value tempRes = dest.getMemref();
1936     fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1937     mlir::Location loc = converter.getCurrentLocation();
1938     builder.create<fir::ArrayMergeStoreOp>(loc, dest, fir::getBase(loopRes),
1939                                            tempRes, dest.getSlice(),
1940                                            dest.getTypeparams());
1941 
1942     auto arrTy =
1943         fir::dyn_cast_ptrEleTy(tempRes.getType()).cast<fir::SequenceType>();
1944     if (auto charTy =
1945             arrTy.getEleTy().template dyn_cast<fir::CharacterType>()) {
1946       if (fir::characterWithDynamicLen(charTy))
1947         TODO(loc, "CHARACTER does not have constant LEN");
1948       mlir::Value len = builder.createIntegerConstant(
1949           loc, builder.getCharacterLengthType(), charTy.getLen());
1950       return fir::CharArrayBoxValue(tempRes, len, dest.getExtents());
1951     }
1952     return fir::ArrayBoxValue(tempRes, dest.getExtents());
1953   }
1954 
1955   // FIXME: should take multiple inner arguments.
1956   std::pair<IterationSpace, mlir::OpBuilder::InsertPoint>
1957   genImplicitLoops(mlir::ValueRange shape, mlir::Value innerArg) {
1958     mlir::Location loc = getLoc();
1959     mlir::IndexType idxTy = builder.getIndexType();
1960     mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
1961     mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
1962     llvm::SmallVector<mlir::Value> loopUppers;
1963 
1964     // Convert any implied shape to closed interval form. The fir.do_loop will
1965     // run from 0 to `extent - 1` inclusive.
1966     for (auto extent : shape)
1967       loopUppers.push_back(
1968           builder.create<mlir::arith::SubIOp>(loc, extent, one));
1969 
1970     // Iteration space is created with outermost columns, innermost rows
1971     llvm::SmallVector<fir::DoLoopOp> loops;
1972 
1973     const std::size_t loopDepth = loopUppers.size();
1974     llvm::SmallVector<mlir::Value> ivars;
1975 
1976     for (auto i : llvm::enumerate(llvm::reverse(loopUppers))) {
1977       if (i.index() > 0) {
1978         assert(!loops.empty());
1979         builder.setInsertionPointToStart(loops.back().getBody());
1980       }
1981       fir::DoLoopOp loop;
1982       if (innerArg) {
1983         loop = builder.create<fir::DoLoopOp>(
1984             loc, zero, i.value(), one, isUnordered(),
1985             /*finalCount=*/false, mlir::ValueRange{innerArg});
1986         innerArg = loop.getRegionIterArgs().front();
1987         if (explicitSpaceIsActive())
1988           explicitSpace->setInnerArg(0, innerArg);
1989       } else {
1990         loop = builder.create<fir::DoLoopOp>(loc, zero, i.value(), one,
1991                                              isUnordered(),
1992                                              /*finalCount=*/false);
1993       }
1994       ivars.push_back(loop.getInductionVar());
1995       loops.push_back(loop);
1996     }
1997 
1998     if (innerArg)
1999       for (std::remove_const_t<decltype(loopDepth)> i = 0; i + 1 < loopDepth;
2000            ++i) {
2001         builder.setInsertionPointToEnd(loops[i].getBody());
2002         builder.create<fir::ResultOp>(loc, loops[i + 1].getResult(0));
2003       }
2004 
2005     // Move insertion point to the start of the innermost loop in the nest.
2006     builder.setInsertionPointToStart(loops.back().getBody());
2007     // Set `afterLoopNest` to just after the entire loop nest.
2008     auto currPt = builder.saveInsertionPoint();
2009     builder.setInsertionPointAfter(loops[0]);
2010     auto afterLoopNest = builder.saveInsertionPoint();
2011     builder.restoreInsertionPoint(currPt);
2012 
2013     // Put the implicit loop variables in row to column order to match FIR's
2014     // Ops. (The loops were constructed from outermost column to innermost
2015     // row.)
2016     mlir::Value outerRes = loops[0].getResult(0);
2017     return {IterationSpace(innerArg, outerRes, llvm::reverse(ivars)),
2018             afterLoopNest};
2019   }
2020 
2021   /// Build the iteration space into which the array expression will be
2022   /// lowered. The resultType is used to create a temporary, if needed.
2023   std::pair<IterationSpace, mlir::OpBuilder::InsertPoint>
2024   genIterSpace(mlir::Type resultType) {
2025     mlir::Location loc = getLoc();
2026     llvm::SmallVector<mlir::Value> shape = genIterationShape();
2027     if (!destination) {
2028       // Allocate storage for the result if it is not already provided.
2029       destination = createAndLoadSomeArrayTemp(resultType, shape);
2030     }
2031 
2032     // Generate the lazy mask allocation, if one was given.
2033     if (ccPrelude.hasValue())
2034       ccPrelude.getValue()(shape);
2035 
2036     // Now handle the implicit loops.
2037     mlir::Value inner = explicitSpaceIsActive()
2038                             ? explicitSpace->getInnerArgs().front()
2039                             : destination.getResult();
2040     auto [iters, afterLoopNest] = genImplicitLoops(shape, inner);
2041     mlir::Value innerArg = iters.innerArgument();
2042 
2043     // Generate the mask conditional structure, if there are masks. Unlike the
2044     // explicit masks, which are interleaved, these mask expression appear in
2045     // the innermost loop.
2046     if (implicitSpaceHasMasks()) {
2047       // Recover the cached condition from the mask buffer.
2048       auto genCond = [&](Fortran::lower::FrontEndExpr e, IterSpace iters) {
2049         return implicitSpace->getBoundClosure(e)(iters);
2050       };
2051 
2052       // Handle the negated conditions in topological order of the WHERE
2053       // clauses. See 10.2.3.2p4 as to why this control structure is produced.
2054       for (llvm::SmallVector<Fortran::lower::FrontEndExpr> maskExprs :
2055            implicitSpace->getMasks()) {
2056         const std::size_t size = maskExprs.size() - 1;
2057         auto genFalseBlock = [&](const auto *e, auto &&cond) {
2058           auto ifOp = builder.create<fir::IfOp>(
2059               loc, mlir::TypeRange{innerArg.getType()}, fir::getBase(cond),
2060               /*withElseRegion=*/true);
2061           builder.create<fir::ResultOp>(loc, ifOp.getResult(0));
2062           builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
2063           builder.create<fir::ResultOp>(loc, innerArg);
2064           builder.setInsertionPointToStart(&ifOp.getElseRegion().front());
2065         };
2066         auto genTrueBlock = [&](const auto *e, auto &&cond) {
2067           auto ifOp = builder.create<fir::IfOp>(
2068               loc, mlir::TypeRange{innerArg.getType()}, fir::getBase(cond),
2069               /*withElseRegion=*/true);
2070           builder.create<fir::ResultOp>(loc, ifOp.getResult(0));
2071           builder.setInsertionPointToStart(&ifOp.getElseRegion().front());
2072           builder.create<fir::ResultOp>(loc, innerArg);
2073           builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
2074         };
2075         for (std::remove_const_t<decltype(size)> i = 0; i < size; ++i)
2076           if (const auto *e = maskExprs[i])
2077             genFalseBlock(e, genCond(e, iters));
2078 
2079         // The last condition is either non-negated or unconditionally negated.
2080         if (const auto *e = maskExprs[size])
2081           genTrueBlock(e, genCond(e, iters));
2082       }
2083     }
2084 
2085     // We're ready to lower the body (an assignment statement) for this context
2086     // of loop nests at this point.
2087     return {iters, afterLoopNest};
2088   }
2089 
2090   fir::ArrayLoadOp
2091   createAndLoadSomeArrayTemp(mlir::Type type,
2092                              llvm::ArrayRef<mlir::Value> shape) {
2093     if (ccLoadDest.hasValue())
2094       return ccLoadDest.getValue()(shape);
2095     auto seqTy = type.dyn_cast<fir::SequenceType>();
2096     assert(seqTy && "must be an array");
2097     mlir::Location loc = getLoc();
2098     // TODO: Need to thread the length parameters here. For character, they may
2099     // differ from the operands length (e.g concatenation). So the array loads
2100     // type parameters are not enough.
2101     if (auto charTy = seqTy.getEleTy().dyn_cast<fir::CharacterType>())
2102       if (charTy.hasDynamicLen())
2103         TODO(loc, "character array expression temp with dynamic length");
2104     if (auto recTy = seqTy.getEleTy().dyn_cast<fir::RecordType>())
2105       if (recTy.getNumLenParams() > 0)
2106         TODO(loc, "derived type array expression temp with length parameters");
2107     mlir::Value temp = seqTy.hasConstantShape()
2108                            ? builder.create<fir::AllocMemOp>(loc, type)
2109                            : builder.create<fir::AllocMemOp>(
2110                                  loc, type, ".array.expr", llvm::None, shape);
2111     fir::FirOpBuilder *bldr = &converter.getFirOpBuilder();
2112     stmtCtx.attachCleanup(
2113         [bldr, loc, temp]() { bldr->create<fir::FreeMemOp>(loc, temp); });
2114     mlir::Value shapeOp = genShapeOp(shape);
2115     return builder.create<fir::ArrayLoadOp>(loc, seqTy, temp, shapeOp,
2116                                             /*slice=*/mlir::Value{},
2117                                             llvm::None);
2118   }
2119 
2120   static fir::ShapeOp genShapeOp(mlir::Location loc, fir::FirOpBuilder &builder,
2121                                  llvm::ArrayRef<mlir::Value> shape) {
2122     mlir::IndexType idxTy = builder.getIndexType();
2123     llvm::SmallVector<mlir::Value> idxShape;
2124     for (auto s : shape)
2125       idxShape.push_back(builder.createConvert(loc, idxTy, s));
2126     auto shapeTy = fir::ShapeType::get(builder.getContext(), idxShape.size());
2127     return builder.create<fir::ShapeOp>(loc, shapeTy, idxShape);
2128   }
2129 
2130   fir::ShapeOp genShapeOp(llvm::ArrayRef<mlir::Value> shape) {
2131     return genShapeOp(getLoc(), builder, shape);
2132   }
2133 
2134   //===--------------------------------------------------------------------===//
2135   // Expression traversal and lowering.
2136   //===--------------------------------------------------------------------===//
2137 
2138   /// Lower the expression, \p x, in a scalar context.
2139   template <typename A>
2140   ExtValue asScalar(const A &x) {
2141     return ScalarExprLowering{getLoc(), converter, symMap, stmtCtx}.genval(x);
2142   }
2143 
2144   /// Lower the expression in a scalar context to a memory reference.
2145   template <typename A>
2146   ExtValue asScalarRef(const A &x) {
2147     return ScalarExprLowering{getLoc(), converter, symMap, stmtCtx}.gen(x);
2148   }
2149 
2150   // An expression with non-zero rank is an array expression.
2151   template <typename A>
2152   bool isArray(const A &x) const {
2153     return x.Rank() != 0;
2154   }
2155 
2156   /// If there were temporaries created for this element evaluation, finalize
2157   /// and deallocate the resources now. This should be done just prior the the
2158   /// fir::ResultOp at the end of the innermost loop.
2159   void finalizeElementCtx() {
2160     if (elementCtx) {
2161       stmtCtx.finalize(/*popScope=*/true);
2162       elementCtx = false;
2163     }
2164   }
2165 
2166   template <typename A>
2167   CC genScalarAndForwardValue(const A &x) {
2168     ExtValue result = asScalar(x);
2169     return [=](IterSpace) { return result; };
2170   }
2171 
2172   template <typename A, typename = std::enable_if_t<Fortran::common::HasMember<
2173                             A, Fortran::evaluate::TypelessExpression>>>
2174   CC genarr(const A &x) {
2175     return genScalarAndForwardValue(x);
2176   }
2177 
2178   template <typename A>
2179   CC genarr(const Fortran::evaluate::Expr<A> &x) {
2180     LLVM_DEBUG(Fortran::lower::DumpEvaluateExpr::dump(llvm::dbgs(), x));
2181     if (isArray(x) || explicitSpaceIsActive() ||
2182         isElementalProcWithArrayArgs(x))
2183       return std::visit([&](const auto &e) { return genarr(e); }, x.u);
2184     return genScalarAndForwardValue(x);
2185   }
2186 
2187   template <Fortran::common::TypeCategory TC1, int KIND,
2188             Fortran::common::TypeCategory TC2>
2189   CC genarr(const Fortran::evaluate::Convert<Fortran::evaluate::Type<TC1, KIND>,
2190                                              TC2> &x) {
2191     TODO(getLoc(), "");
2192   }
2193 
2194   template <int KIND>
2195   CC genarr(const Fortran::evaluate::ComplexComponent<KIND> &x) {
2196     TODO(getLoc(), "");
2197   }
2198 
2199   template <typename T>
2200   CC genarr(const Fortran::evaluate::Parentheses<T> &x) {
2201     TODO(getLoc(), "");
2202   }
2203 
2204   template <int KIND>
2205   CC genarr(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
2206                 Fortran::common::TypeCategory::Integer, KIND>> &x) {
2207     TODO(getLoc(), "");
2208   }
2209 
2210   template <int KIND>
2211   CC genarr(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
2212                 Fortran::common::TypeCategory::Real, KIND>> &x) {
2213     TODO(getLoc(), "");
2214   }
2215   template <int KIND>
2216   CC genarr(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
2217                 Fortran::common::TypeCategory::Complex, KIND>> &x) {
2218     TODO(getLoc(), "");
2219   }
2220 
2221 #undef GENBIN
2222 #define GENBIN(GenBinEvOp, GenBinTyCat, GenBinFirOp)                           \
2223   template <int KIND>                                                          \
2224   CC genarr(const Fortran::evaluate::GenBinEvOp<Fortran::evaluate::Type<       \
2225                 Fortran::common::TypeCategory::GenBinTyCat, KIND>> &x) {       \
2226     TODO(getLoc(), "genarr Binary");                                           \
2227   }
2228 
2229   GENBIN(Add, Integer, mlir::arith::AddIOp)
2230   GENBIN(Add, Real, mlir::arith::AddFOp)
2231   GENBIN(Add, Complex, fir::AddcOp)
2232   GENBIN(Subtract, Integer, mlir::arith::SubIOp)
2233   GENBIN(Subtract, Real, mlir::arith::SubFOp)
2234   GENBIN(Subtract, Complex, fir::SubcOp)
2235   GENBIN(Multiply, Integer, mlir::arith::MulIOp)
2236   GENBIN(Multiply, Real, mlir::arith::MulFOp)
2237   GENBIN(Multiply, Complex, fir::MulcOp)
2238   GENBIN(Divide, Integer, mlir::arith::DivSIOp)
2239   GENBIN(Divide, Real, mlir::arith::DivFOp)
2240   GENBIN(Divide, Complex, fir::DivcOp)
2241 
2242   template <Fortran::common::TypeCategory TC, int KIND>
2243   CC genarr(
2244       const Fortran::evaluate::Power<Fortran::evaluate::Type<TC, KIND>> &x) {
2245     TODO(getLoc(), "genarr ");
2246   }
2247   template <Fortran::common::TypeCategory TC, int KIND>
2248   CC genarr(
2249       const Fortran::evaluate::Extremum<Fortran::evaluate::Type<TC, KIND>> &x) {
2250     TODO(getLoc(), "genarr ");
2251   }
2252   template <Fortran::common::TypeCategory TC, int KIND>
2253   CC genarr(
2254       const Fortran::evaluate::RealToIntPower<Fortran::evaluate::Type<TC, KIND>>
2255           &x) {
2256     TODO(getLoc(), "genarr ");
2257   }
2258   template <int KIND>
2259   CC genarr(const Fortran::evaluate::ComplexConstructor<KIND> &x) {
2260     TODO(getLoc(), "genarr ");
2261   }
2262 
2263   template <int KIND>
2264   CC genarr(const Fortran::evaluate::Concat<KIND> &x) {
2265     TODO(getLoc(), "genarr ");
2266   }
2267 
2268   template <int KIND>
2269   CC genarr(const Fortran::evaluate::SetLength<KIND> &x) {
2270     TODO(getLoc(), "genarr ");
2271   }
2272 
2273   template <typename A>
2274   CC genarr(const Fortran::evaluate::Constant<A> &x) {
2275     TODO(getLoc(), "genarr ");
2276   }
2277 
2278   CC genarr(const Fortran::semantics::SymbolRef &sym,
2279             ComponentPath &components) {
2280     return genarr(sym.get(), components);
2281   }
2282 
2283   ExtValue abstractArrayExtValue(mlir::Value val, mlir::Value len = {}) {
2284     return convertToArrayBoxValue(getLoc(), builder, val, len);
2285   }
2286 
2287   CC genarr(const ExtValue &extMemref) {
2288     ComponentPath dummy(/*isImplicit=*/true);
2289     return genarr(extMemref, dummy);
2290   }
2291 
2292   template <typename A>
2293   CC genarr(const Fortran::evaluate::ArrayConstructor<A> &x) {
2294     TODO(getLoc(), "genarr ArrayConstructor<A>");
2295   }
2296 
2297   CC genarr(const Fortran::evaluate::ImpliedDoIndex &) {
2298     TODO(getLoc(), "genarr ImpliedDoIndex");
2299   }
2300 
2301   CC genarr(const Fortran::evaluate::TypeParamInquiry &x) {
2302     TODO(getLoc(), "genarr TypeParamInquiry");
2303   }
2304 
2305   CC genarr(const Fortran::evaluate::DescriptorInquiry &x) {
2306     TODO(getLoc(), "genarr DescriptorInquiry");
2307   }
2308 
2309   CC genarr(const Fortran::evaluate::StructureConstructor &x) {
2310     TODO(getLoc(), "genarr StructureConstructor");
2311   }
2312 
2313   template <int KIND>
2314   CC genarr(const Fortran::evaluate::Not<KIND> &x) {
2315     TODO(getLoc(), "genarr Not");
2316   }
2317 
2318   template <int KIND>
2319   CC genarr(const Fortran::evaluate::LogicalOperation<KIND> &x) {
2320     TODO(getLoc(), "genarr LogicalOperation");
2321   }
2322 
2323   template <int KIND>
2324   CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
2325                 Fortran::common::TypeCategory::Integer, KIND>> &x) {
2326     TODO(getLoc(), "genarr Relational Integer");
2327   }
2328   template <int KIND>
2329   CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
2330                 Fortran::common::TypeCategory::Character, KIND>> &x) {
2331     TODO(getLoc(), "genarr Relational Character");
2332   }
2333   template <int KIND>
2334   CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
2335                 Fortran::common::TypeCategory::Real, KIND>> &x) {
2336     TODO(getLoc(), "genarr Relational Real");
2337   }
2338   template <int KIND>
2339   CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
2340                 Fortran::common::TypeCategory::Complex, KIND>> &x) {
2341     TODO(getLoc(), "genarr Relational Complex");
2342   }
2343   CC genarr(
2344       const Fortran::evaluate::Relational<Fortran::evaluate::SomeType> &r) {
2345     TODO(getLoc(), "genarr Relational SomeType");
2346   }
2347 
2348   template <typename A>
2349   CC genarr(const Fortran::evaluate::Designator<A> &des) {
2350     ComponentPath components(des.Rank() > 0);
2351     return std::visit([&](const auto &x) { return genarr(x, components); },
2352                       des.u);
2353   }
2354 
2355   template <typename T>
2356   CC genarr(const Fortran::evaluate::FunctionRef<T> &funRef) {
2357     TODO(getLoc(), "genarr FunctionRef");
2358   }
2359 
2360   template <typename A>
2361   CC genImplicitArrayAccess(const A &x, ComponentPath &components) {
2362     components.reversePath.push_back(ImplicitSubscripts{});
2363     ExtValue exv = asScalarRef(x);
2364     // lowerPath(exv, components);
2365     auto lambda = genarr(exv, components);
2366     return [=](IterSpace iters) { return lambda(components.pc(iters)); };
2367   }
2368   CC genImplicitArrayAccess(const Fortran::evaluate::NamedEntity &x,
2369                             ComponentPath &components) {
2370     if (x.IsSymbol())
2371       return genImplicitArrayAccess(x.GetFirstSymbol(), components);
2372     return genImplicitArrayAccess(x.GetComponent(), components);
2373   }
2374 
2375   template <typename A>
2376   CC genAsScalar(const A &x) {
2377     mlir::Location loc = getLoc();
2378     if (isProjectedCopyInCopyOut()) {
2379       return [=, &x, builder = &converter.getFirOpBuilder()](
2380                  IterSpace iters) -> ExtValue {
2381         ExtValue exv = asScalarRef(x);
2382         mlir::Value val = fir::getBase(exv);
2383         mlir::Type eleTy = fir::unwrapRefType(val.getType());
2384         if (isAdjustedArrayElementType(eleTy)) {
2385           if (fir::isa_char(eleTy)) {
2386             TODO(getLoc(), "assignment of character type");
2387           } else if (fir::isa_derived(eleTy)) {
2388             TODO(loc, "assignment of derived type");
2389           } else {
2390             fir::emitFatalError(loc, "array type not expected in scalar");
2391           }
2392         } else {
2393           builder->create<fir::StoreOp>(loc, iters.getElement(), val);
2394         }
2395         return exv;
2396       };
2397     }
2398     return [=, &x](IterSpace) { return asScalar(x); };
2399   }
2400 
2401   CC genarr(const Fortran::semantics::Symbol &x, ComponentPath &components) {
2402     if (explicitSpaceIsActive()) {
2403       TODO(getLoc(), "genarr Symbol explicitSpace");
2404     } else {
2405       return genImplicitArrayAccess(x, components);
2406     }
2407   }
2408 
2409   CC genarr(const Fortran::evaluate::Component &x, ComponentPath &components) {
2410     TODO(getLoc(), "genarr Component");
2411   }
2412 
2413   CC genarr(const Fortran::evaluate::ArrayRef &x, ComponentPath &components) {
2414     TODO(getLoc(), "genar  ArrayRef");
2415   }
2416 
2417   CC genarr(const Fortran::evaluate::CoarrayRef &x, ComponentPath &components) {
2418     TODO(getLoc(), "coarray reference");
2419   }
2420 
2421   CC genarr(const Fortran::evaluate::NamedEntity &x,
2422             ComponentPath &components) {
2423     return x.IsSymbol() ? genarr(x.GetFirstSymbol(), components)
2424                         : genarr(x.GetComponent(), components);
2425   }
2426 
2427   CC genarr(const Fortran::evaluate::DataRef &x, ComponentPath &components) {
2428     return std::visit([&](const auto &v) { return genarr(v, components); },
2429                       x.u);
2430   }
2431 
2432   CC genarr(const Fortran::evaluate::ComplexPart &x,
2433             ComponentPath &components) {
2434     TODO(getLoc(), "genarr ComplexPart");
2435   }
2436 
2437   CC genarr(const Fortran::evaluate::StaticDataObject::Pointer &,
2438             ComponentPath &components) {
2439     TODO(getLoc(), "genarr StaticDataObject::Pointer");
2440   }
2441 
2442   /// Substrings (see 9.4.1)
2443   CC genarr(const Fortran::evaluate::Substring &x, ComponentPath &components) {
2444     TODO(getLoc(), "genarr Substring");
2445   }
2446 
2447   /// Base case of generating an array reference,
2448   CC genarr(const ExtValue &extMemref, ComponentPath &components) {
2449     mlir::Location loc = getLoc();
2450     mlir::Value memref = fir::getBase(extMemref);
2451     mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(memref.getType());
2452     assert(arrTy.isa<fir::SequenceType>() && "memory ref must be an array");
2453     mlir::Value shape = builder.createShape(loc, extMemref);
2454     mlir::Value slice;
2455     if (components.isSlice()) {
2456       TODO(loc, "genarr with Slices");
2457     }
2458     arrayOperands.push_back(ArrayOperand{memref, shape, slice});
2459     if (destShape.empty())
2460       destShape = getShape(arrayOperands.back());
2461     if (isBoxValue()) {
2462       TODO(loc, "genarr BoxValue");
2463     }
2464     if (isReferentiallyOpaque()) {
2465       TODO(loc, "genarr isReferentiallyOpaque");
2466     }
2467     auto arrLoad = builder.create<fir::ArrayLoadOp>(
2468         loc, arrTy, memref, shape, slice, fir::getTypeParams(extMemref));
2469     mlir::Value arrLd = arrLoad.getResult();
2470     if (isProjectedCopyInCopyOut()) {
2471       // Semantics are projected copy-in copy-out.
2472       // The backing store of the destination of an array expression may be
2473       // partially modified. These updates are recorded in FIR by forwarding a
2474       // continuation that generates an `array_update` Op. The destination is
2475       // always loaded at the beginning of the statement and merged at the
2476       // end.
2477       destination = arrLoad;
2478       auto lambda = ccStoreToDest.hasValue()
2479                         ? ccStoreToDest.getValue()
2480                         : defaultStoreToDestination(components.substring);
2481       return [=](IterSpace iters) -> ExtValue { return lambda(iters); };
2482     }
2483     if (isCustomCopyInCopyOut()) {
2484       TODO(loc, "isCustomCopyInCopyOut");
2485     }
2486     if (isCopyInCopyOut()) {
2487       // Semantics are copy-in copy-out.
2488       // The continuation simply forwards the result of the `array_load` Op,
2489       // which is the value of the array as it was when loaded. All data
2490       // references with rank > 0 in an array expression typically have
2491       // copy-in copy-out semantics.
2492       return [=](IterSpace) -> ExtValue { return arrLd; };
2493     }
2494     mlir::Operation::operand_range arrLdTypeParams = arrLoad.getTypeparams();
2495     if (isValueAttribute()) {
2496       // Semantics are value attribute.
2497       // Here the continuation will `array_fetch` a value from an array and
2498       // then store that value in a temporary. One can thus imitate pass by
2499       // value even when the call is pass by reference.
2500       return [=](IterSpace iters) -> ExtValue {
2501         mlir::Value base;
2502         mlir::Type eleTy = fir::applyPathToType(arrTy, iters.iterVec());
2503         if (isAdjustedArrayElementType(eleTy)) {
2504           mlir::Type eleRefTy = builder.getRefType(eleTy);
2505           base = builder.create<fir::ArrayAccessOp>(
2506               loc, eleRefTy, arrLd, iters.iterVec(), arrLdTypeParams);
2507         } else {
2508           base = builder.create<fir::ArrayFetchOp>(
2509               loc, eleTy, arrLd, iters.iterVec(), arrLdTypeParams);
2510         }
2511         mlir::Value temp = builder.createTemporary(
2512             loc, base.getType(),
2513             llvm::ArrayRef<mlir::NamedAttribute>{
2514                 Fortran::lower::getAdaptToByRefAttr(builder)});
2515         builder.create<fir::StoreOp>(loc, base, temp);
2516         return fir::factory::arraySectionElementToExtendedValue(
2517             builder, loc, extMemref, temp, slice);
2518       };
2519     }
2520     // In the default case, the array reference forwards an `array_fetch` or
2521     // `array_access` Op in the continuation.
2522     return [=](IterSpace iters) -> ExtValue {
2523       mlir::Type eleTy = fir::applyPathToType(arrTy, iters.iterVec());
2524       if (isAdjustedArrayElementType(eleTy)) {
2525         mlir::Type eleRefTy = builder.getRefType(eleTy);
2526         mlir::Value arrayOp = builder.create<fir::ArrayAccessOp>(
2527             loc, eleRefTy, arrLd, iters.iterVec(), arrLdTypeParams);
2528         if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) {
2529           llvm::SmallVector<mlir::Value> substringBounds;
2530           populateBounds(substringBounds, components.substring);
2531           if (!substringBounds.empty()) {
2532             // mlir::Value dstLen = fir::factory::genLenOfCharacter(
2533             //     builder, loc, arrLoad, iters.iterVec(), substringBounds);
2534             // fir::CharBoxValue dstChar(arrayOp, dstLen);
2535             // return fir::factory::CharacterExprHelper{builder, loc}
2536             //     .createSubstring(dstChar, substringBounds);
2537           }
2538         }
2539         return fir::factory::arraySectionElementToExtendedValue(
2540             builder, loc, extMemref, arrayOp, slice);
2541       }
2542       auto arrFetch = builder.create<fir::ArrayFetchOp>(
2543           loc, eleTy, arrLd, iters.iterVec(), arrLdTypeParams);
2544       return fir::factory::arraySectionElementToExtendedValue(
2545           builder, loc, extMemref, arrFetch, slice);
2546     };
2547   }
2548 
2549   /// Reduce the rank of a array to be boxed based on the slice's operands.
2550   static mlir::Type reduceRank(mlir::Type arrTy, mlir::Value slice) {
2551     if (slice) {
2552       auto slOp = mlir::dyn_cast<fir::SliceOp>(slice.getDefiningOp());
2553       assert(slOp && "expected slice op");
2554       auto seqTy = arrTy.dyn_cast<fir::SequenceType>();
2555       assert(seqTy && "expected array type");
2556       mlir::Operation::operand_range triples = slOp.getTriples();
2557       fir::SequenceType::Shape shape;
2558       // reduce the rank for each invariant dimension
2559       for (unsigned i = 1, end = triples.size(); i < end; i += 3)
2560         if (!mlir::isa_and_nonnull<fir::UndefOp>(triples[i].getDefiningOp()))
2561           shape.push_back(fir::SequenceType::getUnknownExtent());
2562       return fir::SequenceType::get(shape, seqTy.getEleTy());
2563     }
2564     // not sliced, so no change in rank
2565     return arrTy;
2566   }
2567 
2568 private:
2569   void determineShapeOfDest(const fir::ExtendedValue &lhs) {
2570     destShape = fir::factory::getExtents(builder, getLoc(), lhs);
2571   }
2572 
2573   void determineShapeOfDest(const Fortran::lower::SomeExpr &lhs) {
2574     if (!destShape.empty())
2575       return;
2576     // if (explicitSpaceIsActive() && determineShapeWithSlice(lhs))
2577     //   return;
2578     mlir::Type idxTy = builder.getIndexType();
2579     mlir::Location loc = getLoc();
2580     if (std::optional<Fortran::evaluate::ConstantSubscripts> constantShape =
2581             Fortran::evaluate::GetConstantExtents(converter.getFoldingContext(),
2582                                                   lhs))
2583       for (Fortran::common::ConstantSubscript extent : *constantShape)
2584         destShape.push_back(builder.createIntegerConstant(loc, idxTy, extent));
2585   }
2586 
2587   ExtValue lowerArrayExpression(const Fortran::lower::SomeExpr &exp) {
2588     mlir::Type resTy = converter.genType(exp);
2589     return std::visit(
2590         [&](const auto &e) { return lowerArrayExpression(genarr(e), resTy); },
2591         exp.u);
2592   }
2593   ExtValue lowerArrayExpression(const ExtValue &exv) {
2594     assert(!explicitSpace);
2595     mlir::Type resTy = fir::unwrapPassByRefType(fir::getBase(exv).getType());
2596     return lowerArrayExpression(genarr(exv), resTy);
2597   }
2598 
2599   void populateBounds(llvm::SmallVectorImpl<mlir::Value> &bounds,
2600                       const Fortran::evaluate::Substring *substring) {
2601     if (!substring)
2602       return;
2603     bounds.push_back(fir::getBase(asScalar(substring->lower())));
2604     if (auto upper = substring->upper())
2605       bounds.push_back(fir::getBase(asScalar(*upper)));
2606   }
2607 
2608   /// Default store to destination implementation.
2609   /// This implements the default case, which is to assign the value in
2610   /// `iters.element` into the destination array, `iters.innerArgument`. Handles
2611   /// by value and by reference assignment.
2612   CC defaultStoreToDestination(const Fortran::evaluate::Substring *substring) {
2613     return [=](IterSpace iterSpace) -> ExtValue {
2614       mlir::Location loc = getLoc();
2615       mlir::Value innerArg = iterSpace.innerArgument();
2616       fir::ExtendedValue exv = iterSpace.elementExv();
2617       mlir::Type arrTy = innerArg.getType();
2618       mlir::Type eleTy = fir::applyPathToType(arrTy, iterSpace.iterVec());
2619       if (isAdjustedArrayElementType(eleTy)) {
2620         TODO(loc, "isAdjustedArrayElementType");
2621       }
2622       // By value semantics. The element is being assigned by value.
2623       mlir::Value ele = builder.createConvert(loc, eleTy, fir::getBase(exv));
2624       auto update = builder.create<fir::ArrayUpdateOp>(
2625           loc, arrTy, innerArg, ele, iterSpace.iterVec(),
2626           destination.getTypeparams());
2627       return abstractArrayExtValue(update);
2628     };
2629   }
2630 
2631   /// For an elemental array expression.
2632   ///   1. Lower the scalars and array loads.
2633   ///   2. Create the iteration space.
2634   ///   3. Create the element-by-element computation in the loop.
2635   ///   4. Return the resulting array value.
2636   /// If no destination was set in the array context, a temporary of
2637   /// \p resultTy will be created to hold the evaluated expression.
2638   /// Otherwise, \p resultTy is ignored and the expression is evaluated
2639   /// in the destination. \p f is a continuation built from an
2640   /// evaluate::Expr or an ExtendedValue.
2641   ExtValue lowerArrayExpression(CC f, mlir::Type resultTy) {
2642     mlir::Location loc = getLoc();
2643     auto [iterSpace, insPt] = genIterSpace(resultTy);
2644     auto exv = f(iterSpace);
2645     iterSpace.setElement(std::move(exv));
2646     auto lambda = ccStoreToDest.hasValue()
2647                       ? ccStoreToDest.getValue()
2648                       : defaultStoreToDestination(/*substring=*/nullptr);
2649     mlir::Value updVal = fir::getBase(lambda(iterSpace));
2650     finalizeElementCtx();
2651     builder.create<fir::ResultOp>(loc, updVal);
2652     builder.restoreInsertionPoint(insPt);
2653     return abstractArrayExtValue(iterSpace.outerResult());
2654   }
2655 
2656   /// Get the shape from an ArrayOperand. The shape of the array is adjusted if
2657   /// the array was sliced.
2658   llvm::SmallVector<mlir::Value> getShape(ArrayOperand array) {
2659     // if (array.slice)
2660     //   return computeSliceShape(array.slice);
2661     if (array.memref.getType().isa<fir::BoxType>())
2662       return fir::factory::readExtents(builder, getLoc(),
2663                                        fir::BoxValue{array.memref});
2664     std::vector<mlir::Value, std::allocator<mlir::Value>> extents =
2665         fir::factory::getExtents(array.shape);
2666     return {extents.begin(), extents.end()};
2667   }
2668 
2669   /// Get the shape from an ArrayLoad.
2670   llvm::SmallVector<mlir::Value> getShape(fir::ArrayLoadOp arrayLoad) {
2671     return getShape(ArrayOperand{arrayLoad.getMemref(), arrayLoad.getShape(),
2672                                  arrayLoad.getSlice()});
2673   }
2674 
2675   /// Returns the first array operand that may not be absent. If all
2676   /// array operands may be absent, return the first one.
2677   const ArrayOperand &getInducingShapeArrayOperand() const {
2678     assert(!arrayOperands.empty());
2679     for (const ArrayOperand &op : arrayOperands)
2680       if (!op.mayBeAbsent)
2681         return op;
2682     // If all arrays operand appears in optional position, then none of them
2683     // is allowed to be absent as per 15.5.2.12 point 3. (6). Just pick the
2684     // first operands.
2685     // TODO: There is an opportunity to add a runtime check here that
2686     // this array is present as required.
2687     return arrayOperands[0];
2688   }
2689 
2690   /// Generate the shape of the iteration space over the array expression. The
2691   /// iteration space may be implicit, explicit, or both. If it is implied it is
2692   /// based on the destination and operand array loads, or an optional
2693   /// Fortran::evaluate::Shape from the front end. If the shape is explicit,
2694   /// this returns any implicit shape component, if it exists.
2695   llvm::SmallVector<mlir::Value> genIterationShape() {
2696     // Use the precomputed destination shape.
2697     if (!destShape.empty())
2698       return destShape;
2699     // Otherwise, use the destination's shape.
2700     if (destination)
2701       return getShape(destination);
2702     // Otherwise, use the first ArrayLoad operand shape.
2703     if (!arrayOperands.empty())
2704       return getShape(getInducingShapeArrayOperand());
2705     fir::emitFatalError(getLoc(),
2706                         "failed to compute the array expression shape");
2707   }
2708 
2709   bool explicitSpaceIsActive() const {
2710     return explicitSpace && explicitSpace->isActive();
2711   }
2712 
2713   bool implicitSpaceHasMasks() const {
2714     return implicitSpace && !implicitSpace->empty();
2715   }
2716 
2717   explicit ArrayExprLowering(Fortran::lower::AbstractConverter &converter,
2718                              Fortran::lower::StatementContext &stmtCtx,
2719                              Fortran::lower::SymMap &symMap)
2720       : converter{converter}, builder{converter.getFirOpBuilder()},
2721         stmtCtx{stmtCtx}, symMap{symMap} {}
2722 
2723   explicit ArrayExprLowering(Fortran::lower::AbstractConverter &converter,
2724                              Fortran::lower::StatementContext &stmtCtx,
2725                              Fortran::lower::SymMap &symMap,
2726                              ConstituentSemantics sem)
2727       : converter{converter}, builder{converter.getFirOpBuilder()},
2728         stmtCtx{stmtCtx}, symMap{symMap}, semant{sem} {}
2729 
2730   explicit ArrayExprLowering(Fortran::lower::AbstractConverter &converter,
2731                              Fortran::lower::StatementContext &stmtCtx,
2732                              Fortran::lower::SymMap &symMap,
2733                              ConstituentSemantics sem,
2734                              Fortran::lower::ExplicitIterSpace *expSpace,
2735                              Fortran::lower::ImplicitIterSpace *impSpace)
2736       : converter{converter}, builder{converter.getFirOpBuilder()},
2737         stmtCtx{stmtCtx}, symMap{symMap},
2738         explicitSpace(expSpace->isActive() ? expSpace : nullptr),
2739         implicitSpace(impSpace->empty() ? nullptr : impSpace), semant{sem} {
2740     // Generate any mask expressions, as necessary. This is the compute step
2741     // that creates the effective masks. See 10.2.3.2 in particular.
2742     // genMasks();
2743   }
2744 
2745   mlir::Location getLoc() { return converter.getCurrentLocation(); }
2746 
2747   /// Array appears in a lhs context such that it is assigned after the rhs is
2748   /// fully evaluated.
2749   inline bool isCopyInCopyOut() {
2750     return semant == ConstituentSemantics::CopyInCopyOut;
2751   }
2752 
2753   /// Array appears in a lhs (or temp) context such that a projected,
2754   /// discontiguous subspace of the array is assigned after the rhs is fully
2755   /// evaluated. That is, the rhs array value is merged into a section of the
2756   /// lhs array.
2757   inline bool isProjectedCopyInCopyOut() {
2758     return semant == ConstituentSemantics::ProjectedCopyInCopyOut;
2759   }
2760 
2761   inline bool isCustomCopyInCopyOut() {
2762     return semant == ConstituentSemantics::CustomCopyInCopyOut;
2763   }
2764 
2765   /// Array appears in a context where it must be boxed.
2766   inline bool isBoxValue() { return semant == ConstituentSemantics::BoxValue; }
2767 
2768   /// Array appears in a context where differences in the memory reference can
2769   /// be observable in the computational results. For example, an array
2770   /// element is passed to an impure procedure.
2771   inline bool isReferentiallyOpaque() {
2772     return semant == ConstituentSemantics::RefOpaque;
2773   }
2774 
2775   /// Array appears in a context where it is passed as a VALUE argument.
2776   inline bool isValueAttribute() {
2777     return semant == ConstituentSemantics::ByValueArg;
2778   }
2779 
2780   /// Can the loops over the expression be unordered?
2781   inline bool isUnordered() const { return unordered; }
2782 
2783   void setUnordered(bool b) { unordered = b; }
2784 
2785   Fortran::lower::AbstractConverter &converter;
2786   fir::FirOpBuilder &builder;
2787   Fortran::lower::StatementContext &stmtCtx;
2788   bool elementCtx = false;
2789   Fortran::lower::SymMap &symMap;
2790   /// The continuation to generate code to update the destination.
2791   llvm::Optional<CC> ccStoreToDest;
2792   llvm::Optional<std::function<void(llvm::ArrayRef<mlir::Value>)>> ccPrelude;
2793   llvm::Optional<std::function<fir::ArrayLoadOp(llvm::ArrayRef<mlir::Value>)>>
2794       ccLoadDest;
2795   /// The destination is the loaded array into which the results will be
2796   /// merged.
2797   fir::ArrayLoadOp destination;
2798   /// The shape of the destination.
2799   llvm::SmallVector<mlir::Value> destShape;
2800   /// List of arrays in the expression that have been loaded.
2801   llvm::SmallVector<ArrayOperand> arrayOperands;
2802   /// If there is a user-defined iteration space, explicitShape will hold the
2803   /// information from the front end.
2804   Fortran::lower::ExplicitIterSpace *explicitSpace = nullptr;
2805   Fortran::lower::ImplicitIterSpace *implicitSpace = nullptr;
2806   ConstituentSemantics semant = ConstituentSemantics::RefTransparent;
2807   // Can the array expression be evaluated in any order?
2808   // Will be set to false if any of the expression parts prevent this.
2809   bool unordered = true;
2810 };
2811 } // namespace
2812 
2813 fir::ExtendedValue Fortran::lower::createSomeExtendedExpression(
2814     mlir::Location loc, Fortran::lower::AbstractConverter &converter,
2815     const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
2816     Fortran::lower::StatementContext &stmtCtx) {
2817   LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "expr: ") << '\n');
2818   return ScalarExprLowering{loc, converter, symMap, stmtCtx}.genval(expr);
2819 }
2820 
2821 fir::GlobalOp Fortran::lower::createDenseGlobal(
2822     mlir::Location loc, mlir::Type symTy, llvm::StringRef globalName,
2823     mlir::StringAttr linkage, bool isConst,
2824     const Fortran::lower::SomeExpr &expr,
2825     Fortran::lower::AbstractConverter &converter) {
2826 
2827   Fortran::lower::StatementContext stmtCtx(/*prohibited=*/true);
2828   Fortran::lower::SymMap emptyMap;
2829   InitializerData initData(/*genRawVals=*/true);
2830   ScalarExprLowering sel(loc, converter, emptyMap, stmtCtx,
2831                          /*initializer=*/&initData);
2832   sel.genval(expr);
2833 
2834   size_t sz = initData.rawVals.size();
2835   llvm::ArrayRef<mlir::Attribute> ar = {initData.rawVals.data(), sz};
2836 
2837   mlir::RankedTensorType tensorTy;
2838   auto &builder = converter.getFirOpBuilder();
2839   mlir::Type iTy = initData.rawType;
2840   if (!iTy)
2841     return 0; // array extent is probably 0 in this case, so just return 0.
2842   tensorTy = mlir::RankedTensorType::get(sz, iTy);
2843   auto init = mlir::DenseElementsAttr::get(tensorTy, ar);
2844   return builder.createGlobal(loc, symTy, globalName, linkage, init, isConst);
2845 }
2846 
2847 fir::ExtendedValue Fortran::lower::createSomeInitializerExpression(
2848     mlir::Location loc, Fortran::lower::AbstractConverter &converter,
2849     const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
2850     Fortran::lower::StatementContext &stmtCtx) {
2851   LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "expr: ") << '\n');
2852   InitializerData initData; // needed for initializations
2853   return ScalarExprLowering{loc, converter, symMap, stmtCtx,
2854                             /*initializer=*/&initData}
2855       .genval(expr);
2856 }
2857 
2858 fir::ExtendedValue Fortran::lower::createSomeExtendedAddress(
2859     mlir::Location loc, Fortran::lower::AbstractConverter &converter,
2860     const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
2861     Fortran::lower::StatementContext &stmtCtx) {
2862   LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "address: ") << '\n');
2863   return ScalarExprLowering{loc, converter, symMap, stmtCtx}.gen(expr);
2864 }
2865 
2866 fir::ExtendedValue Fortran::lower::createInitializerAddress(
2867     mlir::Location loc, Fortran::lower::AbstractConverter &converter,
2868     const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
2869     Fortran::lower::StatementContext &stmtCtx) {
2870   LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "address: ") << '\n');
2871   InitializerData init;
2872   return ScalarExprLowering(loc, converter, symMap, stmtCtx, &init).gen(expr);
2873 }
2874 
2875 fir::ExtendedValue
2876 Fortran::lower::createSomeArrayBox(Fortran::lower::AbstractConverter &converter,
2877                                    const Fortran::lower::SomeExpr &expr,
2878                                    Fortran::lower::SymMap &symMap,
2879                                    Fortran::lower::StatementContext &stmtCtx) {
2880   LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "box designator: ") << '\n');
2881   return ArrayExprLowering::lowerBoxedArrayExpression(converter, symMap,
2882                                                       stmtCtx, expr);
2883 }
2884 
2885 fir::MutableBoxValue Fortran::lower::createMutableBox(
2886     mlir::Location loc, Fortran::lower::AbstractConverter &converter,
2887     const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap) {
2888   // MutableBox lowering StatementContext does not need to be propagated
2889   // to the caller because the result value is a variable, not a temporary
2890   // expression. The StatementContext clean-up can occur before using the
2891   // resulting MutableBoxValue. Variables of all other types are handled in the
2892   // bridge.
2893   Fortran::lower::StatementContext dummyStmtCtx;
2894   return ScalarExprLowering{loc, converter, symMap, dummyStmtCtx}
2895       .genMutableBoxValue(expr);
2896 }
2897 
2898 mlir::Value Fortran::lower::createSubroutineCall(
2899     AbstractConverter &converter, const evaluate::ProcedureRef &call,
2900     SymMap &symMap, StatementContext &stmtCtx) {
2901   mlir::Location loc = converter.getCurrentLocation();
2902 
2903   // Simple subroutine call, with potential alternate return.
2904   auto res = Fortran::lower::createSomeExtendedExpression(
2905       loc, converter, toEvExpr(call), symMap, stmtCtx);
2906   return fir::getBase(res);
2907 }
2908 
2909 void Fortran::lower::createSomeArrayAssignment(
2910     Fortran::lower::AbstractConverter &converter,
2911     const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
2912     Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
2913   LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "onto array: ") << '\n';
2914              rhs.AsFortran(llvm::dbgs() << "assign expression: ") << '\n';);
2915   ArrayExprLowering::lowerArrayAssignment(converter, symMap, stmtCtx, lhs, rhs);
2916 }
2917 
2918 void Fortran::lower::createSomeArrayAssignment(
2919     Fortran::lower::AbstractConverter &converter, const fir::ExtendedValue &lhs,
2920     const fir::ExtendedValue &rhs, Fortran::lower::SymMap &symMap,
2921     Fortran::lower::StatementContext &stmtCtx) {
2922   LLVM_DEBUG(llvm::dbgs() << "onto array: " << lhs << '\n';
2923              llvm::dbgs() << "assign expression: " << rhs << '\n';);
2924   ArrayExprLowering::lowerArrayAssignment(converter, symMap, stmtCtx, lhs, rhs);
2925 }
2926 
2927 void Fortran::lower::createAllocatableArrayAssignment(
2928     Fortran::lower::AbstractConverter &converter,
2929     const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
2930     Fortran::lower::ExplicitIterSpace &explicitSpace,
2931     Fortran::lower::ImplicitIterSpace &implicitSpace,
2932     Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
2933   LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "defining array: ") << '\n';
2934              rhs.AsFortran(llvm::dbgs() << "assign expression: ")
2935              << " given the explicit iteration space:\n"
2936              << explicitSpace << "\n and implied mask conditions:\n"
2937              << implicitSpace << '\n';);
2938   ArrayExprLowering::lowerAllocatableArrayAssignment(
2939       converter, symMap, stmtCtx, lhs, rhs, explicitSpace, implicitSpace);
2940 }
2941