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/Common/default-kinds.h"
15 #include "flang/Common/unwrap.h"
16 #include "flang/Evaluate/fold.h"
17 #include "flang/Evaluate/real.h"
18 #include "flang/Evaluate/traverse.h"
19 #include "flang/Lower/Allocatable.h"
20 #include "flang/Lower/Bridge.h"
21 #include "flang/Lower/BuiltinModules.h"
22 #include "flang/Lower/CallInterface.h"
23 #include "flang/Lower/Coarray.h"
24 #include "flang/Lower/ComponentPath.h"
25 #include "flang/Lower/ConvertType.h"
26 #include "flang/Lower/ConvertVariable.h"
27 #include "flang/Lower/CustomIntrinsicCall.h"
28 #include "flang/Lower/DumpEvaluateExpr.h"
29 #include "flang/Lower/IntrinsicCall.h"
30 #include "flang/Lower/Mangler.h"
31 #include "flang/Lower/Runtime.h"
32 #include "flang/Lower/Support/Utils.h"
33 #include "flang/Lower/Todo.h"
34 #include "flang/Optimizer/Builder/Character.h"
35 #include "flang/Optimizer/Builder/Complex.h"
36 #include "flang/Optimizer/Builder/Factory.h"
37 #include "flang/Optimizer/Builder/Runtime/Character.h"
38 #include "flang/Optimizer/Builder/Runtime/RTBuilder.h"
39 #include "flang/Optimizer/Builder/Runtime/Ragged.h"
40 #include "flang/Optimizer/Dialect/FIRAttr.h"
41 #include "flang/Optimizer/Dialect/FIRDialect.h"
42 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
43 #include "flang/Optimizer/Support/FatalError.h"
44 #include "flang/Semantics/expression.h"
45 #include "flang/Semantics/symbol.h"
46 #include "flang/Semantics/tools.h"
47 #include "flang/Semantics/type.h"
48 #include "mlir/Dialect/Func/IR/FuncOps.h"
49 #include "llvm/ADT/TypeSwitch.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include <algorithm>
55 
56 #define DEBUG_TYPE "flang-lower-expr"
57 
58 //===----------------------------------------------------------------------===//
59 // The composition and structure of Fortran::evaluate::Expr is defined in
60 // the various header files in include/flang/Evaluate. You are referred
61 // there for more information on these data structures. Generally speaking,
62 // these data structures are a strongly typed family of abstract data types
63 // that, composed as trees, describe the syntax of Fortran expressions.
64 //
65 // This part of the bridge can traverse these tree structures and lower them
66 // to the correct FIR representation in SSA form.
67 //===----------------------------------------------------------------------===//
68 
69 static llvm::cl::opt<bool> generateArrayCoordinate(
70     "gen-array-coor",
71     llvm::cl::desc("in lowering create ArrayCoorOp instead of CoordinateOp"),
72     llvm::cl::init(false));
73 
74 // The default attempts to balance a modest allocation size with expected user
75 // input to minimize bounds checks and reallocations during dynamic array
76 // construction. Some user codes may have very large array constructors for
77 // which the default can be increased.
78 static llvm::cl::opt<unsigned> clInitialBufferSize(
79     "array-constructor-initial-buffer-size",
80     llvm::cl::desc(
81         "set the incremental array construction buffer size (default=32)"),
82     llvm::cl::init(32u));
83 
84 /// The various semantics of a program constituent (or a part thereof) as it may
85 /// appear in an expression.
86 ///
87 /// Given the following Fortran declarations.
88 /// ```fortran
89 ///   REAL :: v1, v2, v3
90 ///   REAL, POINTER :: vp1
91 ///   REAL :: a1(c), a2(c)
92 ///   REAL ELEMENTAL FUNCTION f1(arg) ! array -> array
93 ///   FUNCTION f2(arg)                ! array -> array
94 ///   vp1 => v3       ! 1
95 ///   v1 = v2 * vp1   ! 2
96 ///   a1 = a1 + a2    ! 3
97 ///   a1 = f1(a2)     ! 4
98 ///   a1 = f2(a2)     ! 5
99 /// ```
100 ///
101 /// In line 1, `vp1` is a BoxAddr to copy a box value into. The box value is
102 /// constructed from the DataAddr of `v3`.
103 /// In line 2, `v1` is a DataAddr to copy a value into. The value is constructed
104 /// from the DataValue of `v2` and `vp1`. DataValue is implicitly a double
105 /// dereference in the `vp1` case.
106 /// In line 3, `a1` and `a2` on the rhs are RefTransparent. The `a1` on the lhs
107 /// is CopyInCopyOut as `a1` is replaced elementally by the additions.
108 /// In line 4, `a2` can be RefTransparent, ByValueArg, RefOpaque, or BoxAddr if
109 /// `arg` is declared as C-like pass-by-value, VALUE, INTENT(?), or ALLOCATABLE/
110 /// POINTER, respectively. `a1` on the lhs is CopyInCopyOut.
111 ///  In line 5, `a2` may be DataAddr or BoxAddr assuming f2 is transformational.
112 ///  `a1` on the lhs is again CopyInCopyOut.
113 enum class ConstituentSemantics {
114   // Scalar data reference semantics.
115   //
116   // For these let `v` be the location in memory of a variable with value `x`
117   DataValue, // refers to the value `x`
118   DataAddr,  // refers to the address `v`
119   BoxValue,  // refers to a box value containing `v`
120   BoxAddr,   // refers to the address of a box value containing `v`
121 
122   // Array data reference semantics.
123   //
124   // For these let `a` be the location in memory of a sequence of value `[xs]`.
125   // Let `x_i` be the `i`-th value in the sequence `[xs]`.
126 
127   // Referentially transparent. Refers to the array's value, `[xs]`.
128   RefTransparent,
129   // Refers to an ephemeral address `tmp` containing value `x_i` (15.5.2.3.p7
130   // note 2). (Passing a copy by reference to simulate pass-by-value.)
131   ByValueArg,
132   // Refers to the merge of array value `[xs]` with another array value `[ys]`.
133   // This merged array value will be written into memory location `a`.
134   CopyInCopyOut,
135   // Similar to CopyInCopyOut but `a` may be a transient projection (rather than
136   // a whole array).
137   ProjectedCopyInCopyOut,
138   // Similar to ProjectedCopyInCopyOut, except the merge value is not assigned
139   // automatically by the framework. Instead, and address for `[xs]` is made
140   // accessible so that custom assignments to `[xs]` can be implemented.
141   CustomCopyInCopyOut,
142   // Referentially opaque. Refers to the address of `x_i`.
143   RefOpaque
144 };
145 
146 /// Convert parser's INTEGER relational operators to MLIR.  TODO: using
147 /// unordered, but we may want to cons ordered in certain situation.
148 static mlir::arith::CmpIPredicate
149 translateRelational(Fortran::common::RelationalOperator rop) {
150   switch (rop) {
151   case Fortran::common::RelationalOperator::LT:
152     return mlir::arith::CmpIPredicate::slt;
153   case Fortran::common::RelationalOperator::LE:
154     return mlir::arith::CmpIPredicate::sle;
155   case Fortran::common::RelationalOperator::EQ:
156     return mlir::arith::CmpIPredicate::eq;
157   case Fortran::common::RelationalOperator::NE:
158     return mlir::arith::CmpIPredicate::ne;
159   case Fortran::common::RelationalOperator::GT:
160     return mlir::arith::CmpIPredicate::sgt;
161   case Fortran::common::RelationalOperator::GE:
162     return mlir::arith::CmpIPredicate::sge;
163   }
164   llvm_unreachable("unhandled INTEGER relational operator");
165 }
166 
167 /// Convert parser's REAL relational operators to MLIR.
168 /// The choice of order (O prefix) vs unorder (U prefix) follows Fortran 2018
169 /// requirements in the IEEE context (table 17.1 of F2018). This choice is
170 /// also applied in other contexts because it is easier and in line with
171 /// other Fortran compilers.
172 /// FIXME: The signaling/quiet aspect of the table 17.1 requirement is not
173 /// fully enforced. FIR and LLVM `fcmp` instructions do not give any guarantee
174 /// whether the comparison will signal or not in case of quiet NaN argument.
175 static mlir::arith::CmpFPredicate
176 translateFloatRelational(Fortran::common::RelationalOperator rop) {
177   switch (rop) {
178   case Fortran::common::RelationalOperator::LT:
179     return mlir::arith::CmpFPredicate::OLT;
180   case Fortran::common::RelationalOperator::LE:
181     return mlir::arith::CmpFPredicate::OLE;
182   case Fortran::common::RelationalOperator::EQ:
183     return mlir::arith::CmpFPredicate::OEQ;
184   case Fortran::common::RelationalOperator::NE:
185     return mlir::arith::CmpFPredicate::UNE;
186   case Fortran::common::RelationalOperator::GT:
187     return mlir::arith::CmpFPredicate::OGT;
188   case Fortran::common::RelationalOperator::GE:
189     return mlir::arith::CmpFPredicate::OGE;
190   }
191   llvm_unreachable("unhandled REAL relational operator");
192 }
193 
194 static mlir::Value genActualIsPresentTest(fir::FirOpBuilder &builder,
195                                           mlir::Location loc,
196                                           fir::ExtendedValue actual) {
197   if (const auto *ptrOrAlloc = actual.getBoxOf<fir::MutableBoxValue>())
198     return fir::factory::genIsAllocatedOrAssociatedTest(builder, loc,
199                                                         *ptrOrAlloc);
200   // Optional case (not that optional allocatable/pointer cannot be absent
201   // when passed to CMPLX as per 15.5.2.12 point 3 (7) and (8)). It is
202   // therefore possible to catch them in the `then` case above.
203   return builder.create<fir::IsPresentOp>(loc, builder.getI1Type(),
204                                           fir::getBase(actual));
205 }
206 
207 /// Convert the array_load, `load`, to an extended value. If `path` is not
208 /// empty, then traverse through the components designated. The base value is
209 /// `newBase`. This does not accept an array_load with a slice operand.
210 static fir::ExtendedValue
211 arrayLoadExtValue(fir::FirOpBuilder &builder, mlir::Location loc,
212                   fir::ArrayLoadOp load, llvm::ArrayRef<mlir::Value> path,
213                   mlir::Value newBase, mlir::Value newLen = {}) {
214   // Recover the extended value from the load.
215   if (load.getSlice())
216     fir::emitFatalError(loc, "array_load with slice is not allowed");
217   mlir::Type arrTy = load.getType();
218   if (!path.empty()) {
219     mlir::Type ty = fir::applyPathToType(arrTy, path);
220     if (!ty)
221       fir::emitFatalError(loc, "path does not apply to type");
222     if (!ty.isa<fir::SequenceType>()) {
223       if (fir::isa_char(ty)) {
224         mlir::Value len = newLen;
225         if (!len)
226           len = fir::factory::CharacterExprHelper{builder, loc}.getLength(
227               load.getMemref());
228         if (!len) {
229           assert(load.getTypeparams().size() == 1 &&
230                  "length must be in array_load");
231           len = load.getTypeparams()[0];
232         }
233         return fir::CharBoxValue{newBase, len};
234       }
235       return newBase;
236     }
237     arrTy = ty.cast<fir::SequenceType>();
238   }
239 
240   auto arrayToExtendedValue =
241       [&](const llvm::SmallVector<mlir::Value> &extents,
242           const llvm::SmallVector<mlir::Value> &origins) -> fir::ExtendedValue {
243     mlir::Type eleTy = fir::unwrapSequenceType(arrTy);
244     if (fir::isa_char(eleTy)) {
245       mlir::Value len = newLen;
246       if (!len)
247         len = fir::factory::CharacterExprHelper{builder, loc}.getLength(
248             load.getMemref());
249       if (!len) {
250         assert(load.getTypeparams().size() == 1 &&
251                "length must be in array_load");
252         len = load.getTypeparams()[0];
253       }
254       return fir::CharArrayBoxValue(newBase, len, extents, origins);
255     }
256     return fir::ArrayBoxValue(newBase, extents, origins);
257   };
258   // Use the shape op, if there is one.
259   mlir::Value shapeVal = load.getShape();
260   if (shapeVal) {
261     if (!mlir::isa<fir::ShiftOp>(shapeVal.getDefiningOp())) {
262       auto extents = fir::factory::getExtents(shapeVal);
263       auto origins = fir::factory::getOrigins(shapeVal);
264       return arrayToExtendedValue(extents, origins);
265     }
266     if (!fir::isa_box_type(load.getMemref().getType()))
267       fir::emitFatalError(loc, "shift op is invalid in this context");
268   }
269 
270   // If we're dealing with the array_load op (not a subobject) and the load does
271   // not have any type parameters, then read the extents from the original box.
272   // The origin may be either from the box or a shift operation. Create and
273   // return the array extended value.
274   if (path.empty() && load.getTypeparams().empty()) {
275     auto oldBox = load.getMemref();
276     fir::ExtendedValue exv = fir::factory::readBoxValue(builder, loc, oldBox);
277     auto extents = fir::factory::getExtents(loc, builder, exv);
278     auto origins = fir::factory::getNonDefaultLowerBounds(builder, loc, exv);
279     if (shapeVal) {
280       // shapeVal is a ShiftOp and load.memref() is a boxed value.
281       newBase = builder.create<fir::ReboxOp>(loc, oldBox.getType(), oldBox,
282                                              shapeVal, /*slice=*/mlir::Value{});
283       origins = fir::factory::getOrigins(shapeVal);
284     }
285     return fir::substBase(arrayToExtendedValue(extents, origins), newBase);
286   }
287   TODO(loc, "path to a POINTER, ALLOCATABLE, or other component that requires "
288             "dereferencing; generating the type parameters is a hard "
289             "requirement for correctness.");
290 }
291 
292 /// Place \p exv in memory if it is not already a memory reference. If
293 /// \p forceValueType is provided, the value is first casted to the provided
294 /// type before being stored (this is mainly intended for logicals whose value
295 /// may be `i1` but needed to be stored as Fortran logicals).
296 static fir::ExtendedValue
297 placeScalarValueInMemory(fir::FirOpBuilder &builder, mlir::Location loc,
298                          const fir::ExtendedValue &exv,
299                          mlir::Type storageType) {
300   mlir::Value valBase = fir::getBase(exv);
301   if (fir::conformsWithPassByRef(valBase.getType()))
302     return exv;
303 
304   assert(!fir::hasDynamicSize(storageType) &&
305          "only expect statically sized scalars to be by value");
306 
307   // Since `a` is not itself a valid referent, determine its value and
308   // create a temporary location at the beginning of the function for
309   // referencing.
310   mlir::Value val = builder.createConvert(loc, storageType, valBase);
311   mlir::Value temp = builder.createTemporary(
312       loc, storageType,
313       llvm::ArrayRef<mlir::NamedAttribute>{
314           Fortran::lower::getAdaptToByRefAttr(builder)});
315   builder.create<fir::StoreOp>(loc, val, temp);
316   return fir::substBase(exv, temp);
317 }
318 
319 // Copy a copy of scalar \p exv in a new temporary.
320 static fir::ExtendedValue
321 createInMemoryScalarCopy(fir::FirOpBuilder &builder, mlir::Location loc,
322                          const fir::ExtendedValue &exv) {
323   assert(exv.rank() == 0 && "input to scalar memory copy must be a scalar");
324   if (exv.getCharBox() != nullptr)
325     return fir::factory::CharacterExprHelper{builder, loc}.createTempFrom(exv);
326   if (fir::isDerivedWithLenParameters(exv))
327     TODO(loc, "copy derived type with length parameters");
328   mlir::Type type = fir::unwrapPassByRefType(fir::getBase(exv).getType());
329   fir::ExtendedValue temp = builder.createTemporary(loc, type);
330   fir::factory::genScalarAssignment(builder, loc, temp, exv);
331   return temp;
332 }
333 
334 // An expression with non-zero rank is an array expression.
335 template <typename A>
336 static bool isArray(const A &x) {
337   return x.Rank() != 0;
338 }
339 
340 /// Is this a variable wrapped in parentheses?
341 template <typename A>
342 static bool isParenthesizedVariable(const A &) {
343   return false;
344 }
345 template <typename T>
346 static bool isParenthesizedVariable(const Fortran::evaluate::Expr<T> &expr) {
347   using ExprVariant = decltype(Fortran::evaluate::Expr<T>::u);
348   using Parentheses = Fortran::evaluate::Parentheses<T>;
349   if constexpr (Fortran::common::HasMember<Parentheses, ExprVariant>) {
350     if (const auto *parentheses = std::get_if<Parentheses>(&expr.u))
351       return Fortran::evaluate::IsVariable(parentheses->left());
352     return false;
353   } else {
354     return std::visit([&](const auto &x) { return isParenthesizedVariable(x); },
355                       expr.u);
356   }
357 }
358 
359 /// Does \p expr only refer to symbols that are mapped to IR values in \p symMap
360 /// ?
361 static bool allSymbolsInExprPresentInMap(const Fortran::lower::SomeExpr &expr,
362                                          Fortran::lower::SymMap &symMap) {
363   for (const auto &sym : Fortran::evaluate::CollectSymbols(expr))
364     if (!symMap.lookupSymbol(sym))
365       return false;
366   return true;
367 }
368 
369 /// Generate a load of a value from an address. Beware that this will lose
370 /// any dynamic type information for polymorphic entities (note that unlimited
371 /// polymorphic cannot be loaded and must not be provided here).
372 static fir::ExtendedValue genLoad(fir::FirOpBuilder &builder,
373                                   mlir::Location loc,
374                                   const fir::ExtendedValue &addr) {
375   return addr.match(
376       [](const fir::CharBoxValue &box) -> fir::ExtendedValue { return box; },
377       [&](const fir::UnboxedValue &v) -> fir::ExtendedValue {
378         if (fir::unwrapRefType(fir::getBase(v).getType())
379                 .isa<fir::RecordType>())
380           return v;
381         return builder.create<fir::LoadOp>(loc, fir::getBase(v));
382       },
383       [&](const fir::MutableBoxValue &box) -> fir::ExtendedValue {
384         return genLoad(builder, loc,
385                        fir::factory::genMutableBoxRead(builder, loc, box));
386       },
387       [&](const fir::BoxValue &box) -> fir::ExtendedValue {
388         if (box.isUnlimitedPolymorphic())
389           fir::emitFatalError(
390               loc,
391               "lowering attempting to load an unlimited polymorphic entity");
392         return genLoad(builder, loc,
393                        fir::factory::readBoxValue(builder, loc, box));
394       },
395       [&](const auto &) -> fir::ExtendedValue {
396         fir::emitFatalError(
397             loc, "attempting to load whole array or procedure address");
398       });
399 }
400 
401 /// Create an optional dummy argument value from entity \p exv that may be
402 /// absent. This can only be called with numerical or logical scalar \p exv.
403 /// If \p exv is considered absent according to 15.5.2.12 point 1., the returned
404 /// value is zero (or false), otherwise it is the value of \p exv.
405 static fir::ExtendedValue genOptionalValue(fir::FirOpBuilder &builder,
406                                            mlir::Location loc,
407                                            const fir::ExtendedValue &exv,
408                                            mlir::Value isPresent) {
409   mlir::Type eleType = fir::getBaseTypeOf(exv);
410   assert(exv.rank() == 0 && fir::isa_trivial(eleType) &&
411          "must be a numerical or logical scalar");
412   return builder
413       .genIfOp(loc, {eleType}, isPresent,
414                /*withElseRegion=*/true)
415       .genThen([&]() {
416         mlir::Value val = fir::getBase(genLoad(builder, loc, exv));
417         builder.create<fir::ResultOp>(loc, val);
418       })
419       .genElse([&]() {
420         mlir::Value zero = fir::factory::createZeroValue(builder, loc, eleType);
421         builder.create<fir::ResultOp>(loc, zero);
422       })
423       .getResults()[0];
424 }
425 
426 /// Create an optional dummy argument address from entity \p exv that may be
427 /// absent. If \p exv is considered absent according to 15.5.2.12 point 1., the
428 /// returned value is a null pointer, otherwise it is the address of \p exv.
429 static fir::ExtendedValue genOptionalAddr(fir::FirOpBuilder &builder,
430                                           mlir::Location loc,
431                                           const fir::ExtendedValue &exv,
432                                           mlir::Value isPresent) {
433   // If it is an exv pointer/allocatable, then it cannot be absent
434   // because it is passed to a non-pointer/non-allocatable.
435   if (const auto *box = exv.getBoxOf<fir::MutableBoxValue>())
436     return fir::factory::genMutableBoxRead(builder, loc, *box);
437   // If this is not a POINTER or ALLOCATABLE, then it is already an OPTIONAL
438   // address and can be passed directly.
439   return exv;
440 }
441 
442 /// Create an optional dummy argument address from entity \p exv that may be
443 /// absent. If \p exv is considered absent according to 15.5.2.12 point 1., the
444 /// returned value is an absent fir.box, otherwise it is a fir.box describing \p
445 /// exv.
446 static fir::ExtendedValue genOptionalBox(fir::FirOpBuilder &builder,
447                                          mlir::Location loc,
448                                          const fir::ExtendedValue &exv,
449                                          mlir::Value isPresent) {
450   // Non allocatable/pointer optional box -> simply forward
451   if (exv.getBoxOf<fir::BoxValue>())
452     return exv;
453 
454   fir::ExtendedValue newExv = exv;
455   // Optional allocatable/pointer -> Cannot be absent, but need to translate
456   // unallocated/diassociated into absent fir.box.
457   if (const auto *box = exv.getBoxOf<fir::MutableBoxValue>())
458     newExv = fir::factory::genMutableBoxRead(builder, loc, *box);
459 
460   // createBox will not do create any invalid memory dereferences if exv is
461   // absent. The created fir.box will not be usable, but the SelectOp below
462   // ensures it won't be.
463   mlir::Value box = builder.createBox(loc, newExv);
464   mlir::Type boxType = box.getType();
465   auto absent = builder.create<fir::AbsentOp>(loc, boxType);
466   auto boxOrAbsent = builder.create<mlir::arith::SelectOp>(
467       loc, boxType, isPresent, box, absent);
468   return fir::BoxValue(boxOrAbsent);
469 }
470 
471 /// Is this a call to an elemental procedure with at least one array argument?
472 static bool
473 isElementalProcWithArrayArgs(const Fortran::evaluate::ProcedureRef &procRef) {
474   if (procRef.IsElemental())
475     for (const std::optional<Fortran::evaluate::ActualArgument> &arg :
476          procRef.arguments())
477       if (arg && arg->Rank() != 0)
478         return true;
479   return false;
480 }
481 template <typename T>
482 static bool isElementalProcWithArrayArgs(const Fortran::evaluate::Expr<T> &) {
483   return false;
484 }
485 template <>
486 bool isElementalProcWithArrayArgs(const Fortran::lower::SomeExpr &x) {
487   if (const auto *procRef = std::get_if<Fortran::evaluate::ProcedureRef>(&x.u))
488     return isElementalProcWithArrayArgs(*procRef);
489   return false;
490 }
491 
492 /// Some auxiliary data for processing initialization in ScalarExprLowering
493 /// below. This is currently used for generating dense attributed global
494 /// arrays.
495 struct InitializerData {
496   explicit InitializerData(bool getRawVals = false) : genRawVals{getRawVals} {}
497   llvm::SmallVector<mlir::Attribute> rawVals; // initialization raw values
498   mlir::Type rawType; // Type of elements processed for rawVals vector.
499   bool genRawVals;    // generate the rawVals vector if set.
500 };
501 
502 /// If \p arg is the address of a function with a denoted host-association tuple
503 /// argument, then return the host-associations tuple value of the current
504 /// procedure. Otherwise, return nullptr.
505 static mlir::Value
506 argumentHostAssocs(Fortran::lower::AbstractConverter &converter,
507                    mlir::Value arg) {
508   if (auto addr = mlir::dyn_cast_or_null<fir::AddrOfOp>(arg.getDefiningOp())) {
509     auto &builder = converter.getFirOpBuilder();
510     if (auto funcOp = builder.getNamedFunction(addr.getSymbol()))
511       if (fir::anyFuncArgsHaveAttr(funcOp, fir::getHostAssocAttrName()))
512         return converter.hostAssocTupleValue();
513   }
514   return {};
515 }
516 
517 /// \p argTy must be a tuple (pair) of boxproc and integral types. Convert the
518 /// \p funcAddr argument to a boxproc value, with the host-association as
519 /// required. Call the factory function to finish creating the tuple value.
520 static mlir::Value
521 createBoxProcCharTuple(Fortran::lower::AbstractConverter &converter,
522                        mlir::Type argTy, mlir::Value funcAddr,
523                        mlir::Value charLen) {
524   auto boxTy =
525       argTy.cast<mlir::TupleType>().getType(0).cast<fir::BoxProcType>();
526   mlir::Location loc = converter.getCurrentLocation();
527   auto &builder = converter.getFirOpBuilder();
528   auto boxProc = [&]() -> mlir::Value {
529     if (auto host = argumentHostAssocs(converter, funcAddr))
530       return builder.create<fir::EmboxProcOp>(
531           loc, boxTy, llvm::ArrayRef<mlir::Value>{funcAddr, host});
532     return builder.create<fir::EmboxProcOp>(loc, boxTy, funcAddr);
533   }();
534   return fir::factory::createCharacterProcedureTuple(builder, loc, argTy,
535                                                      boxProc, charLen);
536 }
537 
538 // Helper to get the ultimate first symbol. This works around the fact that
539 // symbol resolution in the front end doesn't always resolve a symbol to its
540 // ultimate symbol but may leave placeholder indirections for use and host
541 // associations.
542 template <typename A>
543 const Fortran::semantics::Symbol &getFirstSym(const A &obj) {
544   return obj.GetFirstSymbol().GetUltimate();
545 }
546 
547 // Helper to get the ultimate last symbol.
548 template <typename A>
549 const Fortran::semantics::Symbol &getLastSym(const A &obj) {
550   return obj.GetLastSymbol().GetUltimate();
551 }
552 
553 namespace {
554 
555 /// Lowering of Fortran::evaluate::Expr<T> expressions
556 class ScalarExprLowering {
557 public:
558   using ExtValue = fir::ExtendedValue;
559 
560   explicit ScalarExprLowering(mlir::Location loc,
561                               Fortran::lower::AbstractConverter &converter,
562                               Fortran::lower::SymMap &symMap,
563                               Fortran::lower::StatementContext &stmtCtx,
564                               InitializerData *initializer = nullptr)
565       : location{loc}, converter{converter},
566         builder{converter.getFirOpBuilder()}, stmtCtx{stmtCtx}, symMap{symMap},
567         inInitializer{initializer} {}
568 
569   ExtValue genExtAddr(const Fortran::lower::SomeExpr &expr) {
570     return gen(expr);
571   }
572 
573   /// Lower `expr` to be passed as a fir.box argument. Do not create a temp
574   /// for the expr if it is a variable that can be described as a fir.box.
575   ExtValue genBoxArg(const Fortran::lower::SomeExpr &expr) {
576     bool saveUseBoxArg = useBoxArg;
577     useBoxArg = true;
578     ExtValue result = gen(expr);
579     useBoxArg = saveUseBoxArg;
580     return result;
581   }
582 
583   ExtValue genExtValue(const Fortran::lower::SomeExpr &expr) {
584     return genval(expr);
585   }
586 
587   /// Lower an expression that is a pointer or an allocatable to a
588   /// MutableBoxValue.
589   fir::MutableBoxValue
590   genMutableBoxValue(const Fortran::lower::SomeExpr &expr) {
591     // Pointers and allocatables can only be:
592     //    - a simple designator "x"
593     //    - a component designator "a%b(i,j)%x"
594     //    - a function reference "foo()"
595     //    - result of NULL() or NULL(MOLD) intrinsic.
596     //    NULL() requires some context to be lowered, so it is not handled
597     //    here and must be lowered according to the context where it appears.
598     ExtValue exv = std::visit(
599         [&](const auto &x) { return genMutableBoxValueImpl(x); }, expr.u);
600     const fir::MutableBoxValue *mutableBox =
601         exv.getBoxOf<fir::MutableBoxValue>();
602     if (!mutableBox)
603       fir::emitFatalError(getLoc(), "expr was not lowered to MutableBoxValue");
604     return *mutableBox;
605   }
606 
607   template <typename T>
608   ExtValue genMutableBoxValueImpl(const T &) {
609     // NULL() case should not be handled here.
610     fir::emitFatalError(getLoc(), "NULL() must be lowered in its context");
611   }
612 
613   /// A `NULL()` in a position where a mutable box is expected has the same
614   /// semantics as an absent optional box value.
615   ExtValue genMutableBoxValueImpl(const Fortran::evaluate::NullPointer &) {
616     mlir::Location loc = getLoc();
617     auto nullConst = builder.createNullConstant(loc);
618     auto noneTy = mlir::NoneType::get(builder.getContext());
619     auto polyRefTy = fir::LLVMPointerType::get(noneTy);
620     // MutableBoxValue will dereference the box, so create a bogus temporary for
621     // the `nullptr`. The LLVM optimizer will garbage collect the temp.
622     auto temp =
623         builder.createTemporary(loc, polyRefTy, /*shape=*/mlir::ValueRange{});
624     auto nullPtr = builder.createConvert(loc, polyRefTy, nullConst);
625     builder.create<fir::StoreOp>(loc, nullPtr, temp);
626     auto nullBoxTy = builder.getRefType(fir::BoxType::get(noneTy));
627     return fir::MutableBoxValue(builder.createConvert(loc, nullBoxTy, temp),
628                                 /*lenParameters=*/mlir::ValueRange{},
629                                 /*mutableProperties=*/{});
630   }
631 
632   template <typename T>
633   ExtValue
634   genMutableBoxValueImpl(const Fortran::evaluate::FunctionRef<T> &funRef) {
635     return genRawProcedureRef(funRef, converter.genType(toEvExpr(funRef)));
636   }
637 
638   template <typename T>
639   ExtValue
640   genMutableBoxValueImpl(const Fortran::evaluate::Designator<T> &designator) {
641     return std::visit(
642         Fortran::common::visitors{
643             [&](const Fortran::evaluate::SymbolRef &sym) -> ExtValue {
644               return symMap.lookupSymbol(*sym).toExtendedValue();
645             },
646             [&](const Fortran::evaluate::Component &comp) -> ExtValue {
647               return genComponent(comp);
648             },
649             [&](const auto &) -> ExtValue {
650               fir::emitFatalError(getLoc(),
651                                   "not an allocatable or pointer designator");
652             }},
653         designator.u);
654   }
655 
656   template <typename T>
657   ExtValue genMutableBoxValueImpl(const Fortran::evaluate::Expr<T> &expr) {
658     return std::visit([&](const auto &x) { return genMutableBoxValueImpl(x); },
659                       expr.u);
660   }
661 
662   mlir::Location getLoc() { return location; }
663 
664   template <typename A>
665   mlir::Value genunbox(const A &expr) {
666     ExtValue e = genval(expr);
667     if (const fir::UnboxedValue *r = e.getUnboxed())
668       return *r;
669     fir::emitFatalError(getLoc(), "unboxed expression expected");
670   }
671 
672   /// Generate an integral constant of `value`
673   template <int KIND>
674   mlir::Value genIntegerConstant(mlir::MLIRContext *context,
675                                  std::int64_t value) {
676     mlir::Type type =
677         converter.genType(Fortran::common::TypeCategory::Integer, KIND);
678     return builder.createIntegerConstant(getLoc(), type, value);
679   }
680 
681   /// Generate a logical/boolean constant of `value`
682   mlir::Value genBoolConstant(bool value) {
683     return builder.createBool(getLoc(), value);
684   }
685 
686   /// Generate a real constant with a value `value`.
687   template <int KIND>
688   mlir::Value genRealConstant(mlir::MLIRContext *context,
689                               const llvm::APFloat &value) {
690     mlir::Type fltTy = Fortran::lower::convertReal(context, KIND);
691     return builder.createRealConstant(getLoc(), fltTy, value);
692   }
693 
694   mlir::Type getSomeKindInteger() { return builder.getIndexType(); }
695 
696   mlir::func::FuncOp getFunction(llvm::StringRef name,
697                                  mlir::FunctionType funTy) {
698     if (mlir::func::FuncOp func = builder.getNamedFunction(name))
699       return func;
700     return builder.createFunction(getLoc(), name, funTy);
701   }
702 
703   template <typename OpTy>
704   mlir::Value createCompareOp(mlir::arith::CmpIPredicate pred,
705                               const ExtValue &left, const ExtValue &right) {
706     if (const fir::UnboxedValue *lhs = left.getUnboxed())
707       if (const fir::UnboxedValue *rhs = right.getUnboxed())
708         return builder.create<OpTy>(getLoc(), pred, *lhs, *rhs);
709     fir::emitFatalError(getLoc(), "array compare should be handled in genarr");
710   }
711   template <typename OpTy, typename A>
712   mlir::Value createCompareOp(const A &ex, mlir::arith::CmpIPredicate pred) {
713     ExtValue left = genval(ex.left());
714     return createCompareOp<OpTy>(pred, left, genval(ex.right()));
715   }
716 
717   template <typename OpTy>
718   mlir::Value createFltCmpOp(mlir::arith::CmpFPredicate pred,
719                              const ExtValue &left, const ExtValue &right) {
720     if (const fir::UnboxedValue *lhs = left.getUnboxed())
721       if (const fir::UnboxedValue *rhs = right.getUnboxed())
722         return builder.create<OpTy>(getLoc(), pred, *lhs, *rhs);
723     fir::emitFatalError(getLoc(), "array compare should be handled in genarr");
724   }
725   template <typename OpTy, typename A>
726   mlir::Value createFltCmpOp(const A &ex, mlir::arith::CmpFPredicate pred) {
727     ExtValue left = genval(ex.left());
728     return createFltCmpOp<OpTy>(pred, left, genval(ex.right()));
729   }
730 
731   /// Create a call to the runtime to compare two CHARACTER values.
732   /// Precondition: This assumes that the two values have `fir.boxchar` type.
733   mlir::Value createCharCompare(mlir::arith::CmpIPredicate pred,
734                                 const ExtValue &left, const ExtValue &right) {
735     return fir::runtime::genCharCompare(builder, getLoc(), pred, left, right);
736   }
737 
738   template <typename A>
739   mlir::Value createCharCompare(const A &ex, mlir::arith::CmpIPredicate pred) {
740     ExtValue left = genval(ex.left());
741     return createCharCompare(pred, left, genval(ex.right()));
742   }
743 
744   /// Returns a reference to a symbol or its box/boxChar descriptor if it has
745   /// one.
746   ExtValue gen(Fortran::semantics::SymbolRef sym) {
747     if (Fortran::lower::SymbolBox val = symMap.lookupSymbol(sym))
748       return val.match(
749           [&](const Fortran::lower::SymbolBox::PointerOrAllocatable &boxAddr) {
750             return fir::factory::genMutableBoxRead(builder, getLoc(), boxAddr);
751           },
752           [&val](auto &) { return val.toExtendedValue(); });
753     LLVM_DEBUG(llvm::dbgs()
754                << "unknown symbol: " << sym << "\nmap: " << symMap << '\n');
755     fir::emitFatalError(getLoc(), "symbol is not mapped to any IR value");
756   }
757 
758   ExtValue genLoad(const ExtValue &exv) {
759     return ::genLoad(builder, getLoc(), exv);
760   }
761 
762   ExtValue genval(Fortran::semantics::SymbolRef sym) {
763     mlir::Location loc = getLoc();
764     ExtValue var = gen(sym);
765     if (const fir::UnboxedValue *s = var.getUnboxed())
766       if (fir::isa_ref_type(s->getType())) {
767         // A function with multiple entry points returning different types
768         // tags all result variables with one of the largest types to allow
769         // them to share the same storage.  A reference to a result variable
770         // of one of the other types requires conversion to the actual type.
771         fir::UnboxedValue addr = *s;
772         if (Fortran::semantics::IsFunctionResult(sym)) {
773           mlir::Type resultType = converter.genType(*sym);
774           if (addr.getType() != resultType)
775             addr = builder.createConvert(loc, builder.getRefType(resultType),
776                                          addr);
777         }
778         return genLoad(addr);
779       }
780     return var;
781   }
782 
783   ExtValue genval(const Fortran::evaluate::BOZLiteralConstant &) {
784     TODO(getLoc(), "BOZ");
785   }
786 
787   /// Return indirection to function designated in ProcedureDesignator.
788   /// The type of the function indirection is not guaranteed to match the one
789   /// of the ProcedureDesignator due to Fortran implicit typing rules.
790   ExtValue genval(const Fortran::evaluate::ProcedureDesignator &proc) {
791     mlir::Location loc = getLoc();
792     if (const Fortran::evaluate::SpecificIntrinsic *intrinsic =
793             proc.GetSpecificIntrinsic()) {
794       mlir::FunctionType signature =
795           Fortran::lower::translateSignature(proc, converter);
796       // Intrinsic lowering is based on the generic name, so retrieve it here in
797       // case it is different from the specific name. The type of the specific
798       // intrinsic is retained in the signature.
799       std::string genericName =
800           converter.getFoldingContext().intrinsics().GetGenericIntrinsicName(
801               intrinsic->name);
802       mlir::SymbolRefAttr symbolRefAttr =
803           Fortran::lower::getUnrestrictedIntrinsicSymbolRefAttr(
804               builder, loc, genericName, signature);
805       mlir::Value funcPtr =
806           builder.create<fir::AddrOfOp>(loc, signature, symbolRefAttr);
807       return funcPtr;
808     }
809     const Fortran::semantics::Symbol *symbol = proc.GetSymbol();
810     assert(symbol && "expected symbol in ProcedureDesignator");
811     mlir::Value funcPtr;
812     mlir::Value funcPtrResultLength;
813     if (Fortran::semantics::IsDummy(*symbol)) {
814       Fortran::lower::SymbolBox val = symMap.lookupSymbol(*symbol);
815       assert(val && "Dummy procedure not in symbol map");
816       funcPtr = val.getAddr();
817       if (fir::isCharacterProcedureTuple(funcPtr.getType(),
818                                          /*acceptRawFunc=*/false))
819         std::tie(funcPtr, funcPtrResultLength) =
820             fir::factory::extractCharacterProcedureTuple(builder, loc, funcPtr);
821     } else {
822       std::string name = converter.mangleName(*symbol);
823       mlir::func::FuncOp func =
824           Fortran::lower::getOrDeclareFunction(name, proc, converter);
825       funcPtr = builder.create<fir::AddrOfOp>(loc, func.getFunctionType(),
826                                               builder.getSymbolRefAttr(name));
827     }
828     if (Fortran::lower::mustPassLengthWithDummyProcedure(proc, converter)) {
829       // The result length, if available here, must be propagated along the
830       // procedure address so that call sites where the result length is assumed
831       // can retrieve the length.
832       Fortran::evaluate::DynamicType resultType = proc.GetType().value();
833       if (const auto &lengthExpr = resultType.GetCharLength()) {
834         // The length expression may refer to dummy argument symbols that are
835         // meaningless without any actual arguments. Leave the length as
836         // unknown in that case, it be resolved on the call site
837         // with the actual arguments.
838         if (allSymbolsInExprPresentInMap(toEvExpr(*lengthExpr), symMap)) {
839           mlir::Value rawLen = fir::getBase(genval(*lengthExpr));
840           // F2018 7.4.4.2 point 5.
841           funcPtrResultLength =
842               Fortran::lower::genMaxWithZero(builder, getLoc(), rawLen);
843         }
844       }
845       if (!funcPtrResultLength)
846         funcPtrResultLength = builder.createIntegerConstant(
847             loc, builder.getCharacterLengthType(), -1);
848       return fir::CharBoxValue{funcPtr, funcPtrResultLength};
849     }
850     return funcPtr;
851   }
852   ExtValue genval(const Fortran::evaluate::NullPointer &) {
853     return builder.createNullConstant(getLoc());
854   }
855 
856   static bool
857   isDerivedTypeWithLengthParameters(const Fortran::semantics::Symbol &sym) {
858     if (const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType())
859       if (const Fortran::semantics::DerivedTypeSpec *derived =
860               declTy->AsDerived())
861         return Fortran::semantics::CountLenParameters(*derived) > 0;
862     return false;
863   }
864 
865   static bool isBuiltinCPtr(const Fortran::semantics::Symbol &sym) {
866     if (const Fortran::semantics::DeclTypeSpec *declType = sym.GetType())
867       if (const Fortran::semantics::DerivedTypeSpec *derived =
868               declType->AsDerived())
869         return Fortran::semantics::IsIsoCType(derived);
870     return false;
871   }
872 
873   /// Lower structure constructor without a temporary. This can be used in
874   /// fir::GloablOp, and assumes that the structure component is a constant.
875   ExtValue genStructComponentInInitializer(
876       const Fortran::evaluate::StructureConstructor &ctor) {
877     mlir::Location loc = getLoc();
878     mlir::Type ty = translateSomeExprToFIRType(converter, toEvExpr(ctor));
879     auto recTy = ty.cast<fir::RecordType>();
880     auto fieldTy = fir::FieldType::get(ty.getContext());
881     mlir::Value res = builder.create<fir::UndefOp>(loc, recTy);
882 
883     for (const auto &[sym, expr] : ctor.values()) {
884       // Parent components need more work because they do not appear in the
885       // fir.rec type.
886       if (sym->test(Fortran::semantics::Symbol::Flag::ParentComp))
887         TODO(loc, "parent component in structure constructor");
888 
889       llvm::StringRef name = toStringRef(sym->name());
890       mlir::Type componentTy = recTy.getType(name);
891       // FIXME: type parameters must come from the derived-type-spec
892       auto field = builder.create<fir::FieldIndexOp>(
893           loc, fieldTy, name, ty,
894           /*typeParams=*/mlir::ValueRange{} /*TODO*/);
895 
896       if (Fortran::semantics::IsAllocatable(sym))
897         TODO(loc, "allocatable component in structure constructor");
898 
899       if (Fortran::semantics::IsPointer(sym)) {
900         mlir::Value initialTarget = Fortran::lower::genInitialDataTarget(
901             converter, loc, componentTy, expr.value());
902         res = builder.create<fir::InsertValueOp>(
903             loc, recTy, res, initialTarget,
904             builder.getArrayAttr(field.getAttributes()));
905         continue;
906       }
907 
908       if (isDerivedTypeWithLengthParameters(sym))
909         TODO(loc, "component with length parameters in structure constructor");
910 
911       if (isBuiltinCPtr(sym)) {
912         // Builtin c_ptr and c_funptr have special handling because initial
913         // value are handled for them as an extension.
914         mlir::Value addr = fir::getBase(Fortran::lower::genExtAddrInInitializer(
915             converter, loc, expr.value()));
916         if (addr.getType() == componentTy) {
917           // Do nothing. The Ev::Expr was returned as a value that can be
918           // inserted directly to the component without an intermediary.
919         } else {
920           // The Ev::Expr returned is an initializer that is a pointer (e.g.,
921           // null) that must be inserted into an intermediate cptr record
922           // value's address field, which ought to be an intptr_t on the target.
923           assert((fir::isa_ref_type(addr.getType()) ||
924                   addr.getType().isa<mlir::FunctionType>()) &&
925                  "expect reference type for address field");
926           assert(fir::isa_derived(componentTy) &&
927                  "expect C_PTR, C_FUNPTR to be a record");
928           auto cPtrRecTy = componentTy.cast<fir::RecordType>();
929           llvm::StringRef addrFieldName =
930               Fortran::lower::builtin::cptrFieldName;
931           mlir::Type addrFieldTy = cPtrRecTy.getType(addrFieldName);
932           auto addrField = builder.create<fir::FieldIndexOp>(
933               loc, fieldTy, addrFieldName, componentTy,
934               /*typeParams=*/mlir::ValueRange{});
935           mlir::Value castAddr = builder.createConvert(loc, addrFieldTy, addr);
936           auto undef = builder.create<fir::UndefOp>(loc, componentTy);
937           addr = builder.create<fir::InsertValueOp>(
938               loc, componentTy, undef, castAddr,
939               builder.getArrayAttr(addrField.getAttributes()));
940         }
941         res = builder.create<fir::InsertValueOp>(
942             loc, recTy, res, addr, builder.getArrayAttr(field.getAttributes()));
943         continue;
944       }
945 
946       mlir::Value val = fir::getBase(genval(expr.value()));
947       assert(!fir::isa_ref_type(val.getType()) && "expecting a constant value");
948       mlir::Value castVal = builder.createConvert(loc, componentTy, val);
949       res = builder.create<fir::InsertValueOp>(
950           loc, recTy, res, castVal,
951           builder.getArrayAttr(field.getAttributes()));
952     }
953     return res;
954   }
955 
956   /// A structure constructor is lowered two ways. In an initializer context,
957   /// the entire structure must be constant, so the aggregate value is
958   /// constructed inline. This allows it to be the body of a GlobalOp.
959   /// Otherwise, the structure constructor is in an expression. In that case, a
960   /// temporary object is constructed in the stack frame of the procedure.
961   ExtValue genval(const Fortran::evaluate::StructureConstructor &ctor) {
962     if (inInitializer)
963       return genStructComponentInInitializer(ctor);
964     mlir::Location loc = getLoc();
965     mlir::Type ty = translateSomeExprToFIRType(converter, toEvExpr(ctor));
966     auto recTy = ty.cast<fir::RecordType>();
967     auto fieldTy = fir::FieldType::get(ty.getContext());
968     mlir::Value res = builder.createTemporary(loc, recTy);
969 
970     for (const auto &value : ctor.values()) {
971       const Fortran::semantics::Symbol &sym = *value.first;
972       const Fortran::lower::SomeExpr &expr = value.second.value();
973       // Parent components need more work because they do not appear in the
974       // fir.rec type.
975       if (sym.test(Fortran::semantics::Symbol::Flag::ParentComp))
976         TODO(loc, "parent component in structure constructor");
977 
978       if (isDerivedTypeWithLengthParameters(sym))
979         TODO(loc, "component with length parameters in structure constructor");
980 
981       llvm::StringRef name = toStringRef(sym.name());
982       // FIXME: type parameters must come from the derived-type-spec
983       mlir::Value field = builder.create<fir::FieldIndexOp>(
984           loc, fieldTy, name, ty,
985           /*typeParams=*/mlir::ValueRange{} /*TODO*/);
986       mlir::Type coorTy = builder.getRefType(recTy.getType(name));
987       auto coor = builder.create<fir::CoordinateOp>(loc, coorTy,
988                                                     fir::getBase(res), field);
989       ExtValue to = fir::factory::componentToExtendedValue(builder, loc, coor);
990       to.match(
991           [&](const fir::UnboxedValue &toPtr) {
992             ExtValue value = genval(expr);
993             fir::factory::genScalarAssignment(builder, loc, to, value);
994           },
995           [&](const fir::CharBoxValue &) {
996             ExtValue value = genval(expr);
997             fir::factory::genScalarAssignment(builder, loc, to, value);
998           },
999           [&](const fir::ArrayBoxValue &) {
1000             Fortran::lower::createSomeArrayAssignment(converter, to, expr,
1001                                                       symMap, stmtCtx);
1002           },
1003           [&](const fir::CharArrayBoxValue &) {
1004             Fortran::lower::createSomeArrayAssignment(converter, to, expr,
1005                                                       symMap, stmtCtx);
1006           },
1007           [&](const fir::BoxValue &toBox) {
1008             fir::emitFatalError(loc, "derived type components must not be "
1009                                      "represented by fir::BoxValue");
1010           },
1011           [&](const fir::MutableBoxValue &toBox) {
1012             if (toBox.isPointer()) {
1013               Fortran::lower::associateMutableBox(
1014                   converter, loc, toBox, expr, /*lbounds=*/llvm::None, stmtCtx);
1015               return;
1016             }
1017             // For allocatable components, a deep copy is needed.
1018             TODO(loc, "allocatable components in derived type assignment");
1019           },
1020           [&](const fir::ProcBoxValue &toBox) {
1021             TODO(loc, "procedure pointer component in derived type assignment");
1022           });
1023     }
1024     return res;
1025   }
1026 
1027   /// Lowering of an <i>ac-do-variable</i>, which is not a Symbol.
1028   ExtValue genval(const Fortran::evaluate::ImpliedDoIndex &var) {
1029     return converter.impliedDoBinding(toStringRef(var.name));
1030   }
1031 
1032   ExtValue genval(const Fortran::evaluate::DescriptorInquiry &desc) {
1033     ExtValue exv = desc.base().IsSymbol() ? gen(getLastSym(desc.base()))
1034                                           : gen(desc.base().GetComponent());
1035     mlir::IndexType idxTy = builder.getIndexType();
1036     mlir::Location loc = getLoc();
1037     auto castResult = [&](mlir::Value v) {
1038       using ResTy = Fortran::evaluate::DescriptorInquiry::Result;
1039       return builder.createConvert(
1040           loc, converter.genType(ResTy::category, ResTy::kind), v);
1041     };
1042     switch (desc.field()) {
1043     case Fortran::evaluate::DescriptorInquiry::Field::Len:
1044       return castResult(fir::factory::readCharLen(builder, loc, exv));
1045     case Fortran::evaluate::DescriptorInquiry::Field::LowerBound:
1046       return castResult(fir::factory::readLowerBound(
1047           builder, loc, exv, desc.dimension(),
1048           builder.createIntegerConstant(loc, idxTy, 1)));
1049     case Fortran::evaluate::DescriptorInquiry::Field::Extent:
1050       return castResult(
1051           fir::factory::readExtent(builder, loc, exv, desc.dimension()));
1052     case Fortran::evaluate::DescriptorInquiry::Field::Rank:
1053       TODO(loc, "rank inquiry on assumed rank");
1054     case Fortran::evaluate::DescriptorInquiry::Field::Stride:
1055       // So far the front end does not generate this inquiry.
1056       TODO(loc, "Stride inquiry");
1057     }
1058     llvm_unreachable("unknown descriptor inquiry");
1059   }
1060 
1061   ExtValue genval(const Fortran::evaluate::TypeParamInquiry &) {
1062     TODO(getLoc(), "type parameter inquiry");
1063   }
1064 
1065   mlir::Value extractComplexPart(mlir::Value cplx, bool isImagPart) {
1066     return fir::factory::Complex{builder, getLoc()}.extractComplexPart(
1067         cplx, isImagPart);
1068   }
1069 
1070   template <int KIND>
1071   ExtValue genval(const Fortran::evaluate::ComplexComponent<KIND> &part) {
1072     return extractComplexPart(genunbox(part.left()), part.isImaginaryPart);
1073   }
1074 
1075   template <int KIND>
1076   ExtValue genval(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
1077                       Fortran::common::TypeCategory::Integer, KIND>> &op) {
1078     mlir::Value input = genunbox(op.left());
1079     // Like LLVM, integer negation is the binary op "0 - value"
1080     mlir::Value zero = genIntegerConstant<KIND>(builder.getContext(), 0);
1081     return builder.create<mlir::arith::SubIOp>(getLoc(), zero, input);
1082   }
1083   template <int KIND>
1084   ExtValue genval(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
1085                       Fortran::common::TypeCategory::Real, KIND>> &op) {
1086     return builder.create<mlir::arith::NegFOp>(getLoc(), genunbox(op.left()));
1087   }
1088   template <int KIND>
1089   ExtValue genval(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
1090                       Fortran::common::TypeCategory::Complex, KIND>> &op) {
1091     return builder.create<fir::NegcOp>(getLoc(), genunbox(op.left()));
1092   }
1093 
1094   template <typename OpTy>
1095   mlir::Value createBinaryOp(const ExtValue &left, const ExtValue &right) {
1096     assert(fir::isUnboxedValue(left) && fir::isUnboxedValue(right));
1097     mlir::Value lhs = fir::getBase(left);
1098     mlir::Value rhs = fir::getBase(right);
1099     assert(lhs.getType() == rhs.getType() && "types must be the same");
1100     return builder.create<OpTy>(getLoc(), lhs, rhs);
1101   }
1102 
1103   template <typename OpTy, typename A>
1104   mlir::Value createBinaryOp(const A &ex) {
1105     ExtValue left = genval(ex.left());
1106     return createBinaryOp<OpTy>(left, genval(ex.right()));
1107   }
1108 
1109 #undef GENBIN
1110 #define GENBIN(GenBinEvOp, GenBinTyCat, GenBinFirOp)                           \
1111   template <int KIND>                                                          \
1112   ExtValue genval(const Fortran::evaluate::GenBinEvOp<Fortran::evaluate::Type< \
1113                       Fortran::common::TypeCategory::GenBinTyCat, KIND>> &x) { \
1114     return createBinaryOp<GenBinFirOp>(x);                                     \
1115   }
1116 
1117   GENBIN(Add, Integer, mlir::arith::AddIOp)
1118   GENBIN(Add, Real, mlir::arith::AddFOp)
1119   GENBIN(Add, Complex, fir::AddcOp)
1120   GENBIN(Subtract, Integer, mlir::arith::SubIOp)
1121   GENBIN(Subtract, Real, mlir::arith::SubFOp)
1122   GENBIN(Subtract, Complex, fir::SubcOp)
1123   GENBIN(Multiply, Integer, mlir::arith::MulIOp)
1124   GENBIN(Multiply, Real, mlir::arith::MulFOp)
1125   GENBIN(Multiply, Complex, fir::MulcOp)
1126   GENBIN(Divide, Integer, mlir::arith::DivSIOp)
1127   GENBIN(Divide, Real, mlir::arith::DivFOp)
1128   GENBIN(Divide, Complex, fir::DivcOp)
1129 
1130   template <Fortran::common::TypeCategory TC, int KIND>
1131   ExtValue genval(
1132       const Fortran::evaluate::Power<Fortran::evaluate::Type<TC, KIND>> &op) {
1133     mlir::Type ty = converter.genType(TC, KIND);
1134     mlir::Value lhs = genunbox(op.left());
1135     mlir::Value rhs = genunbox(op.right());
1136     return Fortran::lower::genPow(builder, getLoc(), ty, lhs, rhs);
1137   }
1138 
1139   template <Fortran::common::TypeCategory TC, int KIND>
1140   ExtValue genval(
1141       const Fortran::evaluate::RealToIntPower<Fortran::evaluate::Type<TC, KIND>>
1142           &op) {
1143     mlir::Type ty = converter.genType(TC, KIND);
1144     mlir::Value lhs = genunbox(op.left());
1145     mlir::Value rhs = genunbox(op.right());
1146     return Fortran::lower::genPow(builder, getLoc(), ty, lhs, rhs);
1147   }
1148 
1149   template <int KIND>
1150   ExtValue genval(const Fortran::evaluate::ComplexConstructor<KIND> &op) {
1151     mlir::Value realPartValue = genunbox(op.left());
1152     return fir::factory::Complex{builder, getLoc()}.createComplex(
1153         KIND, realPartValue, genunbox(op.right()));
1154   }
1155 
1156   template <int KIND>
1157   ExtValue genval(const Fortran::evaluate::Concat<KIND> &op) {
1158     ExtValue lhs = genval(op.left());
1159     ExtValue rhs = genval(op.right());
1160     const fir::CharBoxValue *lhsChar = lhs.getCharBox();
1161     const fir::CharBoxValue *rhsChar = rhs.getCharBox();
1162     if (lhsChar && rhsChar)
1163       return fir::factory::CharacterExprHelper{builder, getLoc()}
1164           .createConcatenate(*lhsChar, *rhsChar);
1165     TODO(getLoc(), "character array concatenate");
1166   }
1167 
1168   /// MIN and MAX operations
1169   template <Fortran::common::TypeCategory TC, int KIND>
1170   ExtValue
1171   genval(const Fortran::evaluate::Extremum<Fortran::evaluate::Type<TC, KIND>>
1172              &op) {
1173     mlir::Value lhs = genunbox(op.left());
1174     mlir::Value rhs = genunbox(op.right());
1175     switch (op.ordering) {
1176     case Fortran::evaluate::Ordering::Greater:
1177       return Fortran::lower::genMax(builder, getLoc(),
1178                                     llvm::ArrayRef<mlir::Value>{lhs, rhs});
1179     case Fortran::evaluate::Ordering::Less:
1180       return Fortran::lower::genMin(builder, getLoc(),
1181                                     llvm::ArrayRef<mlir::Value>{lhs, rhs});
1182     case Fortran::evaluate::Ordering::Equal:
1183       llvm_unreachable("Equal is not a valid ordering in this context");
1184     }
1185     llvm_unreachable("unknown ordering");
1186   }
1187 
1188   // Change the dynamic length information without actually changing the
1189   // underlying character storage.
1190   fir::ExtendedValue
1191   replaceScalarCharacterLength(const fir::ExtendedValue &scalarChar,
1192                                mlir::Value newLenValue) {
1193     mlir::Location loc = getLoc();
1194     const fir::CharBoxValue *charBox = scalarChar.getCharBox();
1195     if (!charBox)
1196       fir::emitFatalError(loc, "expected scalar character");
1197     mlir::Value charAddr = charBox->getAddr();
1198     auto charType =
1199         fir::unwrapPassByRefType(charAddr.getType()).cast<fir::CharacterType>();
1200     if (charType.hasConstantLen()) {
1201       // Erase previous constant length from the base type.
1202       fir::CharacterType::LenType newLen = fir::CharacterType::unknownLen();
1203       mlir::Type newCharTy = fir::CharacterType::get(
1204           builder.getContext(), charType.getFKind(), newLen);
1205       mlir::Type newType = fir::ReferenceType::get(newCharTy);
1206       charAddr = builder.createConvert(loc, newType, charAddr);
1207       return fir::CharBoxValue{charAddr, newLenValue};
1208     }
1209     return fir::CharBoxValue{charAddr, newLenValue};
1210   }
1211 
1212   template <int KIND>
1213   ExtValue genval(const Fortran::evaluate::SetLength<KIND> &x) {
1214     mlir::Value newLenValue = genunbox(x.right());
1215     fir::ExtendedValue lhs = gen(x.left());
1216     return replaceScalarCharacterLength(lhs, newLenValue);
1217   }
1218 
1219   template <int KIND>
1220   ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
1221                       Fortran::common::TypeCategory::Integer, KIND>> &op) {
1222     return createCompareOp<mlir::arith::CmpIOp>(op,
1223                                                 translateRelational(op.opr));
1224   }
1225   template <int KIND>
1226   ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
1227                       Fortran::common::TypeCategory::Real, KIND>> &op) {
1228     return createFltCmpOp<mlir::arith::CmpFOp>(
1229         op, translateFloatRelational(op.opr));
1230   }
1231   template <int KIND>
1232   ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
1233                       Fortran::common::TypeCategory::Complex, KIND>> &op) {
1234     return createFltCmpOp<fir::CmpcOp>(op, translateFloatRelational(op.opr));
1235   }
1236   template <int KIND>
1237   ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
1238                       Fortran::common::TypeCategory::Character, KIND>> &op) {
1239     return createCharCompare(op, translateRelational(op.opr));
1240   }
1241 
1242   ExtValue
1243   genval(const Fortran::evaluate::Relational<Fortran::evaluate::SomeType> &op) {
1244     return std::visit([&](const auto &x) { return genval(x); }, op.u);
1245   }
1246 
1247   template <Fortran::common::TypeCategory TC1, int KIND,
1248             Fortran::common::TypeCategory TC2>
1249   ExtValue
1250   genval(const Fortran::evaluate::Convert<Fortran::evaluate::Type<TC1, KIND>,
1251                                           TC2> &convert) {
1252     mlir::Type ty = converter.genType(TC1, KIND);
1253     auto fromExpr = genval(convert.left());
1254     auto loc = getLoc();
1255     return fromExpr.match(
1256         [&](const fir::CharBoxValue &boxchar) -> ExtValue {
1257           if constexpr (TC1 == Fortran::common::TypeCategory::Character &&
1258                         TC2 == TC1) {
1259             // Use char_convert. Each code point is translated from a
1260             // narrower/wider encoding to the target encoding. For example, 'A'
1261             // may be translated from 0x41 : i8 to 0x0041 : i16. The symbol
1262             // for euro (0x20AC : i16) may be translated from a wide character
1263             // to "0xE2 0x82 0xAC" : UTF-8.
1264             mlir::Value bufferSize = boxchar.getLen();
1265             auto kindMap = builder.getKindMap();
1266             auto fromBits = kindMap.getCharacterBitsize(
1267                 fir::unwrapRefType(boxchar.getAddr().getType())
1268                     .cast<fir::CharacterType>()
1269                     .getFKind());
1270             auto toBits = kindMap.getCharacterBitsize(
1271                 ty.cast<fir::CharacterType>().getFKind());
1272             if (toBits < fromBits) {
1273               // Scale by relative ratio to give a buffer of the same length.
1274               auto ratio = builder.createIntegerConstant(
1275                   loc, bufferSize.getType(), fromBits / toBits);
1276               bufferSize =
1277                   builder.create<mlir::arith::MulIOp>(loc, bufferSize, ratio);
1278             }
1279             auto dest = builder.create<fir::AllocaOp>(
1280                 loc, ty, mlir::ValueRange{bufferSize});
1281             builder.create<fir::CharConvertOp>(loc, boxchar.getAddr(),
1282                                                boxchar.getLen(), dest);
1283             return fir::CharBoxValue{dest, boxchar.getLen()};
1284           } else {
1285             fir::emitFatalError(
1286                 loc, "unsupported evaluate::Convert between CHARACTER type "
1287                      "category and non-CHARACTER category");
1288           }
1289         },
1290         [&](const fir::UnboxedValue &value) -> ExtValue {
1291           return builder.convertWithSemantics(loc, ty, value);
1292         },
1293         [&](auto &) -> ExtValue {
1294           fir::emitFatalError(loc, "unsupported evaluate::Convert");
1295         });
1296   }
1297 
1298   template <typename A>
1299   ExtValue genval(const Fortran::evaluate::Parentheses<A> &op) {
1300     ExtValue input = genval(op.left());
1301     mlir::Value base = fir::getBase(input);
1302     mlir::Value newBase =
1303         builder.create<fir::NoReassocOp>(getLoc(), base.getType(), base);
1304     return fir::substBase(input, newBase);
1305   }
1306 
1307   template <int KIND>
1308   ExtValue genval(const Fortran::evaluate::Not<KIND> &op) {
1309     mlir::Value logical = genunbox(op.left());
1310     mlir::Value one = genBoolConstant(true);
1311     mlir::Value val =
1312         builder.createConvert(getLoc(), builder.getI1Type(), logical);
1313     return builder.create<mlir::arith::XOrIOp>(getLoc(), val, one);
1314   }
1315 
1316   template <int KIND>
1317   ExtValue genval(const Fortran::evaluate::LogicalOperation<KIND> &op) {
1318     mlir::IntegerType i1Type = builder.getI1Type();
1319     mlir::Value slhs = genunbox(op.left());
1320     mlir::Value srhs = genunbox(op.right());
1321     mlir::Value lhs = builder.createConvert(getLoc(), i1Type, slhs);
1322     mlir::Value rhs = builder.createConvert(getLoc(), i1Type, srhs);
1323     switch (op.logicalOperator) {
1324     case Fortran::evaluate::LogicalOperator::And:
1325       return createBinaryOp<mlir::arith::AndIOp>(lhs, rhs);
1326     case Fortran::evaluate::LogicalOperator::Or:
1327       return createBinaryOp<mlir::arith::OrIOp>(lhs, rhs);
1328     case Fortran::evaluate::LogicalOperator::Eqv:
1329       return createCompareOp<mlir::arith::CmpIOp>(
1330           mlir::arith::CmpIPredicate::eq, lhs, rhs);
1331     case Fortran::evaluate::LogicalOperator::Neqv:
1332       return createCompareOp<mlir::arith::CmpIOp>(
1333           mlir::arith::CmpIPredicate::ne, lhs, rhs);
1334     case Fortran::evaluate::LogicalOperator::Not:
1335       // lib/evaluate expression for .NOT. is Fortran::evaluate::Not<KIND>.
1336       llvm_unreachable(".NOT. is not a binary operator");
1337     }
1338     llvm_unreachable("unhandled logical operation");
1339   }
1340 
1341   /// Convert a scalar literal constant to IR.
1342   template <Fortran::common::TypeCategory TC, int KIND>
1343   ExtValue genScalarLit(
1344       const Fortran::evaluate::Scalar<Fortran::evaluate::Type<TC, KIND>>
1345           &value) {
1346     if constexpr (TC == Fortran::common::TypeCategory::Integer) {
1347       return genIntegerConstant<KIND>(builder.getContext(), value.ToInt64());
1348     } else if constexpr (TC == Fortran::common::TypeCategory::Logical) {
1349       return genBoolConstant(value.IsTrue());
1350     } else if constexpr (TC == Fortran::common::TypeCategory::Real) {
1351       std::string str = value.DumpHexadecimal();
1352       if constexpr (KIND == 2) {
1353         llvm::APFloat floatVal{llvm::APFloatBase::IEEEhalf(), str};
1354         return genRealConstant<KIND>(builder.getContext(), floatVal);
1355       } else if constexpr (KIND == 3) {
1356         llvm::APFloat floatVal{llvm::APFloatBase::BFloat(), str};
1357         return genRealConstant<KIND>(builder.getContext(), floatVal);
1358       } else if constexpr (KIND == 4) {
1359         llvm::APFloat floatVal{llvm::APFloatBase::IEEEsingle(), str};
1360         return genRealConstant<KIND>(builder.getContext(), floatVal);
1361       } else if constexpr (KIND == 10) {
1362         llvm::APFloat floatVal{llvm::APFloatBase::x87DoubleExtended(), str};
1363         return genRealConstant<KIND>(builder.getContext(), floatVal);
1364       } else if constexpr (KIND == 16) {
1365         llvm::APFloat floatVal{llvm::APFloatBase::IEEEquad(), str};
1366         return genRealConstant<KIND>(builder.getContext(), floatVal);
1367       } else {
1368         // convert everything else to double
1369         llvm::APFloat floatVal{llvm::APFloatBase::IEEEdouble(), str};
1370         return genRealConstant<KIND>(builder.getContext(), floatVal);
1371       }
1372     } else if constexpr (TC == Fortran::common::TypeCategory::Complex) {
1373       using TR =
1374           Fortran::evaluate::Type<Fortran::common::TypeCategory::Real, KIND>;
1375       Fortran::evaluate::ComplexConstructor<KIND> ctor(
1376           Fortran::evaluate::Expr<TR>{
1377               Fortran::evaluate::Constant<TR>{value.REAL()}},
1378           Fortran::evaluate::Expr<TR>{
1379               Fortran::evaluate::Constant<TR>{value.AIMAG()}});
1380       return genunbox(ctor);
1381     } else /*constexpr*/ {
1382       llvm_unreachable("unhandled constant");
1383     }
1384   }
1385 
1386   /// Generate a raw literal value and store it in the rawVals vector.
1387   template <Fortran::common::TypeCategory TC, int KIND>
1388   void
1389   genRawLit(const Fortran::evaluate::Scalar<Fortran::evaluate::Type<TC, KIND>>
1390                 &value) {
1391     mlir::Attribute val;
1392     assert(inInitializer != nullptr);
1393     if constexpr (TC == Fortran::common::TypeCategory::Integer) {
1394       inInitializer->rawType = converter.genType(TC, KIND);
1395       val = builder.getIntegerAttr(inInitializer->rawType, value.ToInt64());
1396     } else if constexpr (TC == Fortran::common::TypeCategory::Logical) {
1397       inInitializer->rawType =
1398           converter.genType(Fortran::common::TypeCategory::Integer, KIND);
1399       val = builder.getIntegerAttr(inInitializer->rawType, value.IsTrue());
1400     } else if constexpr (TC == Fortran::common::TypeCategory::Real) {
1401       std::string str = value.DumpHexadecimal();
1402       inInitializer->rawType = converter.genType(TC, KIND);
1403       llvm::APFloat floatVal{builder.getKindMap().getFloatSemantics(KIND), str};
1404       val = builder.getFloatAttr(inInitializer->rawType, floatVal);
1405     } else if constexpr (TC == Fortran::common::TypeCategory::Complex) {
1406       std::string strReal = value.REAL().DumpHexadecimal();
1407       std::string strImg = value.AIMAG().DumpHexadecimal();
1408       inInitializer->rawType = converter.genType(TC, KIND);
1409       llvm::APFloat realVal{builder.getKindMap().getFloatSemantics(KIND),
1410                             strReal};
1411       val = builder.getFloatAttr(inInitializer->rawType, realVal);
1412       inInitializer->rawVals.push_back(val);
1413       llvm::APFloat imgVal{builder.getKindMap().getFloatSemantics(KIND),
1414                            strImg};
1415       val = builder.getFloatAttr(inInitializer->rawType, imgVal);
1416     }
1417     inInitializer->rawVals.push_back(val);
1418   }
1419 
1420   /// Convert a scalar literal CHARACTER to IR.
1421   template <int KIND>
1422   ExtValue
1423   genScalarLit(const Fortran::evaluate::Scalar<Fortran::evaluate::Type<
1424                    Fortran::common::TypeCategory::Character, KIND>> &value,
1425                int64_t len) {
1426     using ET = typename std::decay_t<decltype(value)>::value_type;
1427     if constexpr (KIND == 1) {
1428       assert(value.size() == static_cast<std::uint64_t>(len));
1429       // Outline character constant in ro data if it is not in an initializer.
1430       if (!inInitializer)
1431         return fir::factory::createStringLiteral(builder, getLoc(), value);
1432       // When in an initializer context, construct the literal op itself and do
1433       // not construct another constant object in rodata.
1434       fir::StringLitOp stringLit = builder.createStringLitOp(getLoc(), value);
1435       mlir::Value lenp = builder.createIntegerConstant(
1436           getLoc(), builder.getCharacterLengthType(), len);
1437       return fir::CharBoxValue{stringLit.getResult(), lenp};
1438     }
1439     fir::CharacterType type =
1440         fir::CharacterType::get(builder.getContext(), KIND, len);
1441     auto consLit = [&]() -> fir::StringLitOp {
1442       mlir::MLIRContext *context = builder.getContext();
1443       std::int64_t size = static_cast<std::int64_t>(value.size());
1444       mlir::ShapedType shape = mlir::RankedTensorType::get(
1445           llvm::ArrayRef<std::int64_t>{size},
1446           mlir::IntegerType::get(builder.getContext(), sizeof(ET) * 8));
1447       auto denseAttr = mlir::DenseElementsAttr::get(
1448           shape, llvm::ArrayRef<ET>{value.data(), value.size()});
1449       auto denseTag = mlir::StringAttr::get(context, fir::StringLitOp::xlist());
1450       mlir::NamedAttribute dataAttr(denseTag, denseAttr);
1451       auto sizeTag = mlir::StringAttr::get(context, fir::StringLitOp::size());
1452       mlir::NamedAttribute sizeAttr(sizeTag, builder.getI64IntegerAttr(len));
1453       llvm::SmallVector<mlir::NamedAttribute> attrs = {dataAttr, sizeAttr};
1454       return builder.create<fir::StringLitOp>(
1455           getLoc(), llvm::ArrayRef<mlir::Type>{type}, llvm::None, attrs);
1456     };
1457 
1458     mlir::Value lenp = builder.createIntegerConstant(
1459         getLoc(), builder.getCharacterLengthType(), len);
1460     // When in an initializer context, construct the literal op itself and do
1461     // not construct another constant object in rodata.
1462     if (inInitializer)
1463       return fir::CharBoxValue{consLit().getResult(), lenp};
1464 
1465     // Otherwise, the string is in a plain old expression so "outline" the value
1466     // by hashconsing it to a constant literal object.
1467 
1468     std::string globalName =
1469         fir::factory::uniqueCGIdent("cl", (const char *)value.c_str());
1470     fir::GlobalOp global = builder.getNamedGlobal(globalName);
1471     if (!global)
1472       global = builder.createGlobalConstant(
1473           getLoc(), type, globalName,
1474           [&](fir::FirOpBuilder &builder) {
1475             fir::StringLitOp str = consLit();
1476             builder.create<fir::HasValueOp>(getLoc(), str);
1477           },
1478           builder.createLinkOnceLinkage());
1479     auto addr = builder.create<fir::AddrOfOp>(getLoc(), global.resultType(),
1480                                               global.getSymbol());
1481     return fir::CharBoxValue{addr, lenp};
1482   }
1483 
1484   template <Fortran::common::TypeCategory TC, int KIND>
1485   ExtValue genArrayLit(
1486       const Fortran::evaluate::Constant<Fortran::evaluate::Type<TC, KIND>>
1487           &con) {
1488     mlir::Location loc = getLoc();
1489     mlir::IndexType idxTy = builder.getIndexType();
1490     Fortran::evaluate::ConstantSubscript size =
1491         Fortran::evaluate::GetSize(con.shape());
1492     fir::SequenceType::Shape shape(con.shape().begin(), con.shape().end());
1493     mlir::Type eleTy;
1494     if constexpr (TC == Fortran::common::TypeCategory::Character)
1495       eleTy = converter.genType(TC, KIND, {con.LEN()});
1496     else
1497       eleTy = converter.genType(TC, KIND);
1498     auto arrayTy = fir::SequenceType::get(shape, eleTy);
1499     mlir::Value array;
1500     llvm::SmallVector<mlir::Value> lbounds;
1501     llvm::SmallVector<mlir::Value> extents;
1502     if (!inInitializer || !inInitializer->genRawVals) {
1503       array = builder.create<fir::UndefOp>(loc, arrayTy);
1504       for (auto [lb, extent] : llvm::zip(con.lbounds(), shape)) {
1505         lbounds.push_back(builder.createIntegerConstant(loc, idxTy, lb - 1));
1506         extents.push_back(builder.createIntegerConstant(loc, idxTy, extent));
1507       }
1508     }
1509     if (size == 0) {
1510       if constexpr (TC == Fortran::common::TypeCategory::Character) {
1511         mlir::Value len = builder.createIntegerConstant(loc, idxTy, con.LEN());
1512         return fir::CharArrayBoxValue{array, len, extents, lbounds};
1513       } else {
1514         return fir::ArrayBoxValue{array, extents, lbounds};
1515       }
1516     }
1517     Fortran::evaluate::ConstantSubscripts subscripts = con.lbounds();
1518     auto createIdx = [&]() {
1519       llvm::SmallVector<mlir::Attribute> idx;
1520       for (size_t i = 0; i < subscripts.size(); ++i)
1521         idx.push_back(
1522             builder.getIntegerAttr(idxTy, subscripts[i] - con.lbounds()[i]));
1523       return idx;
1524     };
1525     if constexpr (TC == Fortran::common::TypeCategory::Character) {
1526       assert(array && "array must not be nullptr");
1527       do {
1528         mlir::Value elementVal =
1529             fir::getBase(genScalarLit<KIND>(con.At(subscripts), con.LEN()));
1530         array = builder.create<fir::InsertValueOp>(
1531             loc, arrayTy, array, elementVal, builder.getArrayAttr(createIdx()));
1532       } while (con.IncrementSubscripts(subscripts));
1533       mlir::Value len = builder.createIntegerConstant(loc, idxTy, con.LEN());
1534       return fir::CharArrayBoxValue{array, len, extents, lbounds};
1535     } else {
1536       llvm::SmallVector<mlir::Attribute> rangeStartIdx;
1537       uint64_t rangeSize = 0;
1538       do {
1539         if (inInitializer && inInitializer->genRawVals) {
1540           genRawLit<TC, KIND>(con.At(subscripts));
1541           continue;
1542         }
1543         auto getElementVal = [&]() {
1544           return builder.createConvert(
1545               loc, eleTy,
1546               fir::getBase(genScalarLit<TC, KIND>(con.At(subscripts))));
1547         };
1548         Fortran::evaluate::ConstantSubscripts nextSubscripts = subscripts;
1549         bool nextIsSame = con.IncrementSubscripts(nextSubscripts) &&
1550                           con.At(subscripts) == con.At(nextSubscripts);
1551         if (!rangeSize && !nextIsSame) { // single (non-range) value
1552           array = builder.create<fir::InsertValueOp>(
1553               loc, arrayTy, array, getElementVal(),
1554               builder.getArrayAttr(createIdx()));
1555         } else if (!rangeSize) { // start a range
1556           rangeStartIdx = createIdx();
1557           rangeSize = 1;
1558         } else if (nextIsSame) { // expand a range
1559           ++rangeSize;
1560         } else { // end a range
1561           llvm::SmallVector<int64_t> rangeBounds;
1562           llvm::SmallVector<mlir::Attribute> idx = createIdx();
1563           for (size_t i = 0; i < idx.size(); ++i) {
1564             rangeBounds.push_back(rangeStartIdx[i]
1565                                       .cast<mlir::IntegerAttr>()
1566                                       .getValue()
1567                                       .getSExtValue());
1568             rangeBounds.push_back(
1569                 idx[i].cast<mlir::IntegerAttr>().getValue().getSExtValue());
1570           }
1571           array = builder.create<fir::InsertOnRangeOp>(
1572               loc, arrayTy, array, getElementVal(),
1573               builder.getIndexVectorAttr(rangeBounds));
1574           rangeSize = 0;
1575         }
1576       } while (con.IncrementSubscripts(subscripts));
1577       return fir::ArrayBoxValue{array, extents, lbounds};
1578     }
1579   }
1580 
1581   fir::ExtendedValue genArrayLit(
1582       const Fortran::evaluate::Constant<Fortran::evaluate::SomeDerived> &con) {
1583     mlir::Location loc = getLoc();
1584     mlir::IndexType idxTy = builder.getIndexType();
1585     Fortran::evaluate::ConstantSubscript size =
1586         Fortran::evaluate::GetSize(con.shape());
1587     fir::SequenceType::Shape shape(con.shape().begin(), con.shape().end());
1588     mlir::Type eleTy = converter.genType(con.GetType().GetDerivedTypeSpec());
1589     auto arrayTy = fir::SequenceType::get(shape, eleTy);
1590     mlir::Value array = builder.create<fir::UndefOp>(loc, arrayTy);
1591     llvm::SmallVector<mlir::Value> lbounds;
1592     llvm::SmallVector<mlir::Value> extents;
1593     for (auto [lb, extent] : llvm::zip(con.lbounds(), con.shape())) {
1594       lbounds.push_back(builder.createIntegerConstant(loc, idxTy, lb - 1));
1595       extents.push_back(builder.createIntegerConstant(loc, idxTy, extent));
1596     }
1597     if (size == 0)
1598       return fir::ArrayBoxValue{array, extents, lbounds};
1599     Fortran::evaluate::ConstantSubscripts subscripts = con.lbounds();
1600     do {
1601       mlir::Value derivedVal = fir::getBase(genval(con.At(subscripts)));
1602       llvm::SmallVector<mlir::Attribute> idx;
1603       for (auto [dim, lb] : llvm::zip(subscripts, con.lbounds()))
1604         idx.push_back(builder.getIntegerAttr(idxTy, dim - lb));
1605       array = builder.create<fir::InsertValueOp>(
1606           loc, arrayTy, array, derivedVal, builder.getArrayAttr(idx));
1607     } while (con.IncrementSubscripts(subscripts));
1608     return fir::ArrayBoxValue{array, extents, lbounds};
1609   }
1610 
1611   template <Fortran::common::TypeCategory TC, int KIND>
1612   ExtValue
1613   genval(const Fortran::evaluate::Constant<Fortran::evaluate::Type<TC, KIND>>
1614              &con) {
1615     if (con.Rank() > 0)
1616       return genArrayLit(con);
1617     std::optional<Fortran::evaluate::Scalar<Fortran::evaluate::Type<TC, KIND>>>
1618         opt = con.GetScalarValue();
1619     assert(opt.has_value() && "constant has no value");
1620     if constexpr (TC == Fortran::common::TypeCategory::Character) {
1621       return genScalarLit<KIND>(opt.value(), con.LEN());
1622     } else {
1623       return genScalarLit<TC, KIND>(opt.value());
1624     }
1625   }
1626   fir::ExtendedValue genval(
1627       const Fortran::evaluate::Constant<Fortran::evaluate::SomeDerived> &con) {
1628     if (con.Rank() > 0)
1629       return genArrayLit(con);
1630     if (auto ctor = con.GetScalarValue())
1631       return genval(ctor.value());
1632     fir::emitFatalError(getLoc(),
1633                         "constant of derived type has no constructor");
1634   }
1635 
1636   template <typename A>
1637   ExtValue genval(const Fortran::evaluate::ArrayConstructor<A> &) {
1638     fir::emitFatalError(getLoc(),
1639                         "array constructor: lowering should not reach here");
1640   }
1641 
1642   ExtValue gen(const Fortran::evaluate::ComplexPart &x) {
1643     mlir::Location loc = getLoc();
1644     auto idxTy = builder.getI32Type();
1645     ExtValue exv = gen(x.complex());
1646     mlir::Value base = fir::getBase(exv);
1647     fir::factory::Complex helper{builder, loc};
1648     mlir::Type eleTy =
1649         helper.getComplexPartType(fir::dyn_cast_ptrEleTy(base.getType()));
1650     mlir::Value offset = builder.createIntegerConstant(
1651         loc, idxTy,
1652         x.part() == Fortran::evaluate::ComplexPart::Part::RE ? 0 : 1);
1653     mlir::Value result = builder.create<fir::CoordinateOp>(
1654         loc, builder.getRefType(eleTy), base, mlir::ValueRange{offset});
1655     return {result};
1656   }
1657   ExtValue genval(const Fortran::evaluate::ComplexPart &x) {
1658     return genLoad(gen(x));
1659   }
1660 
1661   /// Reference to a substring.
1662   ExtValue gen(const Fortran::evaluate::Substring &s) {
1663     // Get base string
1664     auto baseString = std::visit(
1665         Fortran::common::visitors{
1666             [&](const Fortran::evaluate::DataRef &x) { return gen(x); },
1667             [&](const Fortran::evaluate::StaticDataObject::Pointer &p)
1668                 -> ExtValue {
1669               if (std::optional<std::string> str = p->AsString())
1670                 return fir::factory::createStringLiteral(builder, getLoc(),
1671                                                          *str);
1672               // TODO: convert StaticDataObject to Constant<T> and use normal
1673               // constant path. Beware that StaticDataObject data() takes into
1674               // account build machine endianness.
1675               TODO(getLoc(),
1676                    "StaticDataObject::Pointer substring with kind > 1");
1677             },
1678         },
1679         s.parent());
1680     llvm::SmallVector<mlir::Value> bounds;
1681     mlir::Value lower = genunbox(s.lower());
1682     bounds.push_back(lower);
1683     if (Fortran::evaluate::MaybeExtentExpr upperBound = s.upper()) {
1684       mlir::Value upper = genunbox(*upperBound);
1685       bounds.push_back(upper);
1686     }
1687     fir::factory::CharacterExprHelper charHelper{builder, getLoc()};
1688     return baseString.match(
1689         [&](const fir::CharBoxValue &x) -> ExtValue {
1690           return charHelper.createSubstring(x, bounds);
1691         },
1692         [&](const fir::CharArrayBoxValue &) -> ExtValue {
1693           fir::emitFatalError(
1694               getLoc(),
1695               "array substring should be handled in array expression");
1696         },
1697         [&](const auto &) -> ExtValue {
1698           fir::emitFatalError(getLoc(), "substring base is not a CharBox");
1699         });
1700   }
1701 
1702   /// The value of a substring.
1703   ExtValue genval(const Fortran::evaluate::Substring &ss) {
1704     // FIXME: why is the value of a substring being lowered the same as the
1705     // address of a substring?
1706     return gen(ss);
1707   }
1708 
1709   ExtValue genval(const Fortran::evaluate::Subscript &subs) {
1710     if (auto *s = std::get_if<Fortran::evaluate::IndirectSubscriptIntegerExpr>(
1711             &subs.u)) {
1712       if (s->value().Rank() > 0)
1713         fir::emitFatalError(getLoc(), "vector subscript is not scalar");
1714       return {genval(s->value())};
1715     }
1716     fir::emitFatalError(getLoc(), "subscript triple notation is not scalar");
1717   }
1718   ExtValue genSubscript(const Fortran::evaluate::Subscript &subs) {
1719     return genval(subs);
1720   }
1721 
1722   ExtValue gen(const Fortran::evaluate::DataRef &dref) {
1723     return std::visit([&](const auto &x) { return gen(x); }, dref.u);
1724   }
1725   ExtValue genval(const Fortran::evaluate::DataRef &dref) {
1726     return std::visit([&](const auto &x) { return genval(x); }, dref.u);
1727   }
1728 
1729   // Helper function to turn the Component structure into a list of nested
1730   // components, ordered from largest/leftmost to smallest/rightmost:
1731   //  - where only the smallest/rightmost item may be allocatable or a pointer
1732   //    (nested allocatable/pointer components require nested coordinate_of ops)
1733   //  - that does not contain any parent components
1734   //    (the front end places parent components directly in the object)
1735   // Return the object used as the base coordinate for the component chain.
1736   static Fortran::evaluate::DataRef const *
1737   reverseComponents(const Fortran::evaluate::Component &cmpt,
1738                     std::list<const Fortran::evaluate::Component *> &list) {
1739     if (!getLastSym(cmpt).test(Fortran::semantics::Symbol::Flag::ParentComp))
1740       list.push_front(&cmpt);
1741     return std::visit(
1742         Fortran::common::visitors{
1743             [&](const Fortran::evaluate::Component &x) {
1744               if (Fortran::semantics::IsAllocatableOrPointer(getLastSym(x)))
1745                 return &cmpt.base();
1746               return reverseComponents(x, list);
1747             },
1748             [&](auto &) { return &cmpt.base(); },
1749         },
1750         cmpt.base().u);
1751   }
1752 
1753   // Return the coordinate of the component reference
1754   ExtValue genComponent(const Fortran::evaluate::Component &cmpt) {
1755     std::list<const Fortran::evaluate::Component *> list;
1756     const Fortran::evaluate::DataRef *base = reverseComponents(cmpt, list);
1757     llvm::SmallVector<mlir::Value> coorArgs;
1758     ExtValue obj = gen(*base);
1759     mlir::Type ty = fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(obj).getType());
1760     mlir::Location loc = getLoc();
1761     auto fldTy = fir::FieldType::get(&converter.getMLIRContext());
1762     // FIXME: need to thread the LEN type parameters here.
1763     for (const Fortran::evaluate::Component *field : list) {
1764       auto recTy = ty.cast<fir::RecordType>();
1765       const Fortran::semantics::Symbol &sym = getLastSym(*field);
1766       llvm::StringRef name = toStringRef(sym.name());
1767       coorArgs.push_back(builder.create<fir::FieldIndexOp>(
1768           loc, fldTy, name, recTy, fir::getTypeParams(obj)));
1769       ty = recTy.getType(name);
1770     }
1771     ty = builder.getRefType(ty);
1772     return fir::factory::componentToExtendedValue(
1773         builder, loc,
1774         builder.create<fir::CoordinateOp>(loc, ty, fir::getBase(obj),
1775                                           coorArgs));
1776   }
1777 
1778   ExtValue gen(const Fortran::evaluate::Component &cmpt) {
1779     // Components may be pointer or allocatable. In the gen() path, the mutable
1780     // aspect is lost to simplify handling on the client side. To retain the
1781     // mutable aspect, genMutableBoxValue should be used.
1782     return genComponent(cmpt).match(
1783         [&](const fir::MutableBoxValue &mutableBox) {
1784           return fir::factory::genMutableBoxRead(builder, getLoc(), mutableBox);
1785         },
1786         [](auto &box) -> ExtValue { return box; });
1787   }
1788 
1789   ExtValue genval(const Fortran::evaluate::Component &cmpt) {
1790     return genLoad(gen(cmpt));
1791   }
1792 
1793   // Determine the result type after removing `dims` dimensions from the array
1794   // type `arrTy`
1795   mlir::Type genSubType(mlir::Type arrTy, unsigned dims) {
1796     mlir::Type unwrapTy = fir::dyn_cast_ptrOrBoxEleTy(arrTy);
1797     assert(unwrapTy && "must be a pointer or box type");
1798     auto seqTy = unwrapTy.cast<fir::SequenceType>();
1799     llvm::ArrayRef<int64_t> shape = seqTy.getShape();
1800     assert(shape.size() > 0 && "removing columns for sequence sans shape");
1801     assert(dims <= shape.size() && "removing more columns than exist");
1802     fir::SequenceType::Shape newBnds;
1803     // follow Fortran semantics and remove columns (from right)
1804     std::size_t e = shape.size() - dims;
1805     for (decltype(e) i = 0; i < e; ++i)
1806       newBnds.push_back(shape[i]);
1807     if (!newBnds.empty())
1808       return fir::SequenceType::get(newBnds, seqTy.getEleTy());
1809     return seqTy.getEleTy();
1810   }
1811 
1812   // Generate the code for a Bound value.
1813   ExtValue genval(const Fortran::semantics::Bound &bound) {
1814     if (bound.isExplicit()) {
1815       Fortran::semantics::MaybeSubscriptIntExpr sub = bound.GetExplicit();
1816       if (sub.has_value())
1817         return genval(*sub);
1818       return genIntegerConstant<8>(builder.getContext(), 1);
1819     }
1820     TODO(getLoc(), "non explicit semantics::Bound lowering");
1821   }
1822 
1823   static bool isSlice(const Fortran::evaluate::ArrayRef &aref) {
1824     for (const Fortran::evaluate::Subscript &sub : aref.subscript())
1825       if (std::holds_alternative<Fortran::evaluate::Triplet>(sub.u))
1826         return true;
1827     return false;
1828   }
1829 
1830   /// Lower an ArrayRef to a fir.coordinate_of given its lowered base.
1831   ExtValue genCoordinateOp(const ExtValue &array,
1832                            const Fortran::evaluate::ArrayRef &aref) {
1833     mlir::Location loc = getLoc();
1834     // References to array of rank > 1 with non constant shape that are not
1835     // fir.box must be collapsed into an offset computation in lowering already.
1836     // The same is needed with dynamic length character arrays of all ranks.
1837     mlir::Type baseType =
1838         fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(array).getType());
1839     if ((array.rank() > 1 && fir::hasDynamicSize(baseType)) ||
1840         fir::characterWithDynamicLen(fir::unwrapSequenceType(baseType)))
1841       if (!array.getBoxOf<fir::BoxValue>())
1842         return genOffsetAndCoordinateOp(array, aref);
1843     // Generate a fir.coordinate_of with zero based array indexes.
1844     llvm::SmallVector<mlir::Value> args;
1845     for (const auto &subsc : llvm::enumerate(aref.subscript())) {
1846       ExtValue subVal = genSubscript(subsc.value());
1847       assert(fir::isUnboxedValue(subVal) && "subscript must be simple scalar");
1848       mlir::Value val = fir::getBase(subVal);
1849       mlir::Type ty = val.getType();
1850       mlir::Value lb = getLBound(array, subsc.index(), ty);
1851       args.push_back(builder.create<mlir::arith::SubIOp>(loc, ty, val, lb));
1852     }
1853 
1854     mlir::Value base = fir::getBase(array);
1855     auto seqTy =
1856         fir::dyn_cast_ptrOrBoxEleTy(base.getType()).cast<fir::SequenceType>();
1857     assert(args.size() == seqTy.getDimension());
1858     mlir::Type ty = builder.getRefType(seqTy.getEleTy());
1859     auto addr = builder.create<fir::CoordinateOp>(loc, ty, base, args);
1860     return fir::factory::arrayElementToExtendedValue(builder, loc, array, addr);
1861   }
1862 
1863   /// Lower an ArrayRef to a fir.coordinate_of using an element offset instead
1864   /// of array indexes.
1865   /// This generates offset computation from the indexes and length parameters,
1866   /// and use the offset to access the element with a fir.coordinate_of. This
1867   /// must only be used if it is not possible to generate a normal
1868   /// fir.coordinate_of using array indexes (i.e. when the shape information is
1869   /// unavailable in the IR).
1870   ExtValue genOffsetAndCoordinateOp(const ExtValue &array,
1871                                     const Fortran::evaluate::ArrayRef &aref) {
1872     mlir::Location loc = getLoc();
1873     mlir::Value addr = fir::getBase(array);
1874     mlir::Type arrTy = fir::dyn_cast_ptrEleTy(addr.getType());
1875     auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy();
1876     mlir::Type seqTy = builder.getRefType(builder.getVarLenSeqTy(eleTy));
1877     mlir::Type refTy = builder.getRefType(eleTy);
1878     mlir::Value base = builder.createConvert(loc, seqTy, addr);
1879     mlir::IndexType idxTy = builder.getIndexType();
1880     mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
1881     mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
1882     auto getLB = [&](const auto &arr, unsigned dim) -> mlir::Value {
1883       return arr.getLBounds().empty() ? one : arr.getLBounds()[dim];
1884     };
1885     auto genFullDim = [&](const auto &arr, mlir::Value delta) -> mlir::Value {
1886       mlir::Value total = zero;
1887       assert(arr.getExtents().size() == aref.subscript().size());
1888       delta = builder.createConvert(loc, idxTy, delta);
1889       unsigned dim = 0;
1890       for (auto [ext, sub] : llvm::zip(arr.getExtents(), aref.subscript())) {
1891         ExtValue subVal = genSubscript(sub);
1892         assert(fir::isUnboxedValue(subVal));
1893         mlir::Value val =
1894             builder.createConvert(loc, idxTy, fir::getBase(subVal));
1895         mlir::Value lb = builder.createConvert(loc, idxTy, getLB(arr, dim));
1896         mlir::Value diff = builder.create<mlir::arith::SubIOp>(loc, val, lb);
1897         mlir::Value prod =
1898             builder.create<mlir::arith::MulIOp>(loc, delta, diff);
1899         total = builder.create<mlir::arith::AddIOp>(loc, prod, total);
1900         if (ext)
1901           delta = builder.create<mlir::arith::MulIOp>(loc, delta, ext);
1902         ++dim;
1903       }
1904       mlir::Type origRefTy = refTy;
1905       if (fir::factory::CharacterExprHelper::isCharacterScalar(refTy)) {
1906         fir::CharacterType chTy =
1907             fir::factory::CharacterExprHelper::getCharacterType(refTy);
1908         if (fir::characterWithDynamicLen(chTy)) {
1909           mlir::MLIRContext *ctx = builder.getContext();
1910           fir::KindTy kind =
1911               fir::factory::CharacterExprHelper::getCharacterKind(chTy);
1912           fir::CharacterType singleTy =
1913               fir::CharacterType::getSingleton(ctx, kind);
1914           refTy = builder.getRefType(singleTy);
1915           mlir::Type seqRefTy =
1916               builder.getRefType(builder.getVarLenSeqTy(singleTy));
1917           base = builder.createConvert(loc, seqRefTy, base);
1918         }
1919       }
1920       auto coor = builder.create<fir::CoordinateOp>(
1921           loc, refTy, base, llvm::ArrayRef<mlir::Value>{total});
1922       // Convert to expected, original type after address arithmetic.
1923       return builder.createConvert(loc, origRefTy, coor);
1924     };
1925     return array.match(
1926         [&](const fir::ArrayBoxValue &arr) -> ExtValue {
1927           // FIXME: this check can be removed when slicing is implemented
1928           if (isSlice(aref))
1929             fir::emitFatalError(
1930                 getLoc(),
1931                 "slice should be handled in array expression context");
1932           return genFullDim(arr, one);
1933         },
1934         [&](const fir::CharArrayBoxValue &arr) -> ExtValue {
1935           mlir::Value delta = arr.getLen();
1936           // If the length is known in the type, fir.coordinate_of will
1937           // already take the length into account.
1938           if (fir::factory::CharacterExprHelper::hasConstantLengthInType(arr))
1939             delta = one;
1940           return fir::CharBoxValue(genFullDim(arr, delta), arr.getLen());
1941         },
1942         [&](const fir::BoxValue &arr) -> ExtValue {
1943           // CoordinateOp for BoxValue is not generated here. The dimensions
1944           // must be kept in the fir.coordinate_op so that potential fir.box
1945           // strides can be applied by codegen.
1946           fir::emitFatalError(
1947               loc, "internal: BoxValue in dim-collapsed fir.coordinate_of");
1948         },
1949         [&](const auto &) -> ExtValue {
1950           fir::emitFatalError(loc, "internal: array lowering failed");
1951         });
1952   }
1953 
1954   /// Lower an ArrayRef to a fir.array_coor.
1955   ExtValue genArrayCoorOp(const ExtValue &exv,
1956                           const Fortran::evaluate::ArrayRef &aref) {
1957     mlir::Location loc = getLoc();
1958     mlir::Value addr = fir::getBase(exv);
1959     mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(addr.getType());
1960     mlir::Type eleTy = arrTy.cast<fir::SequenceType>().getEleTy();
1961     mlir::Type refTy = builder.getRefType(eleTy);
1962     mlir::IndexType idxTy = builder.getIndexType();
1963     llvm::SmallVector<mlir::Value> arrayCoorArgs;
1964     // The ArrayRef is expected to be scalar here, arrays are handled in array
1965     // expression lowering. So no vector subscript or triplet is expected here.
1966     for (const auto &sub : aref.subscript()) {
1967       ExtValue subVal = genSubscript(sub);
1968       assert(fir::isUnboxedValue(subVal));
1969       arrayCoorArgs.push_back(
1970           builder.createConvert(loc, idxTy, fir::getBase(subVal)));
1971     }
1972     mlir::Value shape = builder.createShape(loc, exv);
1973     mlir::Value elementAddr = builder.create<fir::ArrayCoorOp>(
1974         loc, refTy, addr, shape, /*slice=*/mlir::Value{}, arrayCoorArgs,
1975         fir::getTypeParams(exv));
1976     return fir::factory::arrayElementToExtendedValue(builder, loc, exv,
1977                                                      elementAddr);
1978   }
1979 
1980   /// Return the coordinate of the array reference.
1981   ExtValue gen(const Fortran::evaluate::ArrayRef &aref) {
1982     ExtValue base = aref.base().IsSymbol() ? gen(getFirstSym(aref.base()))
1983                                            : gen(aref.base().GetComponent());
1984     // Check for command-line override to use array_coor op.
1985     if (generateArrayCoordinate)
1986       return genArrayCoorOp(base, aref);
1987     // Otherwise, use coordinate_of op.
1988     return genCoordinateOp(base, aref);
1989   }
1990 
1991   /// Return lower bounds of \p box in dimension \p dim. The returned value
1992   /// has type \ty.
1993   mlir::Value getLBound(const ExtValue &box, unsigned dim, mlir::Type ty) {
1994     assert(box.rank() > 0 && "must be an array");
1995     mlir::Location loc = getLoc();
1996     mlir::Value one = builder.createIntegerConstant(loc, ty, 1);
1997     mlir::Value lb = fir::factory::readLowerBound(builder, loc, box, dim, one);
1998     return builder.createConvert(loc, ty, lb);
1999   }
2000 
2001   ExtValue genval(const Fortran::evaluate::ArrayRef &aref) {
2002     return genLoad(gen(aref));
2003   }
2004 
2005   ExtValue gen(const Fortran::evaluate::CoarrayRef &coref) {
2006     return Fortran::lower::CoarrayExprHelper{converter, getLoc(), symMap}
2007         .genAddr(coref);
2008   }
2009 
2010   ExtValue genval(const Fortran::evaluate::CoarrayRef &coref) {
2011     return Fortran::lower::CoarrayExprHelper{converter, getLoc(), symMap}
2012         .genValue(coref);
2013   }
2014 
2015   template <typename A>
2016   ExtValue gen(const Fortran::evaluate::Designator<A> &des) {
2017     return std::visit([&](const auto &x) { return gen(x); }, des.u);
2018   }
2019   template <typename A>
2020   ExtValue genval(const Fortran::evaluate::Designator<A> &des) {
2021     return std::visit([&](const auto &x) { return genval(x); }, des.u);
2022   }
2023 
2024   mlir::Type genType(const Fortran::evaluate::DynamicType &dt) {
2025     if (dt.category() != Fortran::common::TypeCategory::Derived)
2026       return converter.genType(dt.category(), dt.kind());
2027     return converter.genType(dt.GetDerivedTypeSpec());
2028   }
2029 
2030   /// Lower a function reference
2031   template <typename A>
2032   ExtValue genFunctionRef(const Fortran::evaluate::FunctionRef<A> &funcRef) {
2033     if (!funcRef.GetType().has_value())
2034       fir::emitFatalError(getLoc(), "a function must have a type");
2035     mlir::Type resTy = genType(*funcRef.GetType());
2036     return genProcedureRef(funcRef, {resTy});
2037   }
2038 
2039   /// Lower function call `funcRef` and return a reference to the resultant
2040   /// value. This is required for lowering expressions such as `f1(f2(v))`.
2041   template <typename A>
2042   ExtValue gen(const Fortran::evaluate::FunctionRef<A> &funcRef) {
2043     ExtValue retVal = genFunctionRef(funcRef);
2044     mlir::Type resultType = converter.genType(toEvExpr(funcRef));
2045     return placeScalarValueInMemory(builder, getLoc(), retVal, resultType);
2046   }
2047 
2048   /// Helper to lower intrinsic arguments for inquiry intrinsic.
2049   ExtValue
2050   lowerIntrinsicArgumentAsInquired(const Fortran::lower::SomeExpr &expr) {
2051     if (Fortran::evaluate::IsAllocatableOrPointerObject(
2052             expr, converter.getFoldingContext()))
2053       return genMutableBoxValue(expr);
2054     /// Do not create temps for array sections whose properties only need to be
2055     /// inquired: create a descriptor that will be inquired.
2056     if (Fortran::evaluate::IsVariable(expr) && isArray(expr) &&
2057         !Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(expr))
2058       return lowerIntrinsicArgumentAsBox(expr);
2059     return gen(expr);
2060   }
2061 
2062   /// Helper to lower intrinsic arguments to a fir::BoxValue.
2063   /// It preserves all the non default lower bounds/non deferred length
2064   /// parameter information.
2065   ExtValue lowerIntrinsicArgumentAsBox(const Fortran::lower::SomeExpr &expr) {
2066     mlir::Location loc = getLoc();
2067     ExtValue exv = genBoxArg(expr);
2068     mlir::Value box = builder.createBox(loc, exv);
2069     return fir::BoxValue(
2070         box, fir::factory::getNonDefaultLowerBounds(builder, loc, exv),
2071         fir::factory::getNonDeferredLengthParams(exv));
2072   }
2073 
2074   /// Generate a call to an intrinsic function.
2075   ExtValue
2076   genIntrinsicRef(const Fortran::evaluate::ProcedureRef &procRef,
2077                   const Fortran::evaluate::SpecificIntrinsic &intrinsic,
2078                   llvm::Optional<mlir::Type> resultType) {
2079     llvm::SmallVector<ExtValue> operands;
2080 
2081     llvm::StringRef name = intrinsic.name;
2082     mlir::Location loc = getLoc();
2083     if (Fortran::lower::intrinsicRequiresCustomOptionalHandling(
2084             procRef, intrinsic, converter)) {
2085       using ExvAndPresence = std::pair<ExtValue, llvm::Optional<mlir::Value>>;
2086       llvm::SmallVector<ExvAndPresence, 4> operands;
2087       auto prepareOptionalArg = [&](const Fortran::lower::SomeExpr &expr) {
2088         ExtValue optionalArg = lowerIntrinsicArgumentAsInquired(expr);
2089         mlir::Value isPresent =
2090             genActualIsPresentTest(builder, loc, optionalArg);
2091         operands.emplace_back(optionalArg, isPresent);
2092       };
2093       auto prepareOtherArg = [&](const Fortran::lower::SomeExpr &expr) {
2094         operands.emplace_back(genval(expr), llvm::None);
2095       };
2096       Fortran::lower::prepareCustomIntrinsicArgument(
2097           procRef, intrinsic, resultType, prepareOptionalArg, prepareOtherArg,
2098           converter);
2099 
2100       auto getArgument = [&](std::size_t i) -> ExtValue {
2101         if (fir::conformsWithPassByRef(
2102                 fir::getBase(operands[i].first).getType()))
2103           return genLoad(operands[i].first);
2104         return operands[i].first;
2105       };
2106       auto isPresent = [&](std::size_t i) -> llvm::Optional<mlir::Value> {
2107         return operands[i].second;
2108       };
2109       return Fortran::lower::lowerCustomIntrinsic(
2110           builder, loc, name, resultType, isPresent, getArgument,
2111           operands.size(), stmtCtx);
2112     }
2113 
2114     const Fortran::lower::IntrinsicArgumentLoweringRules *argLowering =
2115         Fortran::lower::getIntrinsicArgumentLowering(name);
2116     for (const auto &[arg, dummy] :
2117          llvm::zip(procRef.arguments(),
2118                    intrinsic.characteristics.value().dummyArguments)) {
2119       auto *expr = Fortran::evaluate::UnwrapExpr<Fortran::lower::SomeExpr>(arg);
2120       if (!expr) {
2121         // Absent optional.
2122         operands.emplace_back(Fortran::lower::getAbsentIntrinsicArgument());
2123         continue;
2124       }
2125       if (!argLowering) {
2126         // No argument lowering instruction, lower by value.
2127         operands.emplace_back(genval(*expr));
2128         continue;
2129       }
2130       // Ad-hoc argument lowering handling.
2131       Fortran::lower::ArgLoweringRule argRules =
2132           Fortran::lower::lowerIntrinsicArgumentAs(loc, *argLowering,
2133                                                    dummy.name);
2134       if (argRules.handleDynamicOptional &&
2135           Fortran::evaluate::MayBePassedAsAbsentOptional(
2136               *expr, converter.getFoldingContext())) {
2137         ExtValue optional = lowerIntrinsicArgumentAsInquired(*expr);
2138         mlir::Value isPresent = genActualIsPresentTest(builder, loc, optional);
2139         switch (argRules.lowerAs) {
2140         case Fortran::lower::LowerIntrinsicArgAs::Value:
2141           operands.emplace_back(
2142               genOptionalValue(builder, loc, optional, isPresent));
2143           continue;
2144         case Fortran::lower::LowerIntrinsicArgAs::Addr:
2145           operands.emplace_back(
2146               genOptionalAddr(builder, loc, optional, isPresent));
2147           continue;
2148         case Fortran::lower::LowerIntrinsicArgAs::Box:
2149           operands.emplace_back(
2150               genOptionalBox(builder, loc, optional, isPresent));
2151           continue;
2152         case Fortran::lower::LowerIntrinsicArgAs::Inquired:
2153           operands.emplace_back(optional);
2154           continue;
2155         }
2156         llvm_unreachable("bad switch");
2157       }
2158       switch (argRules.lowerAs) {
2159       case Fortran::lower::LowerIntrinsicArgAs::Value:
2160         operands.emplace_back(genval(*expr));
2161         continue;
2162       case Fortran::lower::LowerIntrinsicArgAs::Addr:
2163         operands.emplace_back(gen(*expr));
2164         continue;
2165       case Fortran::lower::LowerIntrinsicArgAs::Box:
2166         operands.emplace_back(lowerIntrinsicArgumentAsBox(*expr));
2167         continue;
2168       case Fortran::lower::LowerIntrinsicArgAs::Inquired:
2169         operands.emplace_back(lowerIntrinsicArgumentAsInquired(*expr));
2170         continue;
2171       }
2172       llvm_unreachable("bad switch");
2173     }
2174     // Let the intrinsic library lower the intrinsic procedure call
2175     return Fortran::lower::genIntrinsicCall(builder, getLoc(), name, resultType,
2176                                             operands, stmtCtx);
2177   }
2178 
2179   template <typename A>
2180   bool isCharacterType(const A &exp) {
2181     if (auto type = exp.GetType())
2182       return type->category() == Fortran::common::TypeCategory::Character;
2183     return false;
2184   }
2185 
2186   /// helper to detect statement functions
2187   static bool
2188   isStatementFunctionCall(const Fortran::evaluate::ProcedureRef &procRef) {
2189     if (const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol())
2190       if (const auto *details =
2191               symbol->detailsIf<Fortran::semantics::SubprogramDetails>())
2192         return details->stmtFunction().has_value();
2193     return false;
2194   }
2195   /// Generate Statement function calls
2196   ExtValue genStmtFunctionRef(const Fortran::evaluate::ProcedureRef &procRef) {
2197     const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol();
2198     assert(symbol && "expected symbol in ProcedureRef of statement functions");
2199     const auto &details = symbol->get<Fortran::semantics::SubprogramDetails>();
2200 
2201     // Statement functions have their own scope, we just need to associate
2202     // the dummy symbols to argument expressions. They are no
2203     // optional/alternate return arguments. Statement functions cannot be
2204     // recursive (directly or indirectly) so it is safe to add dummy symbols to
2205     // the local map here.
2206     symMap.pushScope();
2207     for (auto [arg, bind] :
2208          llvm::zip(details.dummyArgs(), procRef.arguments())) {
2209       assert(arg && "alternate return in statement function");
2210       assert(bind && "optional argument in statement function");
2211       const auto *expr = bind->UnwrapExpr();
2212       // TODO: assumed type in statement function, that surprisingly seems
2213       // allowed, probably because nobody thought of restricting this usage.
2214       // gfortran/ifort compiles this.
2215       assert(expr && "assumed type used as statement function argument");
2216       // As per Fortran 2018 C1580, statement function arguments can only be
2217       // scalars, so just pass the box with the address. The only care is to
2218       // to use the dummy character explicit length if any instead of the
2219       // actual argument length (that can be bigger).
2220       if (const Fortran::semantics::DeclTypeSpec *type = arg->GetType())
2221         if (type->category() == Fortran::semantics::DeclTypeSpec::Character)
2222           if (const Fortran::semantics::MaybeIntExpr &lenExpr =
2223                   type->characterTypeSpec().length().GetExplicit()) {
2224             mlir::Value len = fir::getBase(genval(*lenExpr));
2225             // F2018 7.4.4.2 point 5.
2226             len = Fortran::lower::genMaxWithZero(builder, getLoc(), len);
2227             symMap.addSymbol(*arg,
2228                              replaceScalarCharacterLength(gen(*expr), len));
2229             continue;
2230           }
2231       symMap.addSymbol(*arg, gen(*expr));
2232     }
2233 
2234     // Explicitly map statement function host associated symbols to their
2235     // parent scope lowered symbol box.
2236     for (const Fortran::semantics::SymbolRef &sym :
2237          Fortran::evaluate::CollectSymbols(*details.stmtFunction()))
2238       if (const auto *details =
2239               sym->detailsIf<Fortran::semantics::HostAssocDetails>())
2240         if (!symMap.lookupSymbol(*sym))
2241           symMap.addSymbol(*sym, gen(details->symbol()));
2242 
2243     ExtValue result = genval(details.stmtFunction().value());
2244     LLVM_DEBUG(llvm::dbgs() << "stmt-function: " << result << '\n');
2245     symMap.popScope();
2246     return result;
2247   }
2248 
2249   /// Helper to package a Value and its properties into an ExtendedValue.
2250   static ExtValue toExtendedValue(mlir::Location loc, mlir::Value base,
2251                                   llvm::ArrayRef<mlir::Value> extents,
2252                                   llvm::ArrayRef<mlir::Value> lengths) {
2253     mlir::Type type = base.getType();
2254     if (type.isa<fir::BoxType>())
2255       return fir::BoxValue(base, /*lbounds=*/{}, lengths, extents);
2256     type = fir::unwrapRefType(type);
2257     if (type.isa<fir::BoxType>())
2258       return fir::MutableBoxValue(base, lengths, /*mutableProperties*/ {});
2259     if (auto seqTy = type.dyn_cast<fir::SequenceType>()) {
2260       if (seqTy.getDimension() != extents.size())
2261         fir::emitFatalError(loc, "incorrect number of extents for array");
2262       if (seqTy.getEleTy().isa<fir::CharacterType>()) {
2263         if (lengths.empty())
2264           fir::emitFatalError(loc, "missing length for character");
2265         assert(lengths.size() == 1);
2266         return fir::CharArrayBoxValue(base, lengths[0], extents);
2267       }
2268       return fir::ArrayBoxValue(base, extents);
2269     }
2270     if (type.isa<fir::CharacterType>()) {
2271       if (lengths.empty())
2272         fir::emitFatalError(loc, "missing length for character");
2273       assert(lengths.size() == 1);
2274       return fir::CharBoxValue(base, lengths[0]);
2275     }
2276     return base;
2277   }
2278 
2279   // Find the argument that corresponds to the host associations.
2280   // Verify some assumptions about how the signature was built here.
2281   [[maybe_unused]] static unsigned
2282   findHostAssocTuplePos(mlir::func::FuncOp fn) {
2283     // Scan the argument list from last to first as the host associations are
2284     // appended for now.
2285     for (unsigned i = fn.getNumArguments(); i > 0; --i)
2286       if (fn.getArgAttr(i - 1, fir::getHostAssocAttrName())) {
2287         // Host assoc tuple must be last argument (for now).
2288         assert(i == fn.getNumArguments() && "tuple must be last");
2289         return i - 1;
2290       }
2291     llvm_unreachable("anyFuncArgsHaveAttr failed");
2292   }
2293 
2294   /// Create a contiguous temporary array with the same shape,
2295   /// length parameters and type as mold. It is up to the caller to deallocate
2296   /// the temporary.
2297   ExtValue genArrayTempFromMold(const ExtValue &mold,
2298                                 llvm::StringRef tempName) {
2299     mlir::Type type = fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(mold).getType());
2300     assert(type && "expected descriptor or memory type");
2301     mlir::Location loc = getLoc();
2302     llvm::SmallVector<mlir::Value> extents =
2303         fir::factory::getExtents(loc, builder, mold);
2304     llvm::SmallVector<mlir::Value> allocMemTypeParams =
2305         fir::getTypeParams(mold);
2306     mlir::Value charLen;
2307     mlir::Type elementType = fir::unwrapSequenceType(type);
2308     if (auto charType = elementType.dyn_cast<fir::CharacterType>()) {
2309       charLen = allocMemTypeParams.empty()
2310                     ? fir::factory::readCharLen(builder, loc, mold)
2311                     : allocMemTypeParams[0];
2312       if (charType.hasDynamicLen() && allocMemTypeParams.empty())
2313         allocMemTypeParams.push_back(charLen);
2314     } else if (fir::hasDynamicSize(elementType)) {
2315       TODO(loc, "Creating temporary for derived type with length parameters");
2316     }
2317 
2318     mlir::Value temp = builder.create<fir::AllocMemOp>(
2319         loc, type, tempName, allocMemTypeParams, extents);
2320     if (fir::unwrapSequenceType(type).isa<fir::CharacterType>())
2321       return fir::CharArrayBoxValue{temp, charLen, extents};
2322     return fir::ArrayBoxValue{temp, extents};
2323   }
2324 
2325   /// Copy \p source array into \p dest array. Both arrays must be
2326   /// conforming, but neither array must be contiguous.
2327   void genArrayCopy(ExtValue dest, ExtValue source) {
2328     return createSomeArrayAssignment(converter, dest, source, symMap, stmtCtx);
2329   }
2330 
2331   /// Lower a non-elemental procedure reference and read allocatable and pointer
2332   /// results into normal values.
2333   ExtValue genProcedureRef(const Fortran::evaluate::ProcedureRef &procRef,
2334                            llvm::Optional<mlir::Type> resultType) {
2335     ExtValue res = genRawProcedureRef(procRef, resultType);
2336     // In most contexts, pointers and allocatable do not appear as allocatable
2337     // or pointer variable on the caller side (see 8.5.3 note 1 for
2338     // allocatables). The few context where this can happen must call
2339     // genRawProcedureRef directly.
2340     if (const auto *box = res.getBoxOf<fir::MutableBoxValue>())
2341       return fir::factory::genMutableBoxRead(builder, getLoc(), *box);
2342     return res;
2343   }
2344 
2345   /// Given a call site for which the arguments were already lowered, generate
2346   /// the call and return the result. This function deals with explicit result
2347   /// allocation and lowering if needed. It also deals with passing the host
2348   /// link to internal procedures.
2349   ExtValue genCallOpAndResult(Fortran::lower::CallerInterface &caller,
2350                               mlir::FunctionType callSiteType,
2351                               llvm::Optional<mlir::Type> resultType) {
2352     mlir::Location loc = getLoc();
2353     using PassBy = Fortran::lower::CallerInterface::PassEntityBy;
2354     // Handle cases where caller must allocate the result or a fir.box for it.
2355     bool mustPopSymMap = false;
2356     if (caller.mustMapInterfaceSymbols()) {
2357       symMap.pushScope();
2358       mustPopSymMap = true;
2359       Fortran::lower::mapCallInterfaceSymbols(converter, caller, symMap);
2360     }
2361     // If this is an indirect call, retrieve the function address. Also retrieve
2362     // the result length if this is a character function (note that this length
2363     // will be used only if there is no explicit length in the local interface).
2364     mlir::Value funcPointer;
2365     mlir::Value charFuncPointerLength;
2366     if (const Fortran::semantics::Symbol *sym =
2367             caller.getIfIndirectCallSymbol()) {
2368       funcPointer = symMap.lookupSymbol(*sym).getAddr();
2369       if (!funcPointer)
2370         fir::emitFatalError(loc, "failed to find indirect call symbol address");
2371       if (fir::isCharacterProcedureTuple(funcPointer.getType(),
2372                                          /*acceptRawFunc=*/false))
2373         std::tie(funcPointer, charFuncPointerLength) =
2374             fir::factory::extractCharacterProcedureTuple(builder, loc,
2375                                                          funcPointer);
2376     }
2377 
2378     mlir::IndexType idxTy = builder.getIndexType();
2379     auto lowerSpecExpr = [&](const auto &expr) -> mlir::Value {
2380       return builder.createConvert(
2381           loc, idxTy, fir::getBase(converter.genExprValue(expr, stmtCtx)));
2382     };
2383     llvm::SmallVector<mlir::Value> resultLengths;
2384     auto allocatedResult = [&]() -> llvm::Optional<ExtValue> {
2385       llvm::SmallVector<mlir::Value> extents;
2386       llvm::SmallVector<mlir::Value> lengths;
2387       if (!caller.callerAllocateResult())
2388         return {};
2389       mlir::Type type = caller.getResultStorageType();
2390       if (type.isa<fir::SequenceType>())
2391         caller.walkResultExtents([&](const Fortran::lower::SomeExpr &e) {
2392           extents.emplace_back(lowerSpecExpr(e));
2393         });
2394       caller.walkResultLengths([&](const Fortran::lower::SomeExpr &e) {
2395         lengths.emplace_back(lowerSpecExpr(e));
2396       });
2397 
2398       // Result length parameters should not be provided to box storage
2399       // allocation and save_results, but they are still useful information to
2400       // keep in the ExtendedValue if non-deferred.
2401       if (!type.isa<fir::BoxType>()) {
2402         if (fir::isa_char(fir::unwrapSequenceType(type)) && lengths.empty()) {
2403           // Calling an assumed length function. This is only possible if this
2404           // is a call to a character dummy procedure.
2405           if (!charFuncPointerLength)
2406             fir::emitFatalError(loc, "failed to retrieve character function "
2407                                      "length while calling it");
2408           lengths.push_back(charFuncPointerLength);
2409         }
2410         resultLengths = lengths;
2411       }
2412 
2413       if (!extents.empty() || !lengths.empty()) {
2414         auto *bldr = &converter.getFirOpBuilder();
2415         auto stackSaveFn = fir::factory::getLlvmStackSave(builder);
2416         auto stackSaveSymbol = bldr->getSymbolRefAttr(stackSaveFn.getName());
2417         mlir::Value sp =
2418             bldr->create<fir::CallOp>(
2419                     loc, stackSaveFn.getFunctionType().getResults(),
2420                     stackSaveSymbol, mlir::ValueRange{})
2421                 .getResult(0);
2422         stmtCtx.attachCleanup([bldr, loc, sp]() {
2423           auto stackRestoreFn = fir::factory::getLlvmStackRestore(*bldr);
2424           auto stackRestoreSymbol =
2425               bldr->getSymbolRefAttr(stackRestoreFn.getName());
2426           bldr->create<fir::CallOp>(
2427               loc, stackRestoreFn.getFunctionType().getResults(),
2428               stackRestoreSymbol, mlir::ValueRange{sp});
2429         });
2430       }
2431       mlir::Value temp =
2432           builder.createTemporary(loc, type, ".result", extents, resultLengths);
2433       return toExtendedValue(loc, temp, extents, lengths);
2434     }();
2435 
2436     if (mustPopSymMap)
2437       symMap.popScope();
2438 
2439     // Place allocated result or prepare the fir.save_result arguments.
2440     mlir::Value arrayResultShape;
2441     if (allocatedResult) {
2442       if (std::optional<Fortran::lower::CallInterface<
2443               Fortran::lower::CallerInterface>::PassedEntity>
2444               resultArg = caller.getPassedResult()) {
2445         if (resultArg->passBy == PassBy::AddressAndLength)
2446           caller.placeAddressAndLengthInput(*resultArg,
2447                                             fir::getBase(*allocatedResult),
2448                                             fir::getLen(*allocatedResult));
2449         else if (resultArg->passBy == PassBy::BaseAddress)
2450           caller.placeInput(*resultArg, fir::getBase(*allocatedResult));
2451         else
2452           fir::emitFatalError(
2453               loc, "only expect character scalar result to be passed by ref");
2454       } else {
2455         assert(caller.mustSaveResult());
2456         arrayResultShape = allocatedResult->match(
2457             [&](const fir::CharArrayBoxValue &) {
2458               return builder.createShape(loc, *allocatedResult);
2459             },
2460             [&](const fir::ArrayBoxValue &) {
2461               return builder.createShape(loc, *allocatedResult);
2462             },
2463             [&](const auto &) { return mlir::Value{}; });
2464       }
2465     }
2466 
2467     // In older Fortran, procedure argument types are inferred. This may lead
2468     // different view of what the function signature is in different locations.
2469     // Casts are inserted as needed below to accommodate this.
2470 
2471     // The mlir::func::FuncOp type prevails, unless it has a different number of
2472     // arguments which can happen in legal program if it was passed as a dummy
2473     // procedure argument earlier with no further type information.
2474     mlir::SymbolRefAttr funcSymbolAttr;
2475     bool addHostAssociations = false;
2476     if (!funcPointer) {
2477       mlir::FunctionType funcOpType = caller.getFuncOp().getFunctionType();
2478       mlir::SymbolRefAttr symbolAttr =
2479           builder.getSymbolRefAttr(caller.getMangledName());
2480       if (callSiteType.getNumResults() == funcOpType.getNumResults() &&
2481           callSiteType.getNumInputs() + 1 == funcOpType.getNumInputs() &&
2482           fir::anyFuncArgsHaveAttr(caller.getFuncOp(),
2483                                    fir::getHostAssocAttrName())) {
2484         // The number of arguments is off by one, and we're lowering a function
2485         // with host associations. Modify call to include host associations
2486         // argument by appending the value at the end of the operands.
2487         assert(funcOpType.getInput(findHostAssocTuplePos(caller.getFuncOp())) ==
2488                converter.hostAssocTupleValue().getType());
2489         addHostAssociations = true;
2490       }
2491       if (!addHostAssociations &&
2492           (callSiteType.getNumResults() != funcOpType.getNumResults() ||
2493            callSiteType.getNumInputs() != funcOpType.getNumInputs())) {
2494         // Deal with argument number mismatch by making a function pointer so
2495         // that function type cast can be inserted. Do not emit a warning here
2496         // because this can happen in legal program if the function is not
2497         // defined here and it was first passed as an argument without any more
2498         // information.
2499         funcPointer =
2500             builder.create<fir::AddrOfOp>(loc, funcOpType, symbolAttr);
2501       } else if (callSiteType.getResults() != funcOpType.getResults()) {
2502         // Implicit interface result type mismatch are not standard Fortran, but
2503         // some compilers are not complaining about it.  The front end is not
2504         // protecting lowering from this currently. Support this with a
2505         // discouraging warning.
2506         LLVM_DEBUG(mlir::emitWarning(
2507             loc, "a return type mismatch is not standard compliant and may "
2508                  "lead to undefined behavior."));
2509         // Cast the actual function to the current caller implicit type because
2510         // that is the behavior we would get if we could not see the definition.
2511         funcPointer =
2512             builder.create<fir::AddrOfOp>(loc, funcOpType, symbolAttr);
2513       } else {
2514         funcSymbolAttr = symbolAttr;
2515       }
2516     }
2517 
2518     mlir::FunctionType funcType =
2519         funcPointer ? callSiteType : caller.getFuncOp().getFunctionType();
2520     llvm::SmallVector<mlir::Value> operands;
2521     // First operand of indirect call is the function pointer. Cast it to
2522     // required function type for the call to handle procedures that have a
2523     // compatible interface in Fortran, but that have different signatures in
2524     // FIR.
2525     if (funcPointer) {
2526       operands.push_back(
2527           funcPointer.getType().isa<fir::BoxProcType>()
2528               ? builder.create<fir::BoxAddrOp>(loc, funcType, funcPointer)
2529               : builder.createConvert(loc, funcType, funcPointer));
2530     }
2531 
2532     // Deal with potential mismatches in arguments types. Passing an array to a
2533     // scalar argument should for instance be tolerated here.
2534     bool callingImplicitInterface = caller.canBeCalledViaImplicitInterface();
2535     for (auto [fst, snd] :
2536          llvm::zip(caller.getInputs(), funcType.getInputs())) {
2537       // When passing arguments to a procedure that can be called an implicit
2538       // interface, allow character actual arguments to be passed to dummy
2539       // arguments of any type and vice versa
2540       mlir::Value cast;
2541       auto *context = builder.getContext();
2542       if (snd.isa<fir::BoxProcType>() &&
2543           fst.getType().isa<mlir::FunctionType>()) {
2544         auto funcTy = mlir::FunctionType::get(context, llvm::None, llvm::None);
2545         auto boxProcTy = builder.getBoxProcType(funcTy);
2546         if (mlir::Value host = argumentHostAssocs(converter, fst)) {
2547           cast = builder.create<fir::EmboxProcOp>(
2548               loc, boxProcTy, llvm::ArrayRef<mlir::Value>{fst, host});
2549         } else {
2550           cast = builder.create<fir::EmboxProcOp>(loc, boxProcTy, fst);
2551         }
2552       } else {
2553         cast = builder.convertWithSemantics(loc, snd, fst,
2554                                             callingImplicitInterface);
2555       }
2556       operands.push_back(cast);
2557     }
2558 
2559     // Add host associations as necessary.
2560     if (addHostAssociations)
2561       operands.push_back(converter.hostAssocTupleValue());
2562 
2563     auto call = builder.create<fir::CallOp>(loc, funcType.getResults(),
2564                                             funcSymbolAttr, operands);
2565 
2566     if (caller.mustSaveResult())
2567       builder.create<fir::SaveResultOp>(
2568           loc, call.getResult(0), fir::getBase(allocatedResult.getValue()),
2569           arrayResultShape, resultLengths);
2570 
2571     if (allocatedResult) {
2572       allocatedResult->match(
2573           [&](const fir::MutableBoxValue &box) {
2574             if (box.isAllocatable()) {
2575               // 9.7.3.2 point 4. Finalize allocatables.
2576               fir::FirOpBuilder *bldr = &converter.getFirOpBuilder();
2577               stmtCtx.attachCleanup([bldr, loc, box]() {
2578                 fir::factory::genFinalization(*bldr, loc, box);
2579               });
2580             }
2581           },
2582           [](const auto &) {});
2583       return *allocatedResult;
2584     }
2585 
2586     if (!resultType.hasValue())
2587       return mlir::Value{}; // subroutine call
2588     // For now, Fortran return values are implemented with a single MLIR
2589     // function return value.
2590     assert(call.getNumResults() == 1 &&
2591            "Expected exactly one result in FUNCTION call");
2592     return call.getResult(0);
2593   }
2594 
2595   /// Like genExtAddr, but ensure the address returned is a temporary even if \p
2596   /// expr is variable inside parentheses.
2597   ExtValue genTempExtAddr(const Fortran::lower::SomeExpr &expr) {
2598     // In general, genExtAddr might not create a temp for variable inside
2599     // parentheses to avoid creating array temporary in sub-expressions. It only
2600     // ensures the sub-expression is not re-associated with other parts of the
2601     // expression. In the call semantics, there is a difference between expr and
2602     // variable (see R1524). For expressions, a variable storage must not be
2603     // argument associated since it could be modified inside the call, or the
2604     // variable could also be modified by other means during the call.
2605     if (!isParenthesizedVariable(expr))
2606       return genExtAddr(expr);
2607     if (expr.Rank() > 0)
2608       return asArray(expr);
2609     mlir::Location loc = getLoc();
2610     return genExtValue(expr).match(
2611         [&](const fir::CharBoxValue &boxChar) -> ExtValue {
2612           return fir::factory::CharacterExprHelper{builder, loc}.createTempFrom(
2613               boxChar);
2614         },
2615         [&](const fir::UnboxedValue &v) -> ExtValue {
2616           mlir::Type type = v.getType();
2617           mlir::Value value = v;
2618           if (fir::isa_ref_type(type))
2619             value = builder.create<fir::LoadOp>(loc, value);
2620           mlir::Value temp = builder.createTemporary(loc, value.getType());
2621           builder.create<fir::StoreOp>(loc, value, temp);
2622           return temp;
2623         },
2624         [&](const fir::BoxValue &x) -> ExtValue {
2625           // Derived type scalar that may be polymorphic.
2626           assert(!x.hasRank() && x.isDerived());
2627           if (x.isDerivedWithLenParameters())
2628             fir::emitFatalError(
2629                 loc, "making temps for derived type with length parameters");
2630           // TODO: polymorphic aspects should be kept but for now the temp
2631           // created always has the declared type.
2632           mlir::Value var =
2633               fir::getBase(fir::factory::readBoxValue(builder, loc, x));
2634           auto value = builder.create<fir::LoadOp>(loc, var);
2635           mlir::Value temp = builder.createTemporary(loc, value.getType());
2636           builder.create<fir::StoreOp>(loc, value, temp);
2637           return temp;
2638         },
2639         [&](const auto &) -> ExtValue {
2640           fir::emitFatalError(loc, "expr is not a scalar value");
2641         });
2642   }
2643 
2644   /// Helper structure to track potential copy-in of non contiguous variable
2645   /// argument into a contiguous temp. It is used to deallocate the temp that
2646   /// may have been created as well as to the copy-out from the temp to the
2647   /// variable after the call.
2648   struct CopyOutPair {
2649     ExtValue var;
2650     ExtValue temp;
2651     // Flag to indicate if the argument may have been modified by the
2652     // callee, in which case it must be copied-out to the variable.
2653     bool argMayBeModifiedByCall;
2654     // Optional boolean value that, if present and false, prevents
2655     // the copy-out and temp deallocation.
2656     llvm::Optional<mlir::Value> restrictCopyAndFreeAtRuntime;
2657   };
2658   using CopyOutPairs = llvm::SmallVector<CopyOutPair, 4>;
2659 
2660   /// Helper to read any fir::BoxValue into other fir::ExtendedValue categories
2661   /// not based on fir.box.
2662   /// This will lose any non contiguous stride information and dynamic type and
2663   /// should only be called if \p exv is known to be contiguous or if its base
2664   /// address will be replaced by a contiguous one. If \p exv is not a
2665   /// fir::BoxValue, this is a no-op.
2666   ExtValue readIfBoxValue(const ExtValue &exv) {
2667     if (const auto *box = exv.getBoxOf<fir::BoxValue>())
2668       return fir::factory::readBoxValue(builder, getLoc(), *box);
2669     return exv;
2670   }
2671 
2672   /// Generate a contiguous temp to pass \p actualArg as argument \p arg. The
2673   /// creation of the temp and copy-in can be made conditional at runtime by
2674   /// providing a runtime boolean flag \p restrictCopyAtRuntime (in which case
2675   /// the temp and copy will only be made if the value is true at runtime).
2676   ExtValue genCopyIn(const ExtValue &actualArg,
2677                      const Fortran::lower::CallerInterface::PassedEntity &arg,
2678                      CopyOutPairs &copyOutPairs,
2679                      llvm::Optional<mlir::Value> restrictCopyAtRuntime) {
2680     if (!restrictCopyAtRuntime) {
2681       ExtValue temp = genArrayTempFromMold(actualArg, ".copyinout");
2682       if (arg.mayBeReadByCall())
2683         genArrayCopy(temp, actualArg);
2684       copyOutPairs.emplace_back(CopyOutPair{
2685           actualArg, temp, arg.mayBeModifiedByCall(), restrictCopyAtRuntime});
2686       return temp;
2687     }
2688     // Otherwise, need to be careful to only copy-in if allowed at runtime.
2689     mlir::Location loc = getLoc();
2690     auto addrType = fir::HeapType::get(
2691         fir::unwrapPassByRefType(fir::getBase(actualArg).getType()));
2692     mlir::Value addr =
2693         builder
2694             .genIfOp(loc, {addrType}, *restrictCopyAtRuntime,
2695                      /*withElseRegion=*/true)
2696             .genThen([&]() {
2697               auto temp = genArrayTempFromMold(actualArg, ".copyinout");
2698               if (arg.mayBeReadByCall())
2699                 genArrayCopy(temp, actualArg);
2700               builder.create<fir::ResultOp>(loc, fir::getBase(temp));
2701             })
2702             .genElse([&]() {
2703               auto nullPtr = builder.createNullConstant(loc, addrType);
2704               builder.create<fir::ResultOp>(loc, nullPtr);
2705             })
2706             .getResults()[0];
2707     // Associate the temp address with actualArg lengths and extents.
2708     fir::ExtendedValue temp = fir::substBase(readIfBoxValue(actualArg), addr);
2709     copyOutPairs.emplace_back(CopyOutPair{
2710         actualArg, temp, arg.mayBeModifiedByCall(), restrictCopyAtRuntime});
2711     return temp;
2712   }
2713 
2714   /// Generate copy-out if needed and free the temporary for an argument that
2715   /// has been copied-in into a contiguous temp.
2716   void genCopyOut(const CopyOutPair &copyOutPair) {
2717     mlir::Location loc = getLoc();
2718     if (!copyOutPair.restrictCopyAndFreeAtRuntime) {
2719       if (copyOutPair.argMayBeModifiedByCall)
2720         genArrayCopy(copyOutPair.var, copyOutPair.temp);
2721       builder.create<fir::FreeMemOp>(loc, fir::getBase(copyOutPair.temp));
2722       return;
2723     }
2724     builder.genIfThen(loc, *copyOutPair.restrictCopyAndFreeAtRuntime)
2725         .genThen([&]() {
2726           if (copyOutPair.argMayBeModifiedByCall)
2727             genArrayCopy(copyOutPair.var, copyOutPair.temp);
2728           builder.create<fir::FreeMemOp>(loc, fir::getBase(copyOutPair.temp));
2729         })
2730         .end();
2731   }
2732 
2733   /// Lower a designator to a variable that may be absent at runtime into an
2734   /// ExtendedValue where all the properties (base address, shape and length
2735   /// parameters) can be safely read (set to zero if not present). It also
2736   /// returns a boolean mlir::Value telling if the variable is present at
2737   /// runtime.
2738   /// This is useful to later be able to do conditional copy-in/copy-out
2739   /// or to retrieve the base address without having to deal with the case
2740   /// where the actual may be an absent fir.box.
2741   std::pair<ExtValue, mlir::Value>
2742   prepareActualThatMayBeAbsent(const Fortran::lower::SomeExpr &expr) {
2743     mlir::Location loc = getLoc();
2744     if (Fortran::evaluate::IsAllocatableOrPointerObject(
2745             expr, converter.getFoldingContext())) {
2746       // Fortran 2018 15.5.2.12 point 1: If unallocated/disassociated,
2747       // it is as if the argument was absent. The main care here is to
2748       // not do a copy-in/copy-out because the temp address, even though
2749       // pointing to a null size storage, would not be a nullptr and
2750       // therefore the argument would not be considered absent on the
2751       // callee side. Note: if wholeSymbol is optional, it cannot be
2752       // absent as per 15.5.2.12 point 7. and 8. We rely on this to
2753       // un-conditionally read the allocatable/pointer descriptor here.
2754       fir::MutableBoxValue mutableBox = genMutableBoxValue(expr);
2755       mlir::Value isPresent = fir::factory::genIsAllocatedOrAssociatedTest(
2756           builder, loc, mutableBox);
2757       fir::ExtendedValue actualArg =
2758           fir::factory::genMutableBoxRead(builder, loc, mutableBox);
2759       return {actualArg, isPresent};
2760     }
2761     // Absent descriptor cannot be read. To avoid any issue in
2762     // copy-in/copy-out, and when retrieving the address/length
2763     // create an descriptor pointing to a null address here if the
2764     // fir.box is absent.
2765     ExtValue actualArg = gen(expr);
2766     mlir::Value actualArgBase = fir::getBase(actualArg);
2767     mlir::Value isPresent = builder.create<fir::IsPresentOp>(
2768         loc, builder.getI1Type(), actualArgBase);
2769     if (!actualArgBase.getType().isa<fir::BoxType>())
2770       return {actualArg, isPresent};
2771     ExtValue safeToReadBox;
2772     return {safeToReadBox, isPresent};
2773   }
2774 
2775   /// Create a temp on the stack for scalar actual arguments that may be absent
2776   /// at runtime, but must be passed via a temp if they are presents.
2777   fir::ExtendedValue
2778   createScalarTempForArgThatMayBeAbsent(ExtValue actualArg,
2779                                         mlir::Value isPresent) {
2780     mlir::Location loc = getLoc();
2781     mlir::Type type = fir::unwrapRefType(fir::getBase(actualArg).getType());
2782     if (fir::isDerivedWithLenParameters(actualArg))
2783       TODO(loc, "parametrized derived type optional scalar argument copy-in");
2784     if (const fir::CharBoxValue *charBox = actualArg.getCharBox()) {
2785       mlir::Value len = charBox->getLen();
2786       mlir::Value zero = builder.createIntegerConstant(loc, len.getType(), 0);
2787       len = builder.create<mlir::arith::SelectOp>(loc, isPresent, len, zero);
2788       mlir::Value temp = builder.createTemporary(
2789           loc, type, /*name=*/{}, /*shape=*/{}, mlir::ValueRange{len},
2790           llvm::ArrayRef<mlir::NamedAttribute>{
2791               Fortran::lower::getAdaptToByRefAttr(builder)});
2792       return fir::CharBoxValue{temp, len};
2793     }
2794     assert((fir::isa_trivial(type) || type.isa<fir::RecordType>()) &&
2795            "must be simple scalar");
2796     return builder.createTemporary(
2797         loc, type,
2798         llvm::ArrayRef<mlir::NamedAttribute>{
2799             Fortran::lower::getAdaptToByRefAttr(builder)});
2800   }
2801 
2802   /// Lower an actual argument that must be passed via an address.
2803   /// This generates of the copy-in/copy-out if the actual is not contiguous, or
2804   /// the creation of the temp if the actual is a variable and \p byValue is
2805   /// true. It handles the cases where the actual may be absent, and all of the
2806   /// copying has to be conditional at runtime.
2807   ExtValue prepareActualToBaseAddressLike(
2808       const Fortran::lower::SomeExpr &expr,
2809       const Fortran::lower::CallerInterface::PassedEntity &arg,
2810       CopyOutPairs &copyOutPairs, bool byValue) {
2811     mlir::Location loc = getLoc();
2812     const bool isArray = expr.Rank() > 0;
2813     const bool actualArgIsVariable = Fortran::evaluate::IsVariable(expr);
2814     // It must be possible to modify VALUE arguments on the callee side, even
2815     // if the actual argument is a literal or named constant. Hence, the
2816     // address of static storage must not be passed in that case, and a copy
2817     // must be made even if this is not a variable.
2818     // Note: isArray should be used here, but genBoxArg already creates copies
2819     // for it, so do not duplicate the copy until genBoxArg behavior is changed.
2820     const bool isStaticConstantByValue =
2821         byValue && Fortran::evaluate::IsActuallyConstant(expr) &&
2822         (isCharacterType(expr));
2823     const bool variableNeedsCopy =
2824         actualArgIsVariable &&
2825         (byValue || (isArray && !Fortran::evaluate::IsSimplyContiguous(
2826                                     expr, converter.getFoldingContext())));
2827     const bool needsCopy = isStaticConstantByValue || variableNeedsCopy;
2828     auto argAddr = [&]() -> ExtValue {
2829       if (!actualArgIsVariable && !needsCopy)
2830         // Actual argument is not a variable. Make sure a variable address is
2831         // not passed.
2832         return genTempExtAddr(expr);
2833       ExtValue baseAddr;
2834       if (arg.isOptional() && Fortran::evaluate::MayBePassedAsAbsentOptional(
2835                                   expr, converter.getFoldingContext())) {
2836         auto [actualArgBind, isPresent] = prepareActualThatMayBeAbsent(expr);
2837         const ExtValue &actualArg = actualArgBind;
2838         if (!needsCopy)
2839           return actualArg;
2840 
2841         if (isArray)
2842           return genCopyIn(actualArg, arg, copyOutPairs,
2843                            isPresent /*, byValue*/);
2844         // Scalars, create a temp, and use it conditionally at runtime if
2845         // the argument is present.
2846         ExtValue temp =
2847             createScalarTempForArgThatMayBeAbsent(actualArg, isPresent);
2848         mlir::Type tempAddrTy = fir::getBase(temp).getType();
2849         mlir::Value selectAddr =
2850             builder
2851                 .genIfOp(loc, {tempAddrTy}, isPresent,
2852                          /*withElseRegion=*/true)
2853                 .genThen([&]() {
2854                   fir::factory::genScalarAssignment(builder, loc, temp,
2855                                                     actualArg);
2856                   builder.create<fir::ResultOp>(loc, fir::getBase(temp));
2857                 })
2858                 .genElse([&]() {
2859                   mlir::Value absent =
2860                       builder.create<fir::AbsentOp>(loc, tempAddrTy);
2861                   builder.create<fir::ResultOp>(loc, absent);
2862                 })
2863                 .getResults()[0];
2864         return fir::substBase(temp, selectAddr);
2865       }
2866       // Actual cannot be absent, the actual argument can safely be
2867       // copied-in/copied-out without any care if needed.
2868       if (isArray) {
2869         ExtValue box = genBoxArg(expr);
2870         if (needsCopy)
2871           return genCopyIn(box, arg, copyOutPairs,
2872                            /*restrictCopyAtRuntime=*/llvm::None /*, byValue*/);
2873         // Contiguous: just use the box we created above!
2874         // This gets "unboxed" below, if needed.
2875         return box;
2876       }
2877       // Actual argument is a non-optional, non-pointer, non-allocatable
2878       // scalar.
2879       ExtValue actualArg = genExtAddr(expr);
2880       if (needsCopy)
2881         return createInMemoryScalarCopy(builder, loc, actualArg);
2882       return actualArg;
2883     }();
2884     // Scalar and contiguous expressions may be lowered to a fir.box,
2885     // either to account for potential polymorphism, or because lowering
2886     // did not account for some contiguity hints.
2887     // Here, polymorphism does not matter (an entity of the declared type
2888     // is passed, not one of the dynamic type), and the expr is known to
2889     // be simply contiguous, so it is safe to unbox it and pass the
2890     // address without making a copy.
2891     return readIfBoxValue(argAddr);
2892   }
2893 
2894   /// Lower a non-elemental procedure reference.
2895   ExtValue genRawProcedureRef(const Fortran::evaluate::ProcedureRef &procRef,
2896                               llvm::Optional<mlir::Type> resultType) {
2897     mlir::Location loc = getLoc();
2898     if (isElementalProcWithArrayArgs(procRef))
2899       fir::emitFatalError(loc, "trying to lower elemental procedure with array "
2900                                "arguments as normal procedure");
2901     if (const Fortran::evaluate::SpecificIntrinsic *intrinsic =
2902             procRef.proc().GetSpecificIntrinsic())
2903       return genIntrinsicRef(procRef, *intrinsic, resultType);
2904 
2905     if (isStatementFunctionCall(procRef))
2906       return genStmtFunctionRef(procRef);
2907 
2908     Fortran::lower::CallerInterface caller(procRef, converter);
2909     using PassBy = Fortran::lower::CallerInterface::PassEntityBy;
2910 
2911     llvm::SmallVector<fir::MutableBoxValue> mutableModifiedByCall;
2912     // List of <var, temp> where temp must be copied into var after the call.
2913     CopyOutPairs copyOutPairs;
2914 
2915     mlir::FunctionType callSiteType = caller.genFunctionType();
2916 
2917     // Lower the actual arguments and map the lowered values to the dummy
2918     // arguments.
2919     for (const Fortran::lower::CallInterface<
2920              Fortran::lower::CallerInterface>::PassedEntity &arg :
2921          caller.getPassedArguments()) {
2922       const auto *actual = arg.entity;
2923       mlir::Type argTy = callSiteType.getInput(arg.firArgument);
2924       if (!actual) {
2925         // Optional dummy argument for which there is no actual argument.
2926         caller.placeInput(arg, builder.create<fir::AbsentOp>(loc, argTy));
2927         continue;
2928       }
2929       const auto *expr = actual->UnwrapExpr();
2930       if (!expr)
2931         TODO(loc, "assumed type actual argument lowering");
2932 
2933       if (arg.passBy == PassBy::Value) {
2934         ExtValue argVal = genval(*expr);
2935         if (!fir::isUnboxedValue(argVal))
2936           fir::emitFatalError(
2937               loc, "internal error: passing non trivial value by value");
2938         caller.placeInput(arg, fir::getBase(argVal));
2939         continue;
2940       }
2941 
2942       if (arg.passBy == PassBy::MutableBox) {
2943         if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
2944                 *expr)) {
2945           // If expr is NULL(), the mutableBox created must be a deallocated
2946           // pointer with the dummy argument characteristics (see table 16.5
2947           // in Fortran 2018 standard).
2948           // No length parameters are set for the created box because any non
2949           // deferred type parameters of the dummy will be evaluated on the
2950           // callee side, and it is illegal to use NULL without a MOLD if any
2951           // dummy length parameters are assumed.
2952           mlir::Type boxTy = fir::dyn_cast_ptrEleTy(argTy);
2953           assert(boxTy && boxTy.isa<fir::BoxType>() &&
2954                  "must be a fir.box type");
2955           mlir::Value boxStorage = builder.createTemporary(loc, boxTy);
2956           mlir::Value nullBox = fir::factory::createUnallocatedBox(
2957               builder, loc, boxTy, /*nonDeferredParams=*/{});
2958           builder.create<fir::StoreOp>(loc, nullBox, boxStorage);
2959           caller.placeInput(arg, boxStorage);
2960           continue;
2961         }
2962         if (fir::isPointerType(argTy) &&
2963             !Fortran::evaluate::IsObjectPointer(
2964                 *expr, converter.getFoldingContext())) {
2965           // Passing a non POINTER actual argument to a POINTER dummy argument.
2966           // Create a pointer of the dummy argument type and assign the actual
2967           // argument to it.
2968           mlir::Value irBox =
2969               builder.createTemporary(loc, fir::unwrapRefType(argTy));
2970           // Non deferred parameters will be evaluated on the callee side.
2971           fir::MutableBoxValue pointer(irBox,
2972                                        /*nonDeferredParams=*/mlir::ValueRange{},
2973                                        /*mutableProperties=*/{});
2974           Fortran::lower::associateMutableBox(converter, loc, pointer, *expr,
2975                                               /*lbounds=*/llvm::None, stmtCtx);
2976           caller.placeInput(arg, irBox);
2977           continue;
2978         }
2979         // Passing a POINTER to a POINTER, or an ALLOCATABLE to an ALLOCATABLE.
2980         fir::MutableBoxValue mutableBox = genMutableBoxValue(*expr);
2981         mlir::Value irBox =
2982             fir::factory::getMutableIRBox(builder, loc, mutableBox);
2983         caller.placeInput(arg, irBox);
2984         if (arg.mayBeModifiedByCall())
2985           mutableModifiedByCall.emplace_back(std::move(mutableBox));
2986         continue;
2987       }
2988       const bool actualArgIsVariable = Fortran::evaluate::IsVariable(*expr);
2989       if (arg.passBy == PassBy::BaseAddressValueAttribute) {
2990         mlir::Value temp;
2991         if (isArray(*expr)) {
2992           auto val = genBoxArg(*expr);
2993           if (!actualArgIsVariable)
2994             temp = getBase(val);
2995           else {
2996             ExtValue copy = genArrayTempFromMold(val, ".copy");
2997             genArrayCopy(copy, val);
2998             temp = fir::getBase(copy);
2999           }
3000         } else {
3001           mlir::Value val = fir::getBase(genval(*expr));
3002           temp = builder.createTemporary(
3003               loc, val.getType(),
3004               llvm::ArrayRef<mlir::NamedAttribute>{
3005                   Fortran::lower::getAdaptToByRefAttr(builder)});
3006           builder.create<fir::StoreOp>(loc, val, temp);
3007         }
3008         caller.placeInput(arg, temp);
3009         continue;
3010       }
3011       if (arg.passBy == PassBy::BaseAddress || arg.passBy == PassBy::BoxChar) {
3012         const bool actualIsSimplyContiguous =
3013             !actualArgIsVariable || Fortran::evaluate::IsSimplyContiguous(
3014                                         *expr, converter.getFoldingContext());
3015         auto argAddr = [&]() -> ExtValue {
3016           ExtValue baseAddr;
3017           if (actualArgIsVariable && arg.isOptional()) {
3018             if (Fortran::evaluate::IsAllocatableOrPointerObject(
3019                     *expr, converter.getFoldingContext())) {
3020               // Fortran 2018 15.5.2.12 point 1: If unallocated/disassociated,
3021               // it is as if the argument was absent. The main care here is to
3022               // not do a copy-in/copy-out because the temp address, even though
3023               // pointing to a null size storage, would not be a nullptr and
3024               // therefore the argument would not be considered absent on the
3025               // callee side. Note: if wholeSymbol is optional, it cannot be
3026               // absent as per 15.5.2.12 point 7. and 8. We rely on this to
3027               // un-conditionally read the allocatable/pointer descriptor here.
3028               if (actualIsSimplyContiguous)
3029                 return genBoxArg(*expr);
3030               fir::MutableBoxValue mutableBox = genMutableBoxValue(*expr);
3031               mlir::Value isAssociated =
3032                   fir::factory::genIsAllocatedOrAssociatedTest(builder, loc,
3033                                                                mutableBox);
3034               fir::ExtendedValue actualExv =
3035                   fir::factory::genMutableBoxRead(builder, loc, mutableBox);
3036               return genCopyIn(actualExv, arg, copyOutPairs, isAssociated);
3037             }
3038             if (const Fortran::semantics::Symbol *wholeSymbol =
3039                     Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(
3040                         *expr))
3041               if (Fortran::semantics::IsOptional(*wholeSymbol)) {
3042                 ExtValue actualArg = gen(*expr);
3043                 mlir::Value actualArgBase = fir::getBase(actualArg);
3044                 if (!actualArgBase.getType().isa<fir::BoxType>())
3045                   return actualArg;
3046                 // Do not read wholeSymbol descriptor that may be a nullptr in
3047                 // case wholeSymbol is absent.
3048                 // Absent descriptor cannot be read. To avoid any issue in
3049                 // copy-in/copy-out, and when retrieving the address/length
3050                 // create an descriptor pointing to a null address here if the
3051                 // fir.box is absent.
3052                 mlir::Value isPresent = builder.create<fir::IsPresentOp>(
3053                     loc, builder.getI1Type(), actualArgBase);
3054                 mlir::Type boxType = actualArgBase.getType();
3055                 mlir::Value emptyBox = fir::factory::createUnallocatedBox(
3056                     builder, loc, boxType, llvm::None);
3057                 auto safeToReadBox = builder.create<mlir::arith::SelectOp>(
3058                     loc, isPresent, actualArgBase, emptyBox);
3059                 fir::ExtendedValue safeToReadExv =
3060                     fir::substBase(actualArg, safeToReadBox);
3061                 if (actualIsSimplyContiguous)
3062                   return safeToReadExv;
3063                 return genCopyIn(safeToReadExv, arg, copyOutPairs, isPresent);
3064               }
3065             // Fall through: The actual argument can safely be
3066             // copied-in/copied-out without any care if needed.
3067           }
3068           if (actualArgIsVariable && expr->Rank() > 0) {
3069             ExtValue box = genBoxArg(*expr);
3070             if (!actualIsSimplyContiguous)
3071               return genCopyIn(box, arg, copyOutPairs,
3072                                /*restrictCopyAtRuntime=*/llvm::None);
3073             // Contiguous: just use the box we created above!
3074             // This gets "unboxed" below, if needed.
3075             return box;
3076           }
3077           // Actual argument is a non optional/non pointer/non allocatable
3078           // scalar.
3079           if (actualArgIsVariable)
3080             return genExtAddr(*expr);
3081           // Actual argument is not a variable. Make sure a variable address is
3082           // not passed.
3083           return genTempExtAddr(*expr);
3084         }();
3085         // Scalar and contiguous expressions may be lowered to a fir.box,
3086         // either to account for potential polymorphism, or because lowering
3087         // did not account for some contiguity hints.
3088         // Here, polymorphism does not matter (an entity of the declared type
3089         // is passed, not one of the dynamic type), and the expr is known to
3090         // be simply contiguous, so it is safe to unbox it and pass the
3091         // address without making a copy.
3092         argAddr = readIfBoxValue(argAddr);
3093 
3094         if (arg.passBy == PassBy::BaseAddress) {
3095           caller.placeInput(arg, fir::getBase(argAddr));
3096         } else {
3097           assert(arg.passBy == PassBy::BoxChar);
3098           auto helper = fir::factory::CharacterExprHelper{builder, loc};
3099           auto boxChar = argAddr.match(
3100               [&](const fir::CharBoxValue &x) { return helper.createEmbox(x); },
3101               [&](const fir::CharArrayBoxValue &x) {
3102                 return helper.createEmbox(x);
3103               },
3104               [&](const auto &x) -> mlir::Value {
3105                 // Fortran allows an actual argument of a completely different
3106                 // type to be passed to a procedure expecting a CHARACTER in the
3107                 // dummy argument position. When this happens, the data pointer
3108                 // argument is simply assumed to point to CHARACTER data and the
3109                 // LEN argument used is garbage. Simulate this behavior by
3110                 // free-casting the base address to be a !fir.char reference and
3111                 // setting the LEN argument to undefined. What could go wrong?
3112                 auto dataPtr = fir::getBase(x);
3113                 assert(!dataPtr.getType().template isa<fir::BoxType>());
3114                 return builder.convertWithSemantics(
3115                     loc, argTy, dataPtr,
3116                     /*allowCharacterConversion=*/true);
3117               });
3118           caller.placeInput(arg, boxChar);
3119         }
3120       } else if (arg.passBy == PassBy::Box) {
3121         // Before lowering to an address, handle the allocatable/pointer actual
3122         // argument to optional fir.box dummy. It is legal to pass
3123         // unallocated/disassociated entity to an optional. In this case, an
3124         // absent fir.box must be created instead of a fir.box with a null value
3125         // (Fortran 2018 15.5.2.12 point 1).
3126         if (arg.isOptional() && Fortran::evaluate::IsAllocatableOrPointerObject(
3127                                     *expr, converter.getFoldingContext())) {
3128           // Note that passing an absent allocatable to a non-allocatable
3129           // optional dummy argument is illegal (15.5.2.12 point 3 (8)). So
3130           // nothing has to be done to generate an absent argument in this case,
3131           // and it is OK to unconditionally read the mutable box here.
3132           fir::MutableBoxValue mutableBox = genMutableBoxValue(*expr);
3133           mlir::Value isAllocated =
3134               fir::factory::genIsAllocatedOrAssociatedTest(builder, loc,
3135                                                            mutableBox);
3136           auto absent = builder.create<fir::AbsentOp>(loc, argTy);
3137           /// For now, assume it is not OK to pass the allocatable/pointer
3138           /// descriptor to a non pointer/allocatable dummy. That is a strict
3139           /// interpretation of 18.3.6 point 4 that stipulates the descriptor
3140           /// has the dummy attributes in BIND(C) contexts.
3141           mlir::Value box = builder.createBox(
3142               loc, fir::factory::genMutableBoxRead(builder, loc, mutableBox));
3143           // Need the box types to be exactly similar for the selectOp.
3144           mlir::Value convertedBox = builder.createConvert(loc, argTy, box);
3145           caller.placeInput(arg, builder.create<mlir::arith::SelectOp>(
3146                                      loc, isAllocated, convertedBox, absent));
3147         } else {
3148           // Make sure a variable address is only passed if the expression is
3149           // actually a variable.
3150           mlir::Value box =
3151               actualArgIsVariable
3152                   ? builder.createBox(loc, genBoxArg(*expr))
3153                   : builder.createBox(getLoc(), genTempExtAddr(*expr));
3154           caller.placeInput(arg, box);
3155         }
3156       } else if (arg.passBy == PassBy::AddressAndLength) {
3157         ExtValue argRef = genExtAddr(*expr);
3158         caller.placeAddressAndLengthInput(arg, fir::getBase(argRef),
3159                                           fir::getLen(argRef));
3160       } else if (arg.passBy == PassBy::CharProcTuple) {
3161         ExtValue argRef = genExtAddr(*expr);
3162         mlir::Value tuple = createBoxProcCharTuple(
3163             converter, argTy, fir::getBase(argRef), fir::getLen(argRef));
3164         caller.placeInput(arg, tuple);
3165       } else {
3166         TODO(loc, "pass by value in non elemental function call");
3167       }
3168     }
3169 
3170     ExtValue result = genCallOpAndResult(caller, callSiteType, resultType);
3171 
3172     // Sync pointers and allocatables that may have been modified during the
3173     // call.
3174     for (const auto &mutableBox : mutableModifiedByCall)
3175       fir::factory::syncMutableBoxFromIRBox(builder, loc, mutableBox);
3176     // Handle case where result was passed as argument
3177 
3178     // Copy-out temps that were created for non contiguous variable arguments if
3179     // needed.
3180     for (const auto &copyOutPair : copyOutPairs)
3181       genCopyOut(copyOutPair);
3182 
3183     return result;
3184   }
3185 
3186   template <typename A>
3187   ExtValue genval(const Fortran::evaluate::FunctionRef<A> &funcRef) {
3188     ExtValue result = genFunctionRef(funcRef);
3189     if (result.rank() == 0 && fir::isa_ref_type(fir::getBase(result).getType()))
3190       return genLoad(result);
3191     return result;
3192   }
3193 
3194   ExtValue genval(const Fortran::evaluate::ProcedureRef &procRef) {
3195     llvm::Optional<mlir::Type> resTy;
3196     if (procRef.hasAlternateReturns())
3197       resTy = builder.getIndexType();
3198     return genProcedureRef(procRef, resTy);
3199   }
3200 
3201   template <typename A>
3202   bool isScalar(const A &x) {
3203     return x.Rank() == 0;
3204   }
3205 
3206   /// Helper to detect Transformational function reference.
3207   template <typename T>
3208   bool isTransformationalRef(const T &) {
3209     return false;
3210   }
3211   template <typename T>
3212   bool isTransformationalRef(const Fortran::evaluate::FunctionRef<T> &funcRef) {
3213     return !funcRef.IsElemental() && funcRef.Rank();
3214   }
3215   template <typename T>
3216   bool isTransformationalRef(Fortran::evaluate::Expr<T> expr) {
3217     return std::visit([&](const auto &e) { return isTransformationalRef(e); },
3218                       expr.u);
3219   }
3220 
3221   template <typename A>
3222   ExtValue asArray(const A &x) {
3223     return Fortran::lower::createSomeArrayTempValue(converter, toEvExpr(x),
3224                                                     symMap, stmtCtx);
3225   }
3226 
3227   /// Lower an array value as an argument. This argument can be passed as a box
3228   /// value, so it may be possible to avoid making a temporary.
3229   template <typename A>
3230   ExtValue asArrayArg(const Fortran::evaluate::Expr<A> &x) {
3231     return std::visit([&](const auto &e) { return asArrayArg(e, x); }, x.u);
3232   }
3233   template <typename A, typename B>
3234   ExtValue asArrayArg(const Fortran::evaluate::Expr<A> &x, const B &y) {
3235     return std::visit([&](const auto &e) { return asArrayArg(e, y); }, x.u);
3236   }
3237   template <typename A, typename B>
3238   ExtValue asArrayArg(const Fortran::evaluate::Designator<A> &, const B &x) {
3239     // Designator is being passed as an argument to a procedure. Lower the
3240     // expression to a boxed value.
3241     auto someExpr = toEvExpr(x);
3242     return Fortran::lower::createBoxValue(getLoc(), converter, someExpr, symMap,
3243                                           stmtCtx);
3244   }
3245   template <typename A, typename B>
3246   ExtValue asArrayArg(const A &, const B &x) {
3247     // If the expression to pass as an argument is not a designator, then create
3248     // an array temp.
3249     return asArray(x);
3250   }
3251 
3252   template <typename A>
3253   ExtValue gen(const Fortran::evaluate::Expr<A> &x) {
3254     // Whole array symbols or components, and results of transformational
3255     // functions already have a storage and the scalar expression lowering path
3256     // is used to not create a new temporary storage.
3257     if (isScalar(x) ||
3258         Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(x) ||
3259         isTransformationalRef(x))
3260       return std::visit([&](const auto &e) { return genref(e); }, x.u);
3261     if (useBoxArg)
3262       return asArrayArg(x);
3263     return asArray(x);
3264   }
3265   template <typename A>
3266   ExtValue genval(const Fortran::evaluate::Expr<A> &x) {
3267     if (isScalar(x) || Fortran::evaluate::UnwrapWholeSymbolDataRef(x) ||
3268         inInitializer)
3269       return std::visit([&](const auto &e) { return genval(e); }, x.u);
3270     return asArray(x);
3271   }
3272 
3273   template <int KIND>
3274   ExtValue genval(const Fortran::evaluate::Expr<Fortran::evaluate::Type<
3275                       Fortran::common::TypeCategory::Logical, KIND>> &exp) {
3276     return std::visit([&](const auto &e) { return genval(e); }, exp.u);
3277   }
3278 
3279   using RefSet =
3280       std::tuple<Fortran::evaluate::ComplexPart, Fortran::evaluate::Substring,
3281                  Fortran::evaluate::DataRef, Fortran::evaluate::Component,
3282                  Fortran::evaluate::ArrayRef, Fortran::evaluate::CoarrayRef,
3283                  Fortran::semantics::SymbolRef>;
3284   template <typename A>
3285   static constexpr bool inRefSet = Fortran::common::HasMember<A, RefSet>;
3286 
3287   template <typename A, typename = std::enable_if_t<inRefSet<A>>>
3288   ExtValue genref(const A &a) {
3289     return gen(a);
3290   }
3291   template <typename A>
3292   ExtValue genref(const A &a) {
3293     if (inInitializer) {
3294       // Initialization expressions can never allocate memory.
3295       return genval(a);
3296     }
3297     mlir::Type storageType = converter.genType(toEvExpr(a));
3298     return placeScalarValueInMemory(builder, getLoc(), genval(a), storageType);
3299   }
3300 
3301   template <typename A, template <typename> typename T,
3302             typename B = std::decay_t<T<A>>,
3303             std::enable_if_t<
3304                 std::is_same_v<B, Fortran::evaluate::Expr<A>> ||
3305                     std::is_same_v<B, Fortran::evaluate::Designator<A>> ||
3306                     std::is_same_v<B, Fortran::evaluate::FunctionRef<A>>,
3307                 bool> = true>
3308   ExtValue genref(const T<A> &x) {
3309     return gen(x);
3310   }
3311 
3312 private:
3313   mlir::Location location;
3314   Fortran::lower::AbstractConverter &converter;
3315   fir::FirOpBuilder &builder;
3316   Fortran::lower::StatementContext &stmtCtx;
3317   Fortran::lower::SymMap &symMap;
3318   InitializerData *inInitializer = nullptr;
3319   bool useBoxArg = false; // expression lowered as argument
3320 };
3321 } // namespace
3322 
3323 // Helper for changing the semantics in a given context. Preserves the current
3324 // semantics which is resumed when the "push" goes out of scope.
3325 #define PushSemantics(PushVal)                                                 \
3326   [[maybe_unused]] auto pushSemanticsLocalVariable##__LINE__ =                 \
3327       Fortran::common::ScopedSet(semant, PushVal);
3328 
3329 static bool isAdjustedArrayElementType(mlir::Type t) {
3330   return fir::isa_char(t) || fir::isa_derived(t) || t.isa<fir::SequenceType>();
3331 }
3332 static bool elementTypeWasAdjusted(mlir::Type t) {
3333   if (auto ty = t.dyn_cast<fir::ReferenceType>())
3334     return isAdjustedArrayElementType(ty.getEleTy());
3335   return false;
3336 }
3337 static mlir::Type adjustedArrayElementType(mlir::Type t) {
3338   return isAdjustedArrayElementType(t) ? fir::ReferenceType::get(t) : t;
3339 }
3340 
3341 /// Helper to generate calls to scalar user defined assignment procedures.
3342 static void genScalarUserDefinedAssignmentCall(fir::FirOpBuilder &builder,
3343                                                mlir::Location loc,
3344                                                mlir::func::FuncOp func,
3345                                                const fir::ExtendedValue &lhs,
3346                                                const fir::ExtendedValue &rhs) {
3347   auto prepareUserDefinedArg =
3348       [](fir::FirOpBuilder &builder, mlir::Location loc,
3349          const fir::ExtendedValue &value, mlir::Type argType) -> mlir::Value {
3350     if (argType.isa<fir::BoxCharType>()) {
3351       const fir::CharBoxValue *charBox = value.getCharBox();
3352       assert(charBox && "argument type mismatch in elemental user assignment");
3353       return fir::factory::CharacterExprHelper{builder, loc}.createEmbox(
3354           *charBox);
3355     }
3356     if (argType.isa<fir::BoxType>()) {
3357       mlir::Value box = builder.createBox(loc, value);
3358       return builder.createConvert(loc, argType, box);
3359     }
3360     // Simple pass by address.
3361     mlir::Type argBaseType = fir::unwrapRefType(argType);
3362     assert(!fir::hasDynamicSize(argBaseType));
3363     mlir::Value from = fir::getBase(value);
3364     if (argBaseType != fir::unwrapRefType(from.getType())) {
3365       // With logicals, it is possible that from is i1 here.
3366       if (fir::isa_ref_type(from.getType()))
3367         from = builder.create<fir::LoadOp>(loc, from);
3368       from = builder.createConvert(loc, argBaseType, from);
3369     }
3370     if (!fir::isa_ref_type(from.getType())) {
3371       mlir::Value temp = builder.createTemporary(loc, argBaseType);
3372       builder.create<fir::StoreOp>(loc, from, temp);
3373       from = temp;
3374     }
3375     return builder.createConvert(loc, argType, from);
3376   };
3377   assert(func.getNumArguments() == 2);
3378   mlir::Type lhsType = func.getFunctionType().getInput(0);
3379   mlir::Type rhsType = func.getFunctionType().getInput(1);
3380   mlir::Value lhsArg = prepareUserDefinedArg(builder, loc, lhs, lhsType);
3381   mlir::Value rhsArg = prepareUserDefinedArg(builder, loc, rhs, rhsType);
3382   builder.create<fir::CallOp>(loc, func, mlir::ValueRange{lhsArg, rhsArg});
3383 }
3384 
3385 /// Convert the result of a fir.array_modify to an ExtendedValue given the
3386 /// related fir.array_load.
3387 static fir::ExtendedValue arrayModifyToExv(fir::FirOpBuilder &builder,
3388                                            mlir::Location loc,
3389                                            fir::ArrayLoadOp load,
3390                                            mlir::Value elementAddr) {
3391   mlir::Type eleTy = fir::unwrapPassByRefType(elementAddr.getType());
3392   if (fir::isa_char(eleTy)) {
3393     auto len = fir::factory::CharacterExprHelper{builder, loc}.getLength(
3394         load.getMemref());
3395     if (!len) {
3396       assert(load.getTypeparams().size() == 1 &&
3397              "length must be in array_load");
3398       len = load.getTypeparams()[0];
3399     }
3400     return fir::CharBoxValue{elementAddr, len};
3401   }
3402   return elementAddr;
3403 }
3404 
3405 //===----------------------------------------------------------------------===//
3406 //
3407 // Lowering of scalar expressions in an explicit iteration space context.
3408 //
3409 //===----------------------------------------------------------------------===//
3410 
3411 // Shared code for creating a copy of a derived type element. This function is
3412 // called from a continuation.
3413 inline static fir::ArrayAmendOp
3414 createDerivedArrayAmend(mlir::Location loc, fir::ArrayLoadOp destLoad,
3415                         fir::FirOpBuilder &builder, fir::ArrayAccessOp destAcc,
3416                         const fir::ExtendedValue &elementExv, mlir::Type eleTy,
3417                         mlir::Value innerArg) {
3418   if (destLoad.getTypeparams().empty()) {
3419     fir::factory::genRecordAssignment(builder, loc, destAcc, elementExv);
3420   } else {
3421     auto boxTy = fir::BoxType::get(eleTy);
3422     auto toBox = builder.create<fir::EmboxOp>(loc, boxTy, destAcc.getResult(),
3423                                               mlir::Value{}, mlir::Value{},
3424                                               destLoad.getTypeparams());
3425     auto fromBox = builder.create<fir::EmboxOp>(
3426         loc, boxTy, fir::getBase(elementExv), mlir::Value{}, mlir::Value{},
3427         destLoad.getTypeparams());
3428     fir::factory::genRecordAssignment(builder, loc, fir::BoxValue(toBox),
3429                                       fir::BoxValue(fromBox));
3430   }
3431   return builder.create<fir::ArrayAmendOp>(loc, innerArg.getType(), innerArg,
3432                                            destAcc);
3433 }
3434 
3435 inline static fir::ArrayAmendOp
3436 createCharArrayAmend(mlir::Location loc, fir::FirOpBuilder &builder,
3437                      fir::ArrayAccessOp dstOp, mlir::Value &dstLen,
3438                      const fir::ExtendedValue &srcExv, mlir::Value innerArg,
3439                      llvm::ArrayRef<mlir::Value> bounds) {
3440   fir::CharBoxValue dstChar(dstOp, dstLen);
3441   fir::factory::CharacterExprHelper helper{builder, loc};
3442   if (!bounds.empty()) {
3443     dstChar = helper.createSubstring(dstChar, bounds);
3444     fir::factory::genCharacterCopy(fir::getBase(srcExv), fir::getLen(srcExv),
3445                                    dstChar.getAddr(), dstChar.getLen(), builder,
3446                                    loc);
3447     // Update the LEN to the substring's LEN.
3448     dstLen = dstChar.getLen();
3449   }
3450   // For a CHARACTER, we generate the element assignment loops inline.
3451   helper.createAssign(fir::ExtendedValue{dstChar}, srcExv);
3452   // Mark this array element as amended.
3453   mlir::Type ty = innerArg.getType();
3454   auto amend = builder.create<fir::ArrayAmendOp>(loc, ty, innerArg, dstOp);
3455   return amend;
3456 }
3457 
3458 /// Build an ExtendedValue from a fir.array<?x...?xT> without actually setting
3459 /// the actual extents and lengths. This is only to allow their propagation as
3460 /// ExtendedValue without triggering verifier failures when propagating
3461 /// character/arrays as unboxed values. Only the base of the resulting
3462 /// ExtendedValue should be used, it is undefined to use the length or extents
3463 /// of the extended value returned,
3464 inline static fir::ExtendedValue
3465 convertToArrayBoxValue(mlir::Location loc, fir::FirOpBuilder &builder,
3466                        mlir::Value val, mlir::Value len) {
3467   mlir::Type ty = fir::unwrapRefType(val.getType());
3468   mlir::IndexType idxTy = builder.getIndexType();
3469   auto seqTy = ty.cast<fir::SequenceType>();
3470   auto undef = builder.create<fir::UndefOp>(loc, idxTy);
3471   llvm::SmallVector<mlir::Value> extents(seqTy.getDimension(), undef);
3472   if (fir::isa_char(seqTy.getEleTy()))
3473     return fir::CharArrayBoxValue(val, len ? len : undef, extents);
3474   return fir::ArrayBoxValue(val, extents);
3475 }
3476 
3477 //===----------------------------------------------------------------------===//
3478 //
3479 // Lowering of array expressions.
3480 //
3481 //===----------------------------------------------------------------------===//
3482 
3483 namespace {
3484 class ArrayExprLowering {
3485   using ExtValue = fir::ExtendedValue;
3486 
3487   /// Structure to keep track of lowered array operands in the
3488   /// array expression. Useful to later deduce the shape of the
3489   /// array expression.
3490   struct ArrayOperand {
3491     /// Array base (can be a fir.box).
3492     mlir::Value memref;
3493     /// ShapeOp, ShapeShiftOp or ShiftOp
3494     mlir::Value shape;
3495     /// SliceOp
3496     mlir::Value slice;
3497     /// Can this operand be absent ?
3498     bool mayBeAbsent = false;
3499   };
3500 
3501   using ImplicitSubscripts = Fortran::lower::details::ImplicitSubscripts;
3502   using PathComponent = Fortran::lower::PathComponent;
3503 
3504   /// Active iteration space.
3505   using IterationSpace = Fortran::lower::IterationSpace;
3506   using IterSpace = const Fortran::lower::IterationSpace &;
3507 
3508   /// Current continuation. Function that will generate IR for a single
3509   /// iteration of the pending iterative loop structure.
3510   using CC = Fortran::lower::GenerateElementalArrayFunc;
3511 
3512   /// Projection continuation. Function that will project one iteration space
3513   /// into another.
3514   using PC = std::function<IterationSpace(IterSpace)>;
3515   using ArrayBaseTy =
3516       std::variant<std::monostate, const Fortran::evaluate::ArrayRef *,
3517                    const Fortran::evaluate::DataRef *>;
3518   using ComponentPath = Fortran::lower::ComponentPath;
3519 
3520 public:
3521   //===--------------------------------------------------------------------===//
3522   // Regular array assignment
3523   //===--------------------------------------------------------------------===//
3524 
3525   /// Entry point for array assignments. Both the left-hand and right-hand sides
3526   /// can either be ExtendedValue or evaluate::Expr.
3527   template <typename TL, typename TR>
3528   static void lowerArrayAssignment(Fortran::lower::AbstractConverter &converter,
3529                                    Fortran::lower::SymMap &symMap,
3530                                    Fortran::lower::StatementContext &stmtCtx,
3531                                    const TL &lhs, const TR &rhs) {
3532     ArrayExprLowering ael(converter, stmtCtx, symMap,
3533                           ConstituentSemantics::CopyInCopyOut);
3534     ael.lowerArrayAssignment(lhs, rhs);
3535   }
3536 
3537   template <typename TL, typename TR>
3538   void lowerArrayAssignment(const TL &lhs, const TR &rhs) {
3539     mlir::Location loc = getLoc();
3540     /// Here the target subspace is not necessarily contiguous. The ArrayUpdate
3541     /// continuation is implicitly returned in `ccStoreToDest` and the ArrayLoad
3542     /// in `destination`.
3543     PushSemantics(ConstituentSemantics::ProjectedCopyInCopyOut);
3544     ccStoreToDest = genarr(lhs);
3545     determineShapeOfDest(lhs);
3546     semant = ConstituentSemantics::RefTransparent;
3547     ExtValue exv = lowerArrayExpression(rhs);
3548     if (explicitSpaceIsActive()) {
3549       explicitSpace->finalizeContext();
3550       builder.create<fir::ResultOp>(loc, fir::getBase(exv));
3551     } else {
3552       builder.create<fir::ArrayMergeStoreOp>(
3553           loc, destination, fir::getBase(exv), destination.getMemref(),
3554           destination.getSlice(), destination.getTypeparams());
3555     }
3556   }
3557 
3558   //===--------------------------------------------------------------------===//
3559   // WHERE array assignment, FORALL assignment, and FORALL+WHERE array
3560   // assignment
3561   //===--------------------------------------------------------------------===//
3562 
3563   /// Entry point for array assignment when the iteration space is explicitly
3564   /// defined (Fortran's FORALL) with or without masks, and/or the implied
3565   /// iteration space involves masks (Fortran's WHERE). Both contexts (explicit
3566   /// space and implicit space with masks) may be present.
3567   static void lowerAnyMaskedArrayAssignment(
3568       Fortran::lower::AbstractConverter &converter,
3569       Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
3570       const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
3571       Fortran::lower::ExplicitIterSpace &explicitSpace,
3572       Fortran::lower::ImplicitIterSpace &implicitSpace) {
3573     if (explicitSpace.isActive() && lhs.Rank() == 0) {
3574       // Scalar assignment expression in a FORALL context.
3575       ArrayExprLowering ael(converter, stmtCtx, symMap,
3576                             ConstituentSemantics::RefTransparent,
3577                             &explicitSpace, &implicitSpace);
3578       ael.lowerScalarAssignment(lhs, rhs);
3579       return;
3580     }
3581     // Array assignment expression in a FORALL and/or WHERE context.
3582     ArrayExprLowering ael(converter, stmtCtx, symMap,
3583                           ConstituentSemantics::CopyInCopyOut, &explicitSpace,
3584                           &implicitSpace);
3585     ael.lowerArrayAssignment(lhs, rhs);
3586   }
3587 
3588   //===--------------------------------------------------------------------===//
3589   // Array assignment to array of pointer box values.
3590   //===--------------------------------------------------------------------===//
3591 
3592   /// Entry point for assignment to pointer in an array of pointers.
3593   static void lowerArrayOfPointerAssignment(
3594       Fortran::lower::AbstractConverter &converter,
3595       Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
3596       const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
3597       Fortran::lower::ExplicitIterSpace &explicitSpace,
3598       Fortran::lower::ImplicitIterSpace &implicitSpace,
3599       const llvm::SmallVector<mlir::Value> &lbounds,
3600       llvm::Optional<llvm::SmallVector<mlir::Value>> ubounds) {
3601     ArrayExprLowering ael(converter, stmtCtx, symMap,
3602                           ConstituentSemantics::CopyInCopyOut, &explicitSpace,
3603                           &implicitSpace);
3604     ael.lowerArrayOfPointerAssignment(lhs, rhs, lbounds, ubounds);
3605   }
3606 
3607   /// Scalar pointer assignment in an explicit iteration space.
3608   ///
3609   /// Pointers may be bound to targets in a FORALL context. This is a scalar
3610   /// assignment in the sense there is never an implied iteration space, even if
3611   /// the pointer is to a target with non-zero rank. Since the pointer
3612   /// assignment must appear in a FORALL construct, correctness may require that
3613   /// the array of pointers follow copy-in/copy-out semantics. The pointer
3614   /// assignment may include a bounds-spec (lower bounds), a bounds-remapping
3615   /// (lower and upper bounds), or neither.
3616   void lowerArrayOfPointerAssignment(
3617       const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
3618       const llvm::SmallVector<mlir::Value> &lbounds,
3619       llvm::Optional<llvm::SmallVector<mlir::Value>> ubounds) {
3620     setPointerAssignmentBounds(lbounds, ubounds);
3621     if (rhs.Rank() == 0 ||
3622         (Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(rhs) &&
3623          Fortran::evaluate::IsAllocatableOrPointerObject(
3624              rhs, converter.getFoldingContext()))) {
3625       lowerScalarAssignment(lhs, rhs);
3626       return;
3627     }
3628     TODO(getLoc(),
3629          "auto boxing of a ranked expression on RHS for pointer assignment");
3630   }
3631 
3632   //===--------------------------------------------------------------------===//
3633   // Array assignment to allocatable array
3634   //===--------------------------------------------------------------------===//
3635 
3636   /// Entry point for assignment to allocatable array.
3637   static void lowerAllocatableArrayAssignment(
3638       Fortran::lower::AbstractConverter &converter,
3639       Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
3640       const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
3641       Fortran::lower::ExplicitIterSpace &explicitSpace,
3642       Fortran::lower::ImplicitIterSpace &implicitSpace) {
3643     ArrayExprLowering ael(converter, stmtCtx, symMap,
3644                           ConstituentSemantics::CopyInCopyOut, &explicitSpace,
3645                           &implicitSpace);
3646     ael.lowerAllocatableArrayAssignment(lhs, rhs);
3647   }
3648 
3649   /// Assignment to allocatable array.
3650   ///
3651   /// The semantics are reverse that of a "regular" array assignment. The rhs
3652   /// defines the iteration space of the computation and the lhs is
3653   /// resized/reallocated to fit if necessary.
3654   void lowerAllocatableArrayAssignment(const Fortran::lower::SomeExpr &lhs,
3655                                        const Fortran::lower::SomeExpr &rhs) {
3656     // With assignment to allocatable, we want to lower the rhs first and use
3657     // its shape to determine if we need to reallocate, etc.
3658     mlir::Location loc = getLoc();
3659     // FIXME: If the lhs is in an explicit iteration space, the assignment may
3660     // be to an array of allocatable arrays rather than a single allocatable
3661     // array.
3662     fir::MutableBoxValue mutableBox =
3663         Fortran::lower::createMutableBox(loc, converter, lhs, symMap);
3664     mlir::Type resultTy = converter.genType(rhs);
3665     if (rhs.Rank() > 0)
3666       determineShapeOfDest(rhs);
3667     auto rhsCC = [&]() {
3668       PushSemantics(ConstituentSemantics::RefTransparent);
3669       return genarr(rhs);
3670     }();
3671 
3672     llvm::SmallVector<mlir::Value> lengthParams;
3673     // Currently no safe way to gather length from rhs (at least for
3674     // character, it cannot be taken from array_loads since it may be
3675     // changed by concatenations).
3676     if ((mutableBox.isCharacter() && !mutableBox.hasNonDeferredLenParams()) ||
3677         mutableBox.isDerivedWithLenParameters())
3678       TODO(loc, "gather rhs length parameters in assignment to allocatable");
3679 
3680     // The allocatable must take lower bounds from the expr if it is
3681     // reallocated and the right hand side is not a scalar.
3682     const bool takeLboundsIfRealloc = rhs.Rank() > 0;
3683     llvm::SmallVector<mlir::Value> lbounds;
3684     // When the reallocated LHS takes its lower bounds from the RHS,
3685     // they will be non default only if the RHS is a whole array
3686     // variable. Otherwise, lbounds is left empty and default lower bounds
3687     // will be used.
3688     if (takeLboundsIfRealloc &&
3689         Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(rhs)) {
3690       assert(arrayOperands.size() == 1 &&
3691              "lbounds can only come from one array");
3692       auto lbs = fir::factory::getOrigins(arrayOperands[0].shape);
3693       lbounds.append(lbs.begin(), lbs.end());
3694     }
3695     fir::factory::MutableBoxReallocation realloc =
3696         fir::factory::genReallocIfNeeded(builder, loc, mutableBox, destShape,
3697                                          lengthParams);
3698     // Create ArrayLoad for the mutable box and save it into `destination`.
3699     PushSemantics(ConstituentSemantics::ProjectedCopyInCopyOut);
3700     ccStoreToDest = genarr(realloc.newValue);
3701     // If the rhs is scalar, get shape from the allocatable ArrayLoad.
3702     if (destShape.empty())
3703       destShape = getShape(destination);
3704     // Finish lowering the loop nest.
3705     assert(destination && "destination must have been set");
3706     ExtValue exv = lowerArrayExpression(rhsCC, resultTy);
3707     if (explicitSpaceIsActive()) {
3708       explicitSpace->finalizeContext();
3709       builder.create<fir::ResultOp>(loc, fir::getBase(exv));
3710     } else {
3711       builder.create<fir::ArrayMergeStoreOp>(
3712           loc, destination, fir::getBase(exv), destination.getMemref(),
3713           destination.getSlice(), destination.getTypeparams());
3714     }
3715     fir::factory::finalizeRealloc(builder, loc, mutableBox, lbounds,
3716                                   takeLboundsIfRealloc, realloc);
3717   }
3718 
3719   /// Entry point for when an array expression appears in a context where the
3720   /// result must be boxed. (BoxValue semantics.)
3721   static ExtValue
3722   lowerBoxedArrayExpression(Fortran::lower::AbstractConverter &converter,
3723                             Fortran::lower::SymMap &symMap,
3724                             Fortran::lower::StatementContext &stmtCtx,
3725                             const Fortran::lower::SomeExpr &expr) {
3726     ArrayExprLowering ael{converter, stmtCtx, symMap,
3727                           ConstituentSemantics::BoxValue};
3728     return ael.lowerBoxedArrayExpr(expr);
3729   }
3730 
3731   ExtValue lowerBoxedArrayExpr(const Fortran::lower::SomeExpr &exp) {
3732     PushSemantics(ConstituentSemantics::BoxValue);
3733     return std::visit(
3734         [&](const auto &e) {
3735           auto f = genarr(e);
3736           ExtValue exv = f(IterationSpace{});
3737           if (fir::getBase(exv).getType().template isa<fir::BoxType>())
3738             return exv;
3739           fir::emitFatalError(getLoc(), "array must be emboxed");
3740         },
3741         exp.u);
3742   }
3743 
3744   /// Entry point into lowering an expression with rank. This entry point is for
3745   /// lowering a rhs expression, for example. (RefTransparent semantics.)
3746   static ExtValue
3747   lowerNewArrayExpression(Fortran::lower::AbstractConverter &converter,
3748                           Fortran::lower::SymMap &symMap,
3749                           Fortran::lower::StatementContext &stmtCtx,
3750                           const Fortran::lower::SomeExpr &expr) {
3751     ArrayExprLowering ael{converter, stmtCtx, symMap};
3752     ael.determineShapeOfDest(expr);
3753     ExtValue loopRes = ael.lowerArrayExpression(expr);
3754     fir::ArrayLoadOp dest = ael.destination;
3755     mlir::Value tempRes = dest.getMemref();
3756     fir::FirOpBuilder &builder = converter.getFirOpBuilder();
3757     mlir::Location loc = converter.getCurrentLocation();
3758     builder.create<fir::ArrayMergeStoreOp>(loc, dest, fir::getBase(loopRes),
3759                                            tempRes, dest.getSlice(),
3760                                            dest.getTypeparams());
3761 
3762     auto arrTy =
3763         fir::dyn_cast_ptrEleTy(tempRes.getType()).cast<fir::SequenceType>();
3764     if (auto charTy =
3765             arrTy.getEleTy().template dyn_cast<fir::CharacterType>()) {
3766       if (fir::characterWithDynamicLen(charTy))
3767         TODO(loc, "CHARACTER does not have constant LEN");
3768       mlir::Value len = builder.createIntegerConstant(
3769           loc, builder.getCharacterLengthType(), charTy.getLen());
3770       return fir::CharArrayBoxValue(tempRes, len, dest.getExtents());
3771     }
3772     return fir::ArrayBoxValue(tempRes, dest.getExtents());
3773   }
3774 
3775   static void lowerLazyArrayExpression(
3776       Fortran::lower::AbstractConverter &converter,
3777       Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
3778       const Fortran::lower::SomeExpr &expr, mlir::Value raggedHeader) {
3779     ArrayExprLowering ael(converter, stmtCtx, symMap);
3780     ael.lowerLazyArrayExpression(expr, raggedHeader);
3781   }
3782 
3783   /// Lower the expression \p expr into a buffer that is created on demand. The
3784   /// variable containing the pointer to the buffer is \p var and the variable
3785   /// containing the shape of the buffer is \p shapeBuffer.
3786   void lowerLazyArrayExpression(const Fortran::lower::SomeExpr &expr,
3787                                 mlir::Value header) {
3788     mlir::Location loc = getLoc();
3789     mlir::TupleType hdrTy = fir::factory::getRaggedArrayHeaderType(builder);
3790     mlir::IntegerType i32Ty = builder.getIntegerType(32);
3791 
3792     // Once the loop extents have been computed, which may require being inside
3793     // some explicit loops, lazily allocate the expression on the heap. The
3794     // following continuation creates the buffer as needed.
3795     ccPrelude = [=](llvm::ArrayRef<mlir::Value> shape) {
3796       mlir::IntegerType i64Ty = builder.getIntegerType(64);
3797       mlir::Value byteSize = builder.createIntegerConstant(loc, i64Ty, 1);
3798       fir::runtime::genRaggedArrayAllocate(
3799           loc, builder, header, /*asHeaders=*/false, byteSize, shape);
3800     };
3801 
3802     // Create a dummy array_load before the loop. We're storing to a lazy
3803     // temporary, so there will be no conflict and no copy-in. TODO: skip this
3804     // as there isn't any necessity for it.
3805     ccLoadDest = [=](llvm::ArrayRef<mlir::Value> shape) -> fir::ArrayLoadOp {
3806       mlir::Value one = builder.createIntegerConstant(loc, i32Ty, 1);
3807       auto var = builder.create<fir::CoordinateOp>(
3808           loc, builder.getRefType(hdrTy.getType(1)), header, one);
3809       auto load = builder.create<fir::LoadOp>(loc, var);
3810       mlir::Type eleTy =
3811           fir::unwrapSequenceType(fir::unwrapRefType(load.getType()));
3812       auto seqTy = fir::SequenceType::get(eleTy, shape.size());
3813       mlir::Value castTo =
3814           builder.createConvert(loc, fir::HeapType::get(seqTy), load);
3815       mlir::Value shapeOp = builder.genShape(loc, shape);
3816       return builder.create<fir::ArrayLoadOp>(
3817           loc, seqTy, castTo, shapeOp, /*slice=*/mlir::Value{}, llvm::None);
3818     };
3819     // Custom lowering of the element store to deal with the extra indirection
3820     // to the lazy allocated buffer.
3821     ccStoreToDest = [=](IterSpace iters) {
3822       mlir::Value one = builder.createIntegerConstant(loc, i32Ty, 1);
3823       auto var = builder.create<fir::CoordinateOp>(
3824           loc, builder.getRefType(hdrTy.getType(1)), header, one);
3825       auto load = builder.create<fir::LoadOp>(loc, var);
3826       mlir::Type eleTy =
3827           fir::unwrapSequenceType(fir::unwrapRefType(load.getType()));
3828       auto seqTy = fir::SequenceType::get(eleTy, iters.iterVec().size());
3829       auto toTy = fir::HeapType::get(seqTy);
3830       mlir::Value castTo = builder.createConvert(loc, toTy, load);
3831       mlir::Value shape = builder.genShape(loc, genIterationShape());
3832       llvm::SmallVector<mlir::Value> indices = fir::factory::originateIndices(
3833           loc, builder, castTo.getType(), shape, iters.iterVec());
3834       auto eleAddr = builder.create<fir::ArrayCoorOp>(
3835           loc, builder.getRefType(eleTy), castTo, shape,
3836           /*slice=*/mlir::Value{}, indices, destination.getTypeparams());
3837       mlir::Value eleVal =
3838           builder.createConvert(loc, eleTy, iters.getElement());
3839       builder.create<fir::StoreOp>(loc, eleVal, eleAddr);
3840       return iters.innerArgument();
3841     };
3842 
3843     // Lower the array expression now. Clean-up any temps that may have
3844     // been generated when lowering `expr` right after the lowered value
3845     // was stored to the ragged array temporary. The local temps will not
3846     // be needed afterwards.
3847     stmtCtx.pushScope();
3848     [[maybe_unused]] ExtValue loopRes = lowerArrayExpression(expr);
3849     stmtCtx.finalize(/*popScope=*/true);
3850     assert(fir::getBase(loopRes));
3851   }
3852 
3853   static void
3854   lowerElementalUserAssignment(Fortran::lower::AbstractConverter &converter,
3855                                Fortran::lower::SymMap &symMap,
3856                                Fortran::lower::StatementContext &stmtCtx,
3857                                Fortran::lower::ExplicitIterSpace &explicitSpace,
3858                                Fortran::lower::ImplicitIterSpace &implicitSpace,
3859                                const Fortran::evaluate::ProcedureRef &procRef) {
3860     ArrayExprLowering ael(converter, stmtCtx, symMap,
3861                           ConstituentSemantics::CustomCopyInCopyOut,
3862                           &explicitSpace, &implicitSpace);
3863     assert(procRef.arguments().size() == 2);
3864     const auto *lhs = procRef.arguments()[0].value().UnwrapExpr();
3865     const auto *rhs = procRef.arguments()[1].value().UnwrapExpr();
3866     assert(lhs && rhs &&
3867            "user defined assignment arguments must be expressions");
3868     mlir::func::FuncOp func =
3869         Fortran::lower::CallerInterface(procRef, converter).getFuncOp();
3870     ael.lowerElementalUserAssignment(func, *lhs, *rhs);
3871   }
3872 
3873   void lowerElementalUserAssignment(mlir::func::FuncOp userAssignment,
3874                                     const Fortran::lower::SomeExpr &lhs,
3875                                     const Fortran::lower::SomeExpr &rhs) {
3876     mlir::Location loc = getLoc();
3877     PushSemantics(ConstituentSemantics::CustomCopyInCopyOut);
3878     auto genArrayModify = genarr(lhs);
3879     ccStoreToDest = [=](IterSpace iters) -> ExtValue {
3880       auto modifiedArray = genArrayModify(iters);
3881       auto arrayModify = mlir::dyn_cast_or_null<fir::ArrayModifyOp>(
3882           fir::getBase(modifiedArray).getDefiningOp());
3883       assert(arrayModify && "must be created by ArrayModifyOp");
3884       fir::ExtendedValue lhs =
3885           arrayModifyToExv(builder, loc, destination, arrayModify.getResult(0));
3886       genScalarUserDefinedAssignmentCall(builder, loc, userAssignment, lhs,
3887                                          iters.elementExv());
3888       return modifiedArray;
3889     };
3890     determineShapeOfDest(lhs);
3891     semant = ConstituentSemantics::RefTransparent;
3892     auto exv = lowerArrayExpression(rhs);
3893     if (explicitSpaceIsActive()) {
3894       explicitSpace->finalizeContext();
3895       builder.create<fir::ResultOp>(loc, fir::getBase(exv));
3896     } else {
3897       builder.create<fir::ArrayMergeStoreOp>(
3898           loc, destination, fir::getBase(exv), destination.getMemref(),
3899           destination.getSlice(), destination.getTypeparams());
3900     }
3901   }
3902 
3903   /// Lower an elemental subroutine call with at least one array argument.
3904   /// An elemental subroutine is an exception and does not have copy-in/copy-out
3905   /// semantics. See 15.8.3.
3906   /// Do NOT use this for user defined assignments.
3907   static void
3908   lowerElementalSubroutine(Fortran::lower::AbstractConverter &converter,
3909                            Fortran::lower::SymMap &symMap,
3910                            Fortran::lower::StatementContext &stmtCtx,
3911                            const Fortran::lower::SomeExpr &call) {
3912     ArrayExprLowering ael(converter, stmtCtx, symMap,
3913                           ConstituentSemantics::RefTransparent);
3914     ael.lowerElementalSubroutine(call);
3915   }
3916 
3917   // TODO: See the comment in genarr(const Fortran::lower::Parentheses<T>&).
3918   // This is skipping generation of copy-in/copy-out code for analysis that is
3919   // required when arguments are in parentheses.
3920   void lowerElementalSubroutine(const Fortran::lower::SomeExpr &call) {
3921     auto f = genarr(call);
3922     llvm::SmallVector<mlir::Value> shape = genIterationShape();
3923     auto [iterSpace, insPt] = genImplicitLoops(shape, /*innerArg=*/{});
3924     f(iterSpace);
3925     finalizeElementCtx();
3926     builder.restoreInsertionPoint(insPt);
3927   }
3928 
3929   ExtValue lowerScalarAssignment(const Fortran::lower::SomeExpr &lhs,
3930                                  const Fortran::lower::SomeExpr &rhs) {
3931     PushSemantics(ConstituentSemantics::RefTransparent);
3932     // 1) Lower the rhs expression with array_fetch op(s).
3933     IterationSpace iters;
3934     iters.setElement(genarr(rhs)(iters));
3935     // 2) Lower the lhs expression to an array_update.
3936     semant = ConstituentSemantics::ProjectedCopyInCopyOut;
3937     auto lexv = genarr(lhs)(iters);
3938     // 3) Finalize the inner context.
3939     explicitSpace->finalizeContext();
3940     // 4) Thread the array value updated forward. Note: the lhs might be
3941     // ill-formed (performing scalar assignment in an array context),
3942     // in which case there is no array to thread.
3943     auto createResult = [&](auto op) {
3944       mlir::Value oldInnerArg = op.getSequence();
3945       std::size_t offset = explicitSpace->argPosition(oldInnerArg);
3946       explicitSpace->setInnerArg(offset, fir::getBase(lexv));
3947       builder.create<fir::ResultOp>(getLoc(), fir::getBase(lexv));
3948     };
3949     llvm::TypeSwitch<mlir::Operation *, void>(
3950         fir::getBase(lexv).getDefiningOp())
3951         .Case([&](fir::ArrayUpdateOp op) { createResult(op); })
3952         .Case([&](fir::ArrayAmendOp op) { createResult(op); })
3953         .Case([&](fir::ArrayModifyOp op) { createResult(op); })
3954         .Default([&](mlir::Operation *) {});
3955     return lexv;
3956   }
3957 
3958   static ExtValue lowerScalarUserAssignment(
3959       Fortran::lower::AbstractConverter &converter,
3960       Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
3961       Fortran::lower::ExplicitIterSpace &explicitIterSpace,
3962       mlir::func::FuncOp userAssignmentFunction,
3963       const Fortran::lower::SomeExpr &lhs,
3964       const Fortran::lower::SomeExpr &rhs) {
3965     Fortran::lower::ImplicitIterSpace implicit;
3966     ArrayExprLowering ael(converter, stmtCtx, symMap,
3967                           ConstituentSemantics::RefTransparent,
3968                           &explicitIterSpace, &implicit);
3969     return ael.lowerScalarUserAssignment(userAssignmentFunction, lhs, rhs);
3970   }
3971 
3972   ExtValue lowerScalarUserAssignment(mlir::func::FuncOp userAssignment,
3973                                      const Fortran::lower::SomeExpr &lhs,
3974                                      const Fortran::lower::SomeExpr &rhs) {
3975     mlir::Location loc = getLoc();
3976     if (rhs.Rank() > 0)
3977       TODO(loc, "user-defined elemental assigment from expression with rank");
3978     // 1) Lower the rhs expression with array_fetch op(s).
3979     IterationSpace iters;
3980     iters.setElement(genarr(rhs)(iters));
3981     fir::ExtendedValue elementalExv = iters.elementExv();
3982     // 2) Lower the lhs expression to an array_modify.
3983     semant = ConstituentSemantics::CustomCopyInCopyOut;
3984     auto lexv = genarr(lhs)(iters);
3985     bool isIllFormedLHS = false;
3986     // 3) Insert the call
3987     if (auto modifyOp = mlir::dyn_cast<fir::ArrayModifyOp>(
3988             fir::getBase(lexv).getDefiningOp())) {
3989       mlir::Value oldInnerArg = modifyOp.getSequence();
3990       std::size_t offset = explicitSpace->argPosition(oldInnerArg);
3991       explicitSpace->setInnerArg(offset, fir::getBase(lexv));
3992       fir::ExtendedValue exv = arrayModifyToExv(
3993           builder, loc, explicitSpace->getLhsLoad(0).getValue(),
3994           modifyOp.getResult(0));
3995       genScalarUserDefinedAssignmentCall(builder, loc, userAssignment, exv,
3996                                          elementalExv);
3997     } else {
3998       // LHS is ill formed, it is a scalar with no references to FORALL
3999       // subscripts, so there is actually no array assignment here. The user
4000       // code is probably bad, but still insert user assignment call since it
4001       // was not rejected by semantics (a warning was emitted).
4002       isIllFormedLHS = true;
4003       genScalarUserDefinedAssignmentCall(builder, getLoc(), userAssignment,
4004                                          lexv, elementalExv);
4005     }
4006     // 4) Finalize the inner context.
4007     explicitSpace->finalizeContext();
4008     // 5). Thread the array value updated forward.
4009     if (!isIllFormedLHS)
4010       builder.create<fir::ResultOp>(getLoc(), fir::getBase(lexv));
4011     return lexv;
4012   }
4013 
4014 private:
4015   void determineShapeOfDest(const fir::ExtendedValue &lhs) {
4016     destShape = fir::factory::getExtents(getLoc(), builder, lhs);
4017   }
4018 
4019   void determineShapeOfDest(const Fortran::lower::SomeExpr &lhs) {
4020     if (!destShape.empty())
4021       return;
4022     if (explicitSpaceIsActive() && determineShapeWithSlice(lhs))
4023       return;
4024     mlir::Type idxTy = builder.getIndexType();
4025     mlir::Location loc = getLoc();
4026     if (std::optional<Fortran::evaluate::ConstantSubscripts> constantShape =
4027             Fortran::evaluate::GetConstantExtents(converter.getFoldingContext(),
4028                                                   lhs))
4029       for (Fortran::common::ConstantSubscript extent : *constantShape)
4030         destShape.push_back(builder.createIntegerConstant(loc, idxTy, extent));
4031   }
4032 
4033   bool genShapeFromDataRef(const Fortran::semantics::Symbol &x) {
4034     return false;
4035   }
4036   bool genShapeFromDataRef(const Fortran::evaluate::CoarrayRef &) {
4037     TODO(getLoc(), "coarray ref");
4038     return false;
4039   }
4040   bool genShapeFromDataRef(const Fortran::evaluate::Component &x) {
4041     return x.base().Rank() > 0 ? genShapeFromDataRef(x.base()) : false;
4042   }
4043   bool genShapeFromDataRef(const Fortran::evaluate::ArrayRef &x) {
4044     if (x.Rank() == 0)
4045       return false;
4046     if (x.base().Rank() > 0)
4047       if (genShapeFromDataRef(x.base()))
4048         return true;
4049     // x has rank and x.base did not produce a shape.
4050     ExtValue exv = x.base().IsSymbol() ? asScalarRef(getFirstSym(x.base()))
4051                                        : asScalarRef(x.base().GetComponent());
4052     mlir::Location loc = getLoc();
4053     mlir::IndexType idxTy = builder.getIndexType();
4054     llvm::SmallVector<mlir::Value> definedShape =
4055         fir::factory::getExtents(loc, builder, exv);
4056     mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
4057     for (auto ss : llvm::enumerate(x.subscript())) {
4058       std::visit(Fortran::common::visitors{
4059                      [&](const Fortran::evaluate::Triplet &trip) {
4060                        // For a subscript of triple notation, we compute the
4061                        // range of this dimension of the iteration space.
4062                        auto lo = [&]() {
4063                          if (auto optLo = trip.lower())
4064                            return fir::getBase(asScalar(*optLo));
4065                          return getLBound(exv, ss.index(), one);
4066                        }();
4067                        auto hi = [&]() {
4068                          if (auto optHi = trip.upper())
4069                            return fir::getBase(asScalar(*optHi));
4070                          return getUBound(exv, ss.index(), one);
4071                        }();
4072                        auto step = builder.createConvert(
4073                            loc, idxTy, fir::getBase(asScalar(trip.stride())));
4074                        auto extent = builder.genExtentFromTriplet(loc, lo, hi,
4075                                                                   step, idxTy);
4076                        destShape.push_back(extent);
4077                      },
4078                      [&](auto) {}},
4079                  ss.value().u);
4080     }
4081     return true;
4082   }
4083   bool genShapeFromDataRef(const Fortran::evaluate::NamedEntity &x) {
4084     if (x.IsSymbol())
4085       return genShapeFromDataRef(getFirstSym(x));
4086     return genShapeFromDataRef(x.GetComponent());
4087   }
4088   bool genShapeFromDataRef(const Fortran::evaluate::DataRef &x) {
4089     return std::visit([&](const auto &v) { return genShapeFromDataRef(v); },
4090                       x.u);
4091   }
4092 
4093   /// When in an explicit space, the ranked component must be evaluated to
4094   /// determine the actual number of iterations when slicing triples are
4095   /// present. Lower these expressions here.
4096   bool determineShapeWithSlice(const Fortran::lower::SomeExpr &lhs) {
4097     LLVM_DEBUG(Fortran::lower::DumpEvaluateExpr::dump(
4098         llvm::dbgs() << "determine shape of:\n", lhs));
4099     // FIXME: We may not want to use ExtractDataRef here since it doesn't deal
4100     // with substrings, etc.
4101     std::optional<Fortran::evaluate::DataRef> dref =
4102         Fortran::evaluate::ExtractDataRef(lhs);
4103     return dref.has_value() ? genShapeFromDataRef(*dref) : false;
4104   }
4105 
4106   /// CHARACTER and derived type elements are treated as memory references. The
4107   /// numeric types are treated as values.
4108   static mlir::Type adjustedArraySubtype(mlir::Type ty,
4109                                          mlir::ValueRange indices) {
4110     mlir::Type pathTy = fir::applyPathToType(ty, indices);
4111     assert(pathTy && "indices failed to apply to type");
4112     return adjustedArrayElementType(pathTy);
4113   }
4114 
4115   ExtValue lowerArrayExpression(const Fortran::lower::SomeExpr &exp) {
4116     mlir::Type resTy = converter.genType(exp);
4117     return std::visit(
4118         [&](const auto &e) { return lowerArrayExpression(genarr(e), resTy); },
4119         exp.u);
4120   }
4121   ExtValue lowerArrayExpression(const ExtValue &exv) {
4122     assert(!explicitSpace);
4123     mlir::Type resTy = fir::unwrapPassByRefType(fir::getBase(exv).getType());
4124     return lowerArrayExpression(genarr(exv), resTy);
4125   }
4126 
4127   void populateBounds(llvm::SmallVectorImpl<mlir::Value> &bounds,
4128                       const Fortran::evaluate::Substring *substring) {
4129     if (!substring)
4130       return;
4131     bounds.push_back(fir::getBase(asScalar(substring->lower())));
4132     if (auto upper = substring->upper())
4133       bounds.push_back(fir::getBase(asScalar(*upper)));
4134   }
4135 
4136   /// Convert the original value, \p origVal, to type \p eleTy. When in a
4137   /// pointer assignment context, generate an appropriate `fir.rebox` for
4138   /// dealing with any bounds parameters on the pointer assignment.
4139   mlir::Value convertElementForUpdate(mlir::Location loc, mlir::Type eleTy,
4140                                       mlir::Value origVal) {
4141     mlir::Value val = builder.createConvert(loc, eleTy, origVal);
4142     if (isBoundsSpec()) {
4143       auto lbs = lbounds.getValue();
4144       if (lbs.size() > 0) {
4145         // Rebox the value with user-specified shift.
4146         auto shiftTy = fir::ShiftType::get(eleTy.getContext(), lbs.size());
4147         mlir::Value shiftOp = builder.create<fir::ShiftOp>(loc, shiftTy, lbs);
4148         val = builder.create<fir::ReboxOp>(loc, eleTy, val, shiftOp,
4149                                            mlir::Value{});
4150       }
4151     } else if (isBoundsRemap()) {
4152       auto lbs = lbounds.getValue();
4153       if (lbs.size() > 0) {
4154         // Rebox the value with user-specified shift and shape.
4155         auto shapeShiftArgs = flatZip(lbs, ubounds.getValue());
4156         auto shapeTy = fir::ShapeShiftType::get(eleTy.getContext(), lbs.size());
4157         mlir::Value shapeShift =
4158             builder.create<fir::ShapeShiftOp>(loc, shapeTy, shapeShiftArgs);
4159         val = builder.create<fir::ReboxOp>(loc, eleTy, val, shapeShift,
4160                                            mlir::Value{});
4161       }
4162     }
4163     return val;
4164   }
4165 
4166   /// Default store to destination implementation.
4167   /// This implements the default case, which is to assign the value in
4168   /// `iters.element` into the destination array, `iters.innerArgument`. Handles
4169   /// by value and by reference assignment.
4170   CC defaultStoreToDestination(const Fortran::evaluate::Substring *substring) {
4171     return [=](IterSpace iterSpace) -> ExtValue {
4172       mlir::Location loc = getLoc();
4173       mlir::Value innerArg = iterSpace.innerArgument();
4174       fir::ExtendedValue exv = iterSpace.elementExv();
4175       mlir::Type arrTy = innerArg.getType();
4176       mlir::Type eleTy = fir::applyPathToType(arrTy, iterSpace.iterVec());
4177       if (isAdjustedArrayElementType(eleTy)) {
4178         // The elemental update is in the memref domain. Under this semantics,
4179         // we must always copy the computed new element from its location in
4180         // memory into the destination array.
4181         mlir::Type resRefTy = builder.getRefType(eleTy);
4182         // Get a reference to the array element to be amended.
4183         auto arrayOp = builder.create<fir::ArrayAccessOp>(
4184             loc, resRefTy, innerArg, iterSpace.iterVec(),
4185             destination.getTypeparams());
4186         if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) {
4187           llvm::SmallVector<mlir::Value> substringBounds;
4188           populateBounds(substringBounds, substring);
4189           mlir::Value dstLen = fir::factory::genLenOfCharacter(
4190               builder, loc, destination, iterSpace.iterVec(), substringBounds);
4191           fir::ArrayAmendOp amend = createCharArrayAmend(
4192               loc, builder, arrayOp, dstLen, exv, innerArg, substringBounds);
4193           return abstractArrayExtValue(amend, dstLen);
4194         }
4195         if (fir::isa_derived(eleTy)) {
4196           fir::ArrayAmendOp amend = createDerivedArrayAmend(
4197               loc, destination, builder, arrayOp, exv, eleTy, innerArg);
4198           return abstractArrayExtValue(amend /*FIXME: typeparams?*/);
4199         }
4200         assert(eleTy.isa<fir::SequenceType>() && "must be an array");
4201         TODO(loc, "array (as element) assignment");
4202       }
4203       // By value semantics. The element is being assigned by value.
4204       auto ele = convertElementForUpdate(loc, eleTy, fir::getBase(exv));
4205       auto update = builder.create<fir::ArrayUpdateOp>(
4206           loc, arrTy, innerArg, ele, iterSpace.iterVec(),
4207           destination.getTypeparams());
4208       return abstractArrayExtValue(update);
4209     };
4210   }
4211 
4212   /// For an elemental array expression.
4213   ///   1. Lower the scalars and array loads.
4214   ///   2. Create the iteration space.
4215   ///   3. Create the element-by-element computation in the loop.
4216   ///   4. Return the resulting array value.
4217   /// If no destination was set in the array context, a temporary of
4218   /// \p resultTy will be created to hold the evaluated expression.
4219   /// Otherwise, \p resultTy is ignored and the expression is evaluated
4220   /// in the destination. \p f is a continuation built from an
4221   /// evaluate::Expr or an ExtendedValue.
4222   ExtValue lowerArrayExpression(CC f, mlir::Type resultTy) {
4223     mlir::Location loc = getLoc();
4224     auto [iterSpace, insPt] = genIterSpace(resultTy);
4225     auto exv = f(iterSpace);
4226     iterSpace.setElement(std::move(exv));
4227     auto lambda = ccStoreToDest.hasValue()
4228                       ? ccStoreToDest.getValue()
4229                       : defaultStoreToDestination(/*substring=*/nullptr);
4230     mlir::Value updVal = fir::getBase(lambda(iterSpace));
4231     finalizeElementCtx();
4232     builder.create<fir::ResultOp>(loc, updVal);
4233     builder.restoreInsertionPoint(insPt);
4234     return abstractArrayExtValue(iterSpace.outerResult());
4235   }
4236 
4237   /// Compute the shape of a slice.
4238   llvm::SmallVector<mlir::Value> computeSliceShape(mlir::Value slice) {
4239     llvm::SmallVector<mlir::Value> slicedShape;
4240     auto slOp = mlir::cast<fir::SliceOp>(slice.getDefiningOp());
4241     mlir::Operation::operand_range triples = slOp.getTriples();
4242     mlir::IndexType idxTy = builder.getIndexType();
4243     mlir::Location loc = getLoc();
4244     for (unsigned i = 0, end = triples.size(); i < end; i += 3) {
4245       if (!mlir::isa_and_nonnull<fir::UndefOp>(
4246               triples[i + 1].getDefiningOp())) {
4247         // (..., lb:ub:step, ...) case:  extent = max((ub-lb+step)/step, 0)
4248         // See Fortran 2018 9.5.3.3.2 section for more details.
4249         mlir::Value res = builder.genExtentFromTriplet(
4250             loc, triples[i], triples[i + 1], triples[i + 2], idxTy);
4251         slicedShape.emplace_back(res);
4252       } else {
4253         // do nothing. `..., i, ...` case, so dimension is dropped.
4254       }
4255     }
4256     return slicedShape;
4257   }
4258 
4259   /// Get the shape from an ArrayOperand. The shape of the array is adjusted if
4260   /// the array was sliced.
4261   llvm::SmallVector<mlir::Value> getShape(ArrayOperand array) {
4262     if (array.slice)
4263       return computeSliceShape(array.slice);
4264     if (array.memref.getType().isa<fir::BoxType>())
4265       return fir::factory::readExtents(builder, getLoc(),
4266                                        fir::BoxValue{array.memref});
4267     return fir::factory::getExtents(array.shape);
4268   }
4269 
4270   /// Get the shape from an ArrayLoad.
4271   llvm::SmallVector<mlir::Value> getShape(fir::ArrayLoadOp arrayLoad) {
4272     return getShape(ArrayOperand{arrayLoad.getMemref(), arrayLoad.getShape(),
4273                                  arrayLoad.getSlice()});
4274   }
4275 
4276   /// Returns the first array operand that may not be absent. If all
4277   /// array operands may be absent, return the first one.
4278   const ArrayOperand &getInducingShapeArrayOperand() const {
4279     assert(!arrayOperands.empty());
4280     for (const ArrayOperand &op : arrayOperands)
4281       if (!op.mayBeAbsent)
4282         return op;
4283     // If all arrays operand appears in optional position, then none of them
4284     // is allowed to be absent as per 15.5.2.12 point 3. (6). Just pick the
4285     // first operands.
4286     // TODO: There is an opportunity to add a runtime check here that
4287     // this array is present as required.
4288     return arrayOperands[0];
4289   }
4290 
4291   /// Generate the shape of the iteration space over the array expression. The
4292   /// iteration space may be implicit, explicit, or both. If it is implied it is
4293   /// based on the destination and operand array loads, or an optional
4294   /// Fortran::evaluate::Shape from the front end. If the shape is explicit,
4295   /// this returns any implicit shape component, if it exists.
4296   llvm::SmallVector<mlir::Value> genIterationShape() {
4297     // Use the precomputed destination shape.
4298     if (!destShape.empty())
4299       return destShape;
4300     // Otherwise, use the destination's shape.
4301     if (destination)
4302       return getShape(destination);
4303     // Otherwise, use the first ArrayLoad operand shape.
4304     if (!arrayOperands.empty())
4305       return getShape(getInducingShapeArrayOperand());
4306     fir::emitFatalError(getLoc(),
4307                         "failed to compute the array expression shape");
4308   }
4309 
4310   bool explicitSpaceIsActive() const {
4311     return explicitSpace && explicitSpace->isActive();
4312   }
4313 
4314   bool implicitSpaceHasMasks() const {
4315     return implicitSpace && !implicitSpace->empty();
4316   }
4317 
4318   CC genMaskAccess(mlir::Value tmp, mlir::Value shape) {
4319     mlir::Location loc = getLoc();
4320     return [=, builder = &converter.getFirOpBuilder()](IterSpace iters) {
4321       mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(tmp.getType());
4322       auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy();
4323       mlir::Type eleRefTy = builder->getRefType(eleTy);
4324       mlir::IntegerType i1Ty = builder->getI1Type();
4325       // Adjust indices for any shift of the origin of the array.
4326       llvm::SmallVector<mlir::Value> indices = fir::factory::originateIndices(
4327           loc, *builder, tmp.getType(), shape, iters.iterVec());
4328       auto addr = builder->create<fir::ArrayCoorOp>(
4329           loc, eleRefTy, tmp, shape, /*slice=*/mlir::Value{}, indices,
4330           /*typeParams=*/llvm::None);
4331       auto load = builder->create<fir::LoadOp>(loc, addr);
4332       return builder->createConvert(loc, i1Ty, load);
4333     };
4334   }
4335 
4336   /// Construct the incremental instantiations of the ragged array structure.
4337   /// Rebind the lazy buffer variable, etc. as we go.
4338   template <bool withAllocation = false>
4339   mlir::Value prepareRaggedArrays(Fortran::lower::FrontEndExpr expr) {
4340     assert(explicitSpaceIsActive());
4341     mlir::Location loc = getLoc();
4342     mlir::TupleType raggedTy = fir::factory::getRaggedArrayHeaderType(builder);
4343     llvm::SmallVector<llvm::SmallVector<fir::DoLoopOp>> loopStack =
4344         explicitSpace->getLoopStack();
4345     const std::size_t depth = loopStack.size();
4346     mlir::IntegerType i64Ty = builder.getIntegerType(64);
4347     [[maybe_unused]] mlir::Value byteSize =
4348         builder.createIntegerConstant(loc, i64Ty, 1);
4349     mlir::Value header = implicitSpace->lookupMaskHeader(expr);
4350     for (std::remove_const_t<decltype(depth)> i = 0; i < depth; ++i) {
4351       auto insPt = builder.saveInsertionPoint();
4352       if (i < depth - 1)
4353         builder.setInsertionPoint(loopStack[i + 1][0]);
4354 
4355       // Compute and gather the extents.
4356       llvm::SmallVector<mlir::Value> extents;
4357       for (auto doLoop : loopStack[i])
4358         extents.push_back(builder.genExtentFromTriplet(
4359             loc, doLoop.getLowerBound(), doLoop.getUpperBound(),
4360             doLoop.getStep(), i64Ty));
4361       if constexpr (withAllocation) {
4362         fir::runtime::genRaggedArrayAllocate(
4363             loc, builder, header, /*asHeader=*/true, byteSize, extents);
4364       }
4365 
4366       // Compute the dynamic position into the header.
4367       llvm::SmallVector<mlir::Value> offsets;
4368       for (auto doLoop : loopStack[i]) {
4369         auto m = builder.create<mlir::arith::SubIOp>(
4370             loc, doLoop.getInductionVar(), doLoop.getLowerBound());
4371         auto n = builder.create<mlir::arith::DivSIOp>(loc, m, doLoop.getStep());
4372         mlir::Value one = builder.createIntegerConstant(loc, n.getType(), 1);
4373         offsets.push_back(builder.create<mlir::arith::AddIOp>(loc, n, one));
4374       }
4375       mlir::IntegerType i32Ty = builder.getIntegerType(32);
4376       mlir::Value uno = builder.createIntegerConstant(loc, i32Ty, 1);
4377       mlir::Type coorTy = builder.getRefType(raggedTy.getType(1));
4378       auto hdOff = builder.create<fir::CoordinateOp>(loc, coorTy, header, uno);
4379       auto toTy = fir::SequenceType::get(raggedTy, offsets.size());
4380       mlir::Type toRefTy = builder.getRefType(toTy);
4381       auto ldHdr = builder.create<fir::LoadOp>(loc, hdOff);
4382       mlir::Value hdArr = builder.createConvert(loc, toRefTy, ldHdr);
4383       auto shapeOp = builder.genShape(loc, extents);
4384       header = builder.create<fir::ArrayCoorOp>(
4385           loc, builder.getRefType(raggedTy), hdArr, shapeOp,
4386           /*slice=*/mlir::Value{}, offsets,
4387           /*typeparams=*/mlir::ValueRange{});
4388       auto hdrVar = builder.create<fir::CoordinateOp>(loc, coorTy, header, uno);
4389       auto inVar = builder.create<fir::LoadOp>(loc, hdrVar);
4390       mlir::Value two = builder.createIntegerConstant(loc, i32Ty, 2);
4391       mlir::Type coorTy2 = builder.getRefType(raggedTy.getType(2));
4392       auto hdrSh = builder.create<fir::CoordinateOp>(loc, coorTy2, header, two);
4393       auto shapePtr = builder.create<fir::LoadOp>(loc, hdrSh);
4394       // Replace the binding.
4395       implicitSpace->rebind(expr, genMaskAccess(inVar, shapePtr));
4396       if (i < depth - 1)
4397         builder.restoreInsertionPoint(insPt);
4398     }
4399     return header;
4400   }
4401 
4402   /// Lower mask expressions with implied iteration spaces from the variants of
4403   /// WHERE syntax. Since it is legal for mask expressions to have side-effects
4404   /// and modify values that will be used for the lhs, rhs, or both of
4405   /// subsequent assignments, the mask must be evaluated before the assignment
4406   /// is processed.
4407   /// Mask expressions are array expressions too.
4408   void genMasks() {
4409     // Lower the mask expressions, if any.
4410     if (implicitSpaceHasMasks()) {
4411       mlir::Location loc = getLoc();
4412       // Mask expressions are array expressions too.
4413       for (const auto *e : implicitSpace->getExprs())
4414         if (e && !implicitSpace->isLowered(e)) {
4415           if (mlir::Value var = implicitSpace->lookupMaskVariable(e)) {
4416             // Allocate the mask buffer lazily.
4417             assert(explicitSpaceIsActive());
4418             mlir::Value header =
4419                 prepareRaggedArrays</*withAllocations=*/true>(e);
4420             Fortran::lower::createLazyArrayTempValue(converter, *e, header,
4421                                                      symMap, stmtCtx);
4422             // Close the explicit loops.
4423             builder.create<fir::ResultOp>(loc, explicitSpace->getInnerArgs());
4424             builder.setInsertionPointAfter(explicitSpace->getOuterLoop());
4425             // Open a new copy of the explicit loop nest.
4426             explicitSpace->genLoopNest();
4427             continue;
4428           }
4429           fir::ExtendedValue tmp = Fortran::lower::createSomeArrayTempValue(
4430               converter, *e, symMap, stmtCtx);
4431           mlir::Value shape = builder.createShape(loc, tmp);
4432           implicitSpace->bind(e, genMaskAccess(fir::getBase(tmp), shape));
4433         }
4434 
4435       // Set buffer from the header.
4436       for (const auto *e : implicitSpace->getExprs()) {
4437         if (!e)
4438           continue;
4439         if (implicitSpace->lookupMaskVariable(e)) {
4440           // Index into the ragged buffer to retrieve cached results.
4441           const int rank = e->Rank();
4442           assert(destShape.empty() ||
4443                  static_cast<std::size_t>(rank) == destShape.size());
4444           mlir::Value header = prepareRaggedArrays(e);
4445           mlir::TupleType raggedTy =
4446               fir::factory::getRaggedArrayHeaderType(builder);
4447           mlir::IntegerType i32Ty = builder.getIntegerType(32);
4448           mlir::Value one = builder.createIntegerConstant(loc, i32Ty, 1);
4449           auto coor1 = builder.create<fir::CoordinateOp>(
4450               loc, builder.getRefType(raggedTy.getType(1)), header, one);
4451           auto db = builder.create<fir::LoadOp>(loc, coor1);
4452           mlir::Type eleTy =
4453               fir::unwrapSequenceType(fir::unwrapRefType(db.getType()));
4454           mlir::Type buffTy =
4455               builder.getRefType(fir::SequenceType::get(eleTy, rank));
4456           // Address of ragged buffer data.
4457           mlir::Value buff = builder.createConvert(loc, buffTy, db);
4458 
4459           mlir::Value two = builder.createIntegerConstant(loc, i32Ty, 2);
4460           auto coor2 = builder.create<fir::CoordinateOp>(
4461               loc, builder.getRefType(raggedTy.getType(2)), header, two);
4462           auto shBuff = builder.create<fir::LoadOp>(loc, coor2);
4463           mlir::IntegerType i64Ty = builder.getIntegerType(64);
4464           mlir::IndexType idxTy = builder.getIndexType();
4465           llvm::SmallVector<mlir::Value> extents;
4466           for (std::remove_const_t<decltype(rank)> i = 0; i < rank; ++i) {
4467             mlir::Value off = builder.createIntegerConstant(loc, i32Ty, i);
4468             auto coor = builder.create<fir::CoordinateOp>(
4469                 loc, builder.getRefType(i64Ty), shBuff, off);
4470             auto ldExt = builder.create<fir::LoadOp>(loc, coor);
4471             extents.push_back(builder.createConvert(loc, idxTy, ldExt));
4472           }
4473           if (destShape.empty())
4474             destShape = extents;
4475           // Construct shape of buffer.
4476           mlir::Value shapeOp = builder.genShape(loc, extents);
4477 
4478           // Replace binding with the local result.
4479           implicitSpace->rebind(e, genMaskAccess(buff, shapeOp));
4480         }
4481       }
4482     }
4483   }
4484 
4485   // FIXME: should take multiple inner arguments.
4486   std::pair<IterationSpace, mlir::OpBuilder::InsertPoint>
4487   genImplicitLoops(mlir::ValueRange shape, mlir::Value innerArg) {
4488     mlir::Location loc = getLoc();
4489     mlir::IndexType idxTy = builder.getIndexType();
4490     mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
4491     mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
4492     llvm::SmallVector<mlir::Value> loopUppers;
4493 
4494     // Convert any implied shape to closed interval form. The fir.do_loop will
4495     // run from 0 to `extent - 1` inclusive.
4496     for (auto extent : shape)
4497       loopUppers.push_back(
4498           builder.create<mlir::arith::SubIOp>(loc, extent, one));
4499 
4500     // Iteration space is created with outermost columns, innermost rows
4501     llvm::SmallVector<fir::DoLoopOp> loops;
4502 
4503     const std::size_t loopDepth = loopUppers.size();
4504     llvm::SmallVector<mlir::Value> ivars;
4505 
4506     for (auto i : llvm::enumerate(llvm::reverse(loopUppers))) {
4507       if (i.index() > 0) {
4508         assert(!loops.empty());
4509         builder.setInsertionPointToStart(loops.back().getBody());
4510       }
4511       fir::DoLoopOp loop;
4512       if (innerArg) {
4513         loop = builder.create<fir::DoLoopOp>(
4514             loc, zero, i.value(), one, isUnordered(),
4515             /*finalCount=*/false, mlir::ValueRange{innerArg});
4516         innerArg = loop.getRegionIterArgs().front();
4517         if (explicitSpaceIsActive())
4518           explicitSpace->setInnerArg(0, innerArg);
4519       } else {
4520         loop = builder.create<fir::DoLoopOp>(loc, zero, i.value(), one,
4521                                              isUnordered(),
4522                                              /*finalCount=*/false);
4523       }
4524       ivars.push_back(loop.getInductionVar());
4525       loops.push_back(loop);
4526     }
4527 
4528     if (innerArg)
4529       for (std::remove_const_t<decltype(loopDepth)> i = 0; i + 1 < loopDepth;
4530            ++i) {
4531         builder.setInsertionPointToEnd(loops[i].getBody());
4532         builder.create<fir::ResultOp>(loc, loops[i + 1].getResult(0));
4533       }
4534 
4535     // Move insertion point to the start of the innermost loop in the nest.
4536     builder.setInsertionPointToStart(loops.back().getBody());
4537     // Set `afterLoopNest` to just after the entire loop nest.
4538     auto currPt = builder.saveInsertionPoint();
4539     builder.setInsertionPointAfter(loops[0]);
4540     auto afterLoopNest = builder.saveInsertionPoint();
4541     builder.restoreInsertionPoint(currPt);
4542 
4543     // Put the implicit loop variables in row to column order to match FIR's
4544     // Ops. (The loops were constructed from outermost column to innermost
4545     // row.)
4546     mlir::Value outerRes = loops[0].getResult(0);
4547     return {IterationSpace(innerArg, outerRes, llvm::reverse(ivars)),
4548             afterLoopNest};
4549   }
4550 
4551   /// Build the iteration space into which the array expression will be lowered.
4552   /// The resultType is used to create a temporary, if needed.
4553   std::pair<IterationSpace, mlir::OpBuilder::InsertPoint>
4554   genIterSpace(mlir::Type resultType) {
4555     mlir::Location loc = getLoc();
4556     llvm::SmallVector<mlir::Value> shape = genIterationShape();
4557     if (!destination) {
4558       // Allocate storage for the result if it is not already provided.
4559       destination = createAndLoadSomeArrayTemp(resultType, shape);
4560     }
4561 
4562     // Generate the lazy mask allocation, if one was given.
4563     if (ccPrelude.hasValue())
4564       ccPrelude.getValue()(shape);
4565 
4566     // Now handle the implicit loops.
4567     mlir::Value inner = explicitSpaceIsActive()
4568                             ? explicitSpace->getInnerArgs().front()
4569                             : destination.getResult();
4570     auto [iters, afterLoopNest] = genImplicitLoops(shape, inner);
4571     mlir::Value innerArg = iters.innerArgument();
4572 
4573     // Generate the mask conditional structure, if there are masks. Unlike the
4574     // explicit masks, which are interleaved, these mask expression appear in
4575     // the innermost loop.
4576     if (implicitSpaceHasMasks()) {
4577       // Recover the cached condition from the mask buffer.
4578       auto genCond = [&](Fortran::lower::FrontEndExpr e, IterSpace iters) {
4579         return implicitSpace->getBoundClosure(e)(iters);
4580       };
4581 
4582       // Handle the negated conditions in topological order of the WHERE
4583       // clauses. See 10.2.3.2p4 as to why this control structure is produced.
4584       for (llvm::SmallVector<Fortran::lower::FrontEndExpr> maskExprs :
4585            implicitSpace->getMasks()) {
4586         const std::size_t size = maskExprs.size() - 1;
4587         auto genFalseBlock = [&](const auto *e, auto &&cond) {
4588           auto ifOp = builder.create<fir::IfOp>(
4589               loc, mlir::TypeRange{innerArg.getType()}, fir::getBase(cond),
4590               /*withElseRegion=*/true);
4591           builder.create<fir::ResultOp>(loc, ifOp.getResult(0));
4592           builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
4593           builder.create<fir::ResultOp>(loc, innerArg);
4594           builder.setInsertionPointToStart(&ifOp.getElseRegion().front());
4595         };
4596         auto genTrueBlock = [&](const auto *e, auto &&cond) {
4597           auto ifOp = builder.create<fir::IfOp>(
4598               loc, mlir::TypeRange{innerArg.getType()}, fir::getBase(cond),
4599               /*withElseRegion=*/true);
4600           builder.create<fir::ResultOp>(loc, ifOp.getResult(0));
4601           builder.setInsertionPointToStart(&ifOp.getElseRegion().front());
4602           builder.create<fir::ResultOp>(loc, innerArg);
4603           builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
4604         };
4605         for (std::remove_const_t<decltype(size)> i = 0; i < size; ++i)
4606           if (const auto *e = maskExprs[i])
4607             genFalseBlock(e, genCond(e, iters));
4608 
4609         // The last condition is either non-negated or unconditionally negated.
4610         if (const auto *e = maskExprs[size])
4611           genTrueBlock(e, genCond(e, iters));
4612       }
4613     }
4614 
4615     // We're ready to lower the body (an assignment statement) for this context
4616     // of loop nests at this point.
4617     return {iters, afterLoopNest};
4618   }
4619 
4620   fir::ArrayLoadOp
4621   createAndLoadSomeArrayTemp(mlir::Type type,
4622                              llvm::ArrayRef<mlir::Value> shape) {
4623     if (ccLoadDest.hasValue())
4624       return ccLoadDest.getValue()(shape);
4625     auto seqTy = type.dyn_cast<fir::SequenceType>();
4626     assert(seqTy && "must be an array");
4627     mlir::Location loc = getLoc();
4628     // TODO: Need to thread the length parameters here. For character, they may
4629     // differ from the operands length (e.g concatenation). So the array loads
4630     // type parameters are not enough.
4631     if (auto charTy = seqTy.getEleTy().dyn_cast<fir::CharacterType>())
4632       if (charTy.hasDynamicLen())
4633         TODO(loc, "character array expression temp with dynamic length");
4634     if (auto recTy = seqTy.getEleTy().dyn_cast<fir::RecordType>())
4635       if (recTy.getNumLenParams() > 0)
4636         TODO(loc, "derived type array expression temp with length parameters");
4637     mlir::Value temp = seqTy.hasConstantShape()
4638                            ? builder.create<fir::AllocMemOp>(loc, type)
4639                            : builder.create<fir::AllocMemOp>(
4640                                  loc, type, ".array.expr", llvm::None, shape);
4641     fir::FirOpBuilder *bldr = &converter.getFirOpBuilder();
4642     stmtCtx.attachCleanup(
4643         [bldr, loc, temp]() { bldr->create<fir::FreeMemOp>(loc, temp); });
4644     mlir::Value shapeOp = genShapeOp(shape);
4645     return builder.create<fir::ArrayLoadOp>(loc, seqTy, temp, shapeOp,
4646                                             /*slice=*/mlir::Value{},
4647                                             llvm::None);
4648   }
4649 
4650   static fir::ShapeOp genShapeOp(mlir::Location loc, fir::FirOpBuilder &builder,
4651                                  llvm::ArrayRef<mlir::Value> shape) {
4652     mlir::IndexType idxTy = builder.getIndexType();
4653     llvm::SmallVector<mlir::Value> idxShape;
4654     for (auto s : shape)
4655       idxShape.push_back(builder.createConvert(loc, idxTy, s));
4656     auto shapeTy = fir::ShapeType::get(builder.getContext(), idxShape.size());
4657     return builder.create<fir::ShapeOp>(loc, shapeTy, idxShape);
4658   }
4659 
4660   fir::ShapeOp genShapeOp(llvm::ArrayRef<mlir::Value> shape) {
4661     return genShapeOp(getLoc(), builder, shape);
4662   }
4663 
4664   //===--------------------------------------------------------------------===//
4665   // Expression traversal and lowering.
4666   //===--------------------------------------------------------------------===//
4667 
4668   /// Lower the expression, \p x, in a scalar context.
4669   template <typename A>
4670   ExtValue asScalar(const A &x) {
4671     return ScalarExprLowering{getLoc(), converter, symMap, stmtCtx}.genval(x);
4672   }
4673 
4674   /// Lower the expression, \p x, in a scalar context. If this is an explicit
4675   /// space, the expression may be scalar and refer to an array. We want to
4676   /// raise the array access to array operations in FIR to analyze potential
4677   /// conflicts even when the result is a scalar element.
4678   template <typename A>
4679   ExtValue asScalarArray(const A &x) {
4680     return explicitSpaceIsActive() && !isPointerAssignment()
4681                ? genarr(x)(IterationSpace{})
4682                : asScalar(x);
4683   }
4684 
4685   /// Lower the expression in a scalar context to a memory reference.
4686   template <typename A>
4687   ExtValue asScalarRef(const A &x) {
4688     return ScalarExprLowering{getLoc(), converter, symMap, stmtCtx}.gen(x);
4689   }
4690 
4691   /// Lower an expression without dereferencing any indirection that may be
4692   /// a nullptr (because this is an absent optional or unallocated/disassociated
4693   /// descriptor). The returned expression cannot be addressed directly, it is
4694   /// meant to inquire about its status before addressing the related entity.
4695   template <typename A>
4696   ExtValue asInquired(const A &x) {
4697     return ScalarExprLowering{getLoc(), converter, symMap, stmtCtx}
4698         .lowerIntrinsicArgumentAsInquired(x);
4699   }
4700 
4701   /// Some temporaries are allocated on an element-by-element basis during the
4702   /// array expression evaluation. Collect the cleanups here so the resources
4703   /// can be freed before the next loop iteration, avoiding memory leaks. etc.
4704   Fortran::lower::StatementContext &getElementCtx() {
4705     if (!elementCtx) {
4706       stmtCtx.pushScope();
4707       elementCtx = true;
4708     }
4709     return stmtCtx;
4710   }
4711 
4712   /// If there were temporaries created for this element evaluation, finalize
4713   /// and deallocate the resources now. This should be done just prior the the
4714   /// fir::ResultOp at the end of the innermost loop.
4715   void finalizeElementCtx() {
4716     if (elementCtx) {
4717       stmtCtx.finalize(/*popScope=*/true);
4718       elementCtx = false;
4719     }
4720   }
4721 
4722   /// Lower an elemental function array argument. This ensures array
4723   /// sub-expressions that are not variables and must be passed by address
4724   /// are lowered by value and placed in memory.
4725   template <typename A>
4726   CC genElementalArgument(const A &x) {
4727     // Ensure the returned element is in memory if this is what was requested.
4728     if ((semant == ConstituentSemantics::RefOpaque ||
4729          semant == ConstituentSemantics::DataAddr ||
4730          semant == ConstituentSemantics::ByValueArg)) {
4731       if (!Fortran::evaluate::IsVariable(x)) {
4732         PushSemantics(ConstituentSemantics::DataValue);
4733         CC cc = genarr(x);
4734         mlir::Location loc = getLoc();
4735         if (isParenthesizedVariable(x)) {
4736           // Parenthesised variables are lowered to a reference to the variable
4737           // storage. When passing it as an argument, a copy must be passed.
4738           return [=](IterSpace iters) -> ExtValue {
4739             return createInMemoryScalarCopy(builder, loc, cc(iters));
4740           };
4741         }
4742         mlir::Type storageType =
4743             fir::unwrapSequenceType(converter.genType(toEvExpr(x)));
4744         return [=](IterSpace iters) -> ExtValue {
4745           return placeScalarValueInMemory(builder, loc, cc(iters), storageType);
4746         };
4747       }
4748     }
4749     return genarr(x);
4750   }
4751 
4752   // A procedure reference to a Fortran elemental intrinsic procedure.
4753   CC genElementalIntrinsicProcRef(
4754       const Fortran::evaluate::ProcedureRef &procRef,
4755       llvm::Optional<mlir::Type> retTy,
4756       const Fortran::evaluate::SpecificIntrinsic &intrinsic) {
4757     llvm::SmallVector<CC> operands;
4758     llvm::StringRef name = intrinsic.name;
4759     const Fortran::lower::IntrinsicArgumentLoweringRules *argLowering =
4760         Fortran::lower::getIntrinsicArgumentLowering(name);
4761     mlir::Location loc = getLoc();
4762     if (Fortran::lower::intrinsicRequiresCustomOptionalHandling(
4763             procRef, intrinsic, converter)) {
4764       using CcPairT = std::pair<CC, llvm::Optional<mlir::Value>>;
4765       llvm::SmallVector<CcPairT> operands;
4766       auto prepareOptionalArg = [&](const Fortran::lower::SomeExpr &expr) {
4767         if (expr.Rank() == 0) {
4768           ExtValue optionalArg = this->asInquired(expr);
4769           mlir::Value isPresent =
4770               genActualIsPresentTest(builder, loc, optionalArg);
4771           operands.emplace_back(
4772               [=](IterSpace iters) -> ExtValue {
4773                 return genLoad(builder, loc, optionalArg);
4774               },
4775               isPresent);
4776         } else {
4777           auto [cc, isPresent, _] = this->genOptionalArrayFetch(expr);
4778           operands.emplace_back(cc, isPresent);
4779         }
4780       };
4781       auto prepareOtherArg = [&](const Fortran::lower::SomeExpr &expr) {
4782         PushSemantics(ConstituentSemantics::RefTransparent);
4783         operands.emplace_back(genElementalArgument(expr), llvm::None);
4784       };
4785       Fortran::lower::prepareCustomIntrinsicArgument(
4786           procRef, intrinsic, retTy, prepareOptionalArg, prepareOtherArg,
4787           converter);
4788 
4789       fir::FirOpBuilder *bldr = &converter.getFirOpBuilder();
4790       llvm::StringRef name = intrinsic.name;
4791       return [=](IterSpace iters) -> ExtValue {
4792         auto getArgument = [&](std::size_t i) -> ExtValue {
4793           return operands[i].first(iters);
4794         };
4795         auto isPresent = [&](std::size_t i) -> llvm::Optional<mlir::Value> {
4796           return operands[i].second;
4797         };
4798         return Fortran::lower::lowerCustomIntrinsic(
4799             *bldr, loc, name, retTy, isPresent, getArgument, operands.size(),
4800             getElementCtx());
4801       };
4802     }
4803     /// Otherwise, pre-lower arguments and use intrinsic lowering utility.
4804     for (const auto &[arg, dummy] :
4805          llvm::zip(procRef.arguments(),
4806                    intrinsic.characteristics.value().dummyArguments)) {
4807       const auto *expr =
4808           Fortran::evaluate::UnwrapExpr<Fortran::lower::SomeExpr>(arg);
4809       if (!expr) {
4810         // Absent optional.
4811         operands.emplace_back([=](IterSpace) { return mlir::Value{}; });
4812       } else if (!argLowering) {
4813         // No argument lowering instruction, lower by value.
4814         PushSemantics(ConstituentSemantics::RefTransparent);
4815         operands.emplace_back(genElementalArgument(*expr));
4816       } else {
4817         // Ad-hoc argument lowering handling.
4818         Fortran::lower::ArgLoweringRule argRules =
4819             Fortran::lower::lowerIntrinsicArgumentAs(getLoc(), *argLowering,
4820                                                      dummy.name);
4821         if (argRules.handleDynamicOptional &&
4822             Fortran::evaluate::MayBePassedAsAbsentOptional(
4823                 *expr, converter.getFoldingContext())) {
4824           // Currently, there is not elemental intrinsic that requires lowering
4825           // a potentially absent argument to something else than a value (apart
4826           // from character MAX/MIN that are handled elsewhere.)
4827           if (argRules.lowerAs != Fortran::lower::LowerIntrinsicArgAs::Value)
4828             TODO(loc, "lowering non trivial optional elemental intrinsic array "
4829                       "argument");
4830           PushSemantics(ConstituentSemantics::RefTransparent);
4831           operands.emplace_back(genarrForwardOptionalArgumentToCall(*expr));
4832           continue;
4833         }
4834         switch (argRules.lowerAs) {
4835         case Fortran::lower::LowerIntrinsicArgAs::Value: {
4836           PushSemantics(ConstituentSemantics::RefTransparent);
4837           operands.emplace_back(genElementalArgument(*expr));
4838         } break;
4839         case Fortran::lower::LowerIntrinsicArgAs::Addr: {
4840           // Note: assume does not have Fortran VALUE attribute semantics.
4841           PushSemantics(ConstituentSemantics::RefOpaque);
4842           operands.emplace_back(genElementalArgument(*expr));
4843         } break;
4844         case Fortran::lower::LowerIntrinsicArgAs::Box: {
4845           PushSemantics(ConstituentSemantics::RefOpaque);
4846           auto lambda = genElementalArgument(*expr);
4847           operands.emplace_back([=](IterSpace iters) {
4848             return builder.createBox(loc, lambda(iters));
4849           });
4850         } break;
4851         case Fortran::lower::LowerIntrinsicArgAs::Inquired:
4852           TODO(loc, "intrinsic function with inquired argument");
4853           break;
4854         }
4855       }
4856     }
4857 
4858     // Let the intrinsic library lower the intrinsic procedure call
4859     return [=](IterSpace iters) {
4860       llvm::SmallVector<ExtValue> args;
4861       for (const auto &cc : operands)
4862         args.push_back(cc(iters));
4863       return Fortran::lower::genIntrinsicCall(builder, loc, name, retTy, args,
4864                                               getElementCtx());
4865     };
4866   }
4867 
4868   /// Lower a procedure reference to a user-defined elemental procedure.
4869   CC genElementalUserDefinedProcRef(
4870       const Fortran::evaluate::ProcedureRef &procRef,
4871       llvm::Optional<mlir::Type> retTy) {
4872     using PassBy = Fortran::lower::CallerInterface::PassEntityBy;
4873 
4874     // 10.1.4 p5. Impure elemental procedures must be called in element order.
4875     if (const Fortran::semantics::Symbol *procSym = procRef.proc().GetSymbol())
4876       if (!Fortran::semantics::IsPureProcedure(*procSym))
4877         setUnordered(false);
4878 
4879     Fortran::lower::CallerInterface caller(procRef, converter);
4880     llvm::SmallVector<CC> operands;
4881     operands.reserve(caller.getPassedArguments().size());
4882     mlir::Location loc = getLoc();
4883     mlir::FunctionType callSiteType = caller.genFunctionType();
4884     for (const Fortran::lower::CallInterface<
4885              Fortran::lower::CallerInterface>::PassedEntity &arg :
4886          caller.getPassedArguments()) {
4887       // 15.8.3 p1. Elemental procedure with intent(out)/intent(inout)
4888       // arguments must be called in element order.
4889       if (arg.mayBeModifiedByCall())
4890         setUnordered(false);
4891       const auto *actual = arg.entity;
4892       mlir::Type argTy = callSiteType.getInput(arg.firArgument);
4893       if (!actual) {
4894         // Optional dummy argument for which there is no actual argument.
4895         auto absent = builder.create<fir::AbsentOp>(loc, argTy);
4896         operands.emplace_back([=](IterSpace) { return absent; });
4897         continue;
4898       }
4899       const auto *expr = actual->UnwrapExpr();
4900       if (!expr)
4901         TODO(loc, "assumed type actual argument lowering");
4902 
4903       LLVM_DEBUG(expr->AsFortran(llvm::dbgs()
4904                                  << "argument: " << arg.firArgument << " = [")
4905                  << "]\n");
4906       if (arg.isOptional() && Fortran::evaluate::MayBePassedAsAbsentOptional(
4907                                   *expr, converter.getFoldingContext()))
4908         TODO(loc,
4909              "passing dynamically optional argument to elemental procedures");
4910       switch (arg.passBy) {
4911       case PassBy::Value: {
4912         // True pass-by-value semantics.
4913         PushSemantics(ConstituentSemantics::RefTransparent);
4914         operands.emplace_back(genElementalArgument(*expr));
4915       } break;
4916       case PassBy::BaseAddressValueAttribute: {
4917         // VALUE attribute or pass-by-reference to a copy semantics. (byval*)
4918         if (isArray(*expr)) {
4919           PushSemantics(ConstituentSemantics::ByValueArg);
4920           operands.emplace_back(genElementalArgument(*expr));
4921         } else {
4922           // Store scalar value in a temp to fulfill VALUE attribute.
4923           mlir::Value val = fir::getBase(asScalar(*expr));
4924           mlir::Value temp = builder.createTemporary(
4925               loc, val.getType(),
4926               llvm::ArrayRef<mlir::NamedAttribute>{
4927                   Fortran::lower::getAdaptToByRefAttr(builder)});
4928           builder.create<fir::StoreOp>(loc, val, temp);
4929           operands.emplace_back(
4930               [=](IterSpace iters) -> ExtValue { return temp; });
4931         }
4932       } break;
4933       case PassBy::BaseAddress: {
4934         if (isArray(*expr)) {
4935           PushSemantics(ConstituentSemantics::RefOpaque);
4936           operands.emplace_back(genElementalArgument(*expr));
4937         } else {
4938           ExtValue exv = asScalarRef(*expr);
4939           operands.emplace_back([=](IterSpace iters) { return exv; });
4940         }
4941       } break;
4942       case PassBy::CharBoxValueAttribute: {
4943         if (isArray(*expr)) {
4944           PushSemantics(ConstituentSemantics::DataValue);
4945           auto lambda = genElementalArgument(*expr);
4946           operands.emplace_back([=](IterSpace iters) {
4947             return fir::factory::CharacterExprHelper{builder, loc}
4948                 .createTempFrom(lambda(iters));
4949           });
4950         } else {
4951           fir::factory::CharacterExprHelper helper(builder, loc);
4952           fir::CharBoxValue argVal = helper.createTempFrom(asScalarRef(*expr));
4953           operands.emplace_back(
4954               [=](IterSpace iters) -> ExtValue { return argVal; });
4955         }
4956       } break;
4957       case PassBy::BoxChar: {
4958         PushSemantics(ConstituentSemantics::RefOpaque);
4959         operands.emplace_back(genElementalArgument(*expr));
4960       } break;
4961       case PassBy::AddressAndLength:
4962         // PassBy::AddressAndLength is only used for character results. Results
4963         // are not handled here.
4964         fir::emitFatalError(
4965             loc, "unexpected PassBy::AddressAndLength in elemental call");
4966         break;
4967       case PassBy::CharProcTuple: {
4968         ExtValue argRef = asScalarRef(*expr);
4969         mlir::Value tuple = createBoxProcCharTuple(
4970             converter, argTy, fir::getBase(argRef), fir::getLen(argRef));
4971         operands.emplace_back(
4972             [=](IterSpace iters) -> ExtValue { return tuple; });
4973       } break;
4974       case PassBy::Box:
4975       case PassBy::MutableBox:
4976         // See C15100 and C15101
4977         fir::emitFatalError(loc, "cannot be POINTER, ALLOCATABLE");
4978       }
4979     }
4980 
4981     if (caller.getIfIndirectCallSymbol())
4982       fir::emitFatalError(loc, "cannot be indirect call");
4983 
4984     // The lambda is mutable so that `caller` copy can be modified inside it.
4985     return
4986         [=, caller = std::move(caller)](IterSpace iters) mutable -> ExtValue {
4987           for (const auto &[cc, argIface] :
4988                llvm::zip(operands, caller.getPassedArguments())) {
4989             auto exv = cc(iters);
4990             auto arg = exv.match(
4991                 [&](const fir::CharBoxValue &cb) -> mlir::Value {
4992                   return fir::factory::CharacterExprHelper{builder, loc}
4993                       .createEmbox(cb);
4994                 },
4995                 [&](const auto &) { return fir::getBase(exv); });
4996             caller.placeInput(argIface, arg);
4997           }
4998           return ScalarExprLowering{loc, converter, symMap, getElementCtx()}
4999               .genCallOpAndResult(caller, callSiteType, retTy);
5000         };
5001   }
5002 
5003   /// Generate a procedure reference. This code is shared for both functions and
5004   /// subroutines, the difference being reflected by `retTy`.
5005   CC genProcRef(const Fortran::evaluate::ProcedureRef &procRef,
5006                 llvm::Optional<mlir::Type> retTy) {
5007     mlir::Location loc = getLoc();
5008     if (procRef.IsElemental()) {
5009       if (const Fortran::evaluate::SpecificIntrinsic *intrin =
5010               procRef.proc().GetSpecificIntrinsic()) {
5011         // All elemental intrinsic functions are pure and cannot modify their
5012         // arguments. The only elemental subroutine, MVBITS has an Intent(inout)
5013         // argument. So for this last one, loops must be in element order
5014         // according to 15.8.3 p1.
5015         if (!retTy)
5016           setUnordered(false);
5017 
5018         // Elemental intrinsic call.
5019         // The intrinsic procedure is called once per element of the array.
5020         return genElementalIntrinsicProcRef(procRef, retTy, *intrin);
5021       }
5022       if (ScalarExprLowering::isStatementFunctionCall(procRef))
5023         fir::emitFatalError(loc, "statement function cannot be elemental");
5024 
5025       // Elemental call.
5026       // The procedure is called once per element of the array argument(s).
5027       return genElementalUserDefinedProcRef(procRef, retTy);
5028     }
5029 
5030     // Transformational call.
5031     // The procedure is called once and produces a value of rank > 0.
5032     if (const Fortran::evaluate::SpecificIntrinsic *intrinsic =
5033             procRef.proc().GetSpecificIntrinsic()) {
5034       if (explicitSpaceIsActive() && procRef.Rank() == 0) {
5035         // Elide any implicit loop iters.
5036         return [=, &procRef](IterSpace) {
5037           return ScalarExprLowering{loc, converter, symMap, stmtCtx}
5038               .genIntrinsicRef(procRef, *intrinsic, retTy);
5039         };
5040       }
5041       return genarr(
5042           ScalarExprLowering{loc, converter, symMap, stmtCtx}.genIntrinsicRef(
5043               procRef, *intrinsic, retTy));
5044     }
5045 
5046     if (explicitSpaceIsActive() && procRef.Rank() == 0) {
5047       // Elide any implicit loop iters.
5048       return [=, &procRef](IterSpace) {
5049         return ScalarExprLowering{loc, converter, symMap, stmtCtx}
5050             .genProcedureRef(procRef, retTy);
5051       };
5052     }
5053     // In the default case, the call can be hoisted out of the loop nest. Apply
5054     // the iterations to the result, which may be an array value.
5055     return genarr(
5056         ScalarExprLowering{loc, converter, symMap, stmtCtx}.genProcedureRef(
5057             procRef, retTy));
5058   }
5059 
5060   CC genarr(const Fortran::evaluate::ProcedureDesignator &) {
5061     TODO(getLoc(), "procedure designator");
5062   }
5063   CC genarr(const Fortran::evaluate::ProcedureRef &x) {
5064     if (x.hasAlternateReturns())
5065       fir::emitFatalError(getLoc(),
5066                           "array procedure reference with alt-return");
5067     return genProcRef(x, llvm::None);
5068   }
5069   template <typename A>
5070   CC genScalarAndForwardValue(const A &x) {
5071     ExtValue result = asScalar(x);
5072     return [=](IterSpace) { return result; };
5073   }
5074   template <typename A, typename = std::enable_if_t<Fortran::common::HasMember<
5075                             A, Fortran::evaluate::TypelessExpression>>>
5076   CC genarr(const A &x) {
5077     return genScalarAndForwardValue(x);
5078   }
5079 
5080   template <typename A>
5081   CC genarr(const Fortran::evaluate::Expr<A> &x) {
5082     LLVM_DEBUG(Fortran::lower::DumpEvaluateExpr::dump(llvm::dbgs(), x));
5083     if (isArray(x) || explicitSpaceIsActive() ||
5084         isElementalProcWithArrayArgs(x))
5085       return std::visit([&](const auto &e) { return genarr(e); }, x.u);
5086     return genScalarAndForwardValue(x);
5087   }
5088 
5089   // Converting a value of memory bound type requires creating a temp and
5090   // copying the value.
5091   static ExtValue convertAdjustedType(fir::FirOpBuilder &builder,
5092                                       mlir::Location loc, mlir::Type toType,
5093                                       const ExtValue &exv) {
5094     return exv.match(
5095         [&](const fir::CharBoxValue &cb) -> ExtValue {
5096           mlir::Value len = cb.getLen();
5097           auto mem =
5098               builder.create<fir::AllocaOp>(loc, toType, mlir::ValueRange{len});
5099           fir::CharBoxValue result(mem, len);
5100           fir::factory::CharacterExprHelper{builder, loc}.createAssign(
5101               ExtValue{result}, exv);
5102           return result;
5103         },
5104         [&](const auto &) -> ExtValue {
5105           fir::emitFatalError(loc, "convert on adjusted extended value");
5106         });
5107   }
5108   template <Fortran::common::TypeCategory TC1, int KIND,
5109             Fortran::common::TypeCategory TC2>
5110   CC genarr(const Fortran::evaluate::Convert<Fortran::evaluate::Type<TC1, KIND>,
5111                                              TC2> &x) {
5112     mlir::Location loc = getLoc();
5113     auto lambda = genarr(x.left());
5114     mlir::Type ty = converter.genType(TC1, KIND);
5115     return [=](IterSpace iters) -> ExtValue {
5116       auto exv = lambda(iters);
5117       mlir::Value val = fir::getBase(exv);
5118       auto valTy = val.getType();
5119       if (elementTypeWasAdjusted(valTy) &&
5120           !(fir::isa_ref_type(valTy) && fir::isa_integer(ty)))
5121         return convertAdjustedType(builder, loc, ty, exv);
5122       return builder.createConvert(loc, ty, val);
5123     };
5124   }
5125 
5126   template <int KIND>
5127   CC genarr(const Fortran::evaluate::ComplexComponent<KIND> &x) {
5128     mlir::Location loc = getLoc();
5129     auto lambda = genarr(x.left());
5130     bool isImagPart = x.isImaginaryPart;
5131     return [=](IterSpace iters) -> ExtValue {
5132       mlir::Value lhs = fir::getBase(lambda(iters));
5133       return fir::factory::Complex{builder, loc}.extractComplexPart(lhs,
5134                                                                     isImagPart);
5135     };
5136   }
5137 
5138   template <typename T>
5139   CC genarr(const Fortran::evaluate::Parentheses<T> &x) {
5140     mlir::Location loc = getLoc();
5141     if (isReferentiallyOpaque()) {
5142       // Context is a call argument in, for example, an elemental procedure
5143       // call. TODO: all array arguments should use array_load, array_access,
5144       // array_amend, and INTENT(OUT), INTENT(INOUT) arguments should have
5145       // array_merge_store ops.
5146       TODO(loc, "parentheses on argument in elemental call");
5147     }
5148     auto f = genarr(x.left());
5149     return [=](IterSpace iters) -> ExtValue {
5150       auto val = f(iters);
5151       mlir::Value base = fir::getBase(val);
5152       auto newBase =
5153           builder.create<fir::NoReassocOp>(loc, base.getType(), base);
5154       return fir::substBase(val, newBase);
5155     };
5156   }
5157   template <int KIND>
5158   CC genarr(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
5159                 Fortran::common::TypeCategory::Integer, KIND>> &x) {
5160     mlir::Location loc = getLoc();
5161     auto f = genarr(x.left());
5162     return [=](IterSpace iters) -> ExtValue {
5163       mlir::Value val = fir::getBase(f(iters));
5164       mlir::Type ty =
5165           converter.genType(Fortran::common::TypeCategory::Integer, KIND);
5166       mlir::Value zero = builder.createIntegerConstant(loc, ty, 0);
5167       return builder.create<mlir::arith::SubIOp>(loc, zero, val);
5168     };
5169   }
5170   template <int KIND>
5171   CC genarr(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
5172                 Fortran::common::TypeCategory::Real, KIND>> &x) {
5173     mlir::Location loc = getLoc();
5174     auto f = genarr(x.left());
5175     return [=](IterSpace iters) -> ExtValue {
5176       return builder.create<mlir::arith::NegFOp>(loc, fir::getBase(f(iters)));
5177     };
5178   }
5179   template <int KIND>
5180   CC genarr(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
5181                 Fortran::common::TypeCategory::Complex, KIND>> &x) {
5182     mlir::Location loc = getLoc();
5183     auto f = genarr(x.left());
5184     return [=](IterSpace iters) -> ExtValue {
5185       return builder.create<fir::NegcOp>(loc, fir::getBase(f(iters)));
5186     };
5187   }
5188 
5189   //===--------------------------------------------------------------------===//
5190   // Binary elemental ops
5191   //===--------------------------------------------------------------------===//
5192 
5193   template <typename OP, typename A>
5194   CC createBinaryOp(const A &evEx) {
5195     mlir::Location loc = getLoc();
5196     auto lambda = genarr(evEx.left());
5197     auto rf = genarr(evEx.right());
5198     return [=](IterSpace iters) -> ExtValue {
5199       mlir::Value left = fir::getBase(lambda(iters));
5200       mlir::Value right = fir::getBase(rf(iters));
5201       return builder.create<OP>(loc, left, right);
5202     };
5203   }
5204 
5205 #undef GENBIN
5206 #define GENBIN(GenBinEvOp, GenBinTyCat, GenBinFirOp)                           \
5207   template <int KIND>                                                          \
5208   CC genarr(const Fortran::evaluate::GenBinEvOp<Fortran::evaluate::Type<       \
5209                 Fortran::common::TypeCategory::GenBinTyCat, KIND>> &x) {       \
5210     return createBinaryOp<GenBinFirOp>(x);                                     \
5211   }
5212 
5213   GENBIN(Add, Integer, mlir::arith::AddIOp)
5214   GENBIN(Add, Real, mlir::arith::AddFOp)
5215   GENBIN(Add, Complex, fir::AddcOp)
5216   GENBIN(Subtract, Integer, mlir::arith::SubIOp)
5217   GENBIN(Subtract, Real, mlir::arith::SubFOp)
5218   GENBIN(Subtract, Complex, fir::SubcOp)
5219   GENBIN(Multiply, Integer, mlir::arith::MulIOp)
5220   GENBIN(Multiply, Real, mlir::arith::MulFOp)
5221   GENBIN(Multiply, Complex, fir::MulcOp)
5222   GENBIN(Divide, Integer, mlir::arith::DivSIOp)
5223   GENBIN(Divide, Real, mlir::arith::DivFOp)
5224   GENBIN(Divide, Complex, fir::DivcOp)
5225 
5226   template <Fortran::common::TypeCategory TC, int KIND>
5227   CC genarr(
5228       const Fortran::evaluate::Power<Fortran::evaluate::Type<TC, KIND>> &x) {
5229     mlir::Location loc = getLoc();
5230     mlir::Type ty = converter.genType(TC, KIND);
5231     auto lf = genarr(x.left());
5232     auto rf = genarr(x.right());
5233     return [=](IterSpace iters) -> ExtValue {
5234       mlir::Value lhs = fir::getBase(lf(iters));
5235       mlir::Value rhs = fir::getBase(rf(iters));
5236       return Fortran::lower::genPow(builder, loc, ty, lhs, rhs);
5237     };
5238   }
5239   template <Fortran::common::TypeCategory TC, int KIND>
5240   CC genarr(
5241       const Fortran::evaluate::Extremum<Fortran::evaluate::Type<TC, KIND>> &x) {
5242     mlir::Location loc = getLoc();
5243     auto lf = genarr(x.left());
5244     auto rf = genarr(x.right());
5245     switch (x.ordering) {
5246     case Fortran::evaluate::Ordering::Greater:
5247       return [=](IterSpace iters) -> ExtValue {
5248         mlir::Value lhs = fir::getBase(lf(iters));
5249         mlir::Value rhs = fir::getBase(rf(iters));
5250         return Fortran::lower::genMax(builder, loc,
5251                                       llvm::ArrayRef<mlir::Value>{lhs, rhs});
5252       };
5253     case Fortran::evaluate::Ordering::Less:
5254       return [=](IterSpace iters) -> ExtValue {
5255         mlir::Value lhs = fir::getBase(lf(iters));
5256         mlir::Value rhs = fir::getBase(rf(iters));
5257         return Fortran::lower::genMin(builder, loc,
5258                                       llvm::ArrayRef<mlir::Value>{lhs, rhs});
5259       };
5260     case Fortran::evaluate::Ordering::Equal:
5261       llvm_unreachable("Equal is not a valid ordering in this context");
5262     }
5263     llvm_unreachable("unknown ordering");
5264   }
5265   template <Fortran::common::TypeCategory TC, int KIND>
5266   CC genarr(
5267       const Fortran::evaluate::RealToIntPower<Fortran::evaluate::Type<TC, KIND>>
5268           &x) {
5269     mlir::Location loc = getLoc();
5270     auto ty = converter.genType(TC, KIND);
5271     auto lf = genarr(x.left());
5272     auto rf = genarr(x.right());
5273     return [=](IterSpace iters) {
5274       mlir::Value lhs = fir::getBase(lf(iters));
5275       mlir::Value rhs = fir::getBase(rf(iters));
5276       return Fortran::lower::genPow(builder, loc, ty, lhs, rhs);
5277     };
5278   }
5279   template <int KIND>
5280   CC genarr(const Fortran::evaluate::ComplexConstructor<KIND> &x) {
5281     mlir::Location loc = getLoc();
5282     auto lf = genarr(x.left());
5283     auto rf = genarr(x.right());
5284     return [=](IterSpace iters) -> ExtValue {
5285       mlir::Value lhs = fir::getBase(lf(iters));
5286       mlir::Value rhs = fir::getBase(rf(iters));
5287       return fir::factory::Complex{builder, loc}.createComplex(KIND, lhs, rhs);
5288     };
5289   }
5290 
5291   /// Fortran's concatenation operator `//`.
5292   template <int KIND>
5293   CC genarr(const Fortran::evaluate::Concat<KIND> &x) {
5294     mlir::Location loc = getLoc();
5295     auto lf = genarr(x.left());
5296     auto rf = genarr(x.right());
5297     return [=](IterSpace iters) -> ExtValue {
5298       auto lhs = lf(iters);
5299       auto rhs = rf(iters);
5300       const fir::CharBoxValue *lchr = lhs.getCharBox();
5301       const fir::CharBoxValue *rchr = rhs.getCharBox();
5302       if (lchr && rchr) {
5303         return fir::factory::CharacterExprHelper{builder, loc}
5304             .createConcatenate(*lchr, *rchr);
5305       }
5306       TODO(loc, "concat on unexpected extended values");
5307       return mlir::Value{};
5308     };
5309   }
5310 
5311   template <int KIND>
5312   CC genarr(const Fortran::evaluate::SetLength<KIND> &x) {
5313     auto lf = genarr(x.left());
5314     mlir::Value rhs = fir::getBase(asScalar(x.right()));
5315     return [=](IterSpace iters) -> ExtValue {
5316       mlir::Value lhs = fir::getBase(lf(iters));
5317       return fir::CharBoxValue{lhs, rhs};
5318     };
5319   }
5320 
5321   template <typename A>
5322   CC genarr(const Fortran::evaluate::Constant<A> &x) {
5323     if (/*explicitSpaceIsActive() &&*/ x.Rank() == 0)
5324       return genScalarAndForwardValue(x);
5325     mlir::Location loc = getLoc();
5326     mlir::IndexType idxTy = builder.getIndexType();
5327     mlir::Type arrTy = converter.genType(toEvExpr(x));
5328     std::string globalName = Fortran::lower::mangle::mangleArrayLiteral(x);
5329     fir::GlobalOp global = builder.getNamedGlobal(globalName);
5330     if (!global) {
5331       mlir::Type symTy = arrTy;
5332       mlir::Type eleTy = symTy.cast<fir::SequenceType>().getEleTy();
5333       // If we have a rank-1 array of integer, real, or logical, then we can
5334       // create a global array with the dense attribute.
5335       //
5336       // The mlir tensor type can only handle integer, real, or logical. It
5337       // does not currently support nested structures which is required for
5338       // complex.
5339       //
5340       // Also, we currently handle just rank-1 since tensor type assumes
5341       // row major array ordering. We will need to reorder the dimensions
5342       // in the tensor type to support Fortran's column major array ordering.
5343       // How to create this tensor type is to be determined.
5344       if (x.Rank() == 1 &&
5345           eleTy.isa<fir::LogicalType, mlir::IntegerType, mlir::FloatType>())
5346         global = Fortran::lower::createDenseGlobal(
5347             loc, arrTy, globalName, builder.createInternalLinkage(), true,
5348             toEvExpr(x), converter);
5349       // Note: If call to createDenseGlobal() returns 0, then call
5350       // createGlobalConstant() below.
5351       if (!global)
5352         global = builder.createGlobalConstant(
5353             loc, arrTy, globalName,
5354             [&](fir::FirOpBuilder &builder) {
5355               Fortran::lower::StatementContext stmtCtx(
5356                   /*cleanupProhibited=*/true);
5357               fir::ExtendedValue result =
5358                   Fortran::lower::createSomeInitializerExpression(
5359                       loc, converter, toEvExpr(x), symMap, stmtCtx);
5360               mlir::Value castTo =
5361                   builder.createConvert(loc, arrTy, fir::getBase(result));
5362               builder.create<fir::HasValueOp>(loc, castTo);
5363             },
5364             builder.createInternalLinkage());
5365     }
5366     auto addr = builder.create<fir::AddrOfOp>(getLoc(), global.resultType(),
5367                                               global.getSymbol());
5368     auto seqTy = global.getType().cast<fir::SequenceType>();
5369     llvm::SmallVector<mlir::Value> extents;
5370     for (auto extent : seqTy.getShape())
5371       extents.push_back(builder.createIntegerConstant(loc, idxTy, extent));
5372     if (auto charTy = seqTy.getEleTy().dyn_cast<fir::CharacterType>()) {
5373       mlir::Value len = builder.createIntegerConstant(loc, builder.getI64Type(),
5374                                                       charTy.getLen());
5375       return genarr(fir::CharArrayBoxValue{addr, len, extents});
5376     }
5377     return genarr(fir::ArrayBoxValue{addr, extents});
5378   }
5379 
5380   //===--------------------------------------------------------------------===//
5381   // A vector subscript expression may be wrapped with a cast to INTEGER*8.
5382   // Get rid of it here so the vector can be loaded. Add it back when
5383   // generating the elemental evaluation (inside the loop nest).
5384 
5385   static Fortran::lower::SomeExpr
5386   ignoreEvConvert(const Fortran::evaluate::Expr<Fortran::evaluate::Type<
5387                       Fortran::common::TypeCategory::Integer, 8>> &x) {
5388     return std::visit([&](const auto &v) { return ignoreEvConvert(v); }, x.u);
5389   }
5390   template <Fortran::common::TypeCategory FROM>
5391   static Fortran::lower::SomeExpr ignoreEvConvert(
5392       const Fortran::evaluate::Convert<
5393           Fortran::evaluate::Type<Fortran::common::TypeCategory::Integer, 8>,
5394           FROM> &x) {
5395     return toEvExpr(x.left());
5396   }
5397   template <typename A>
5398   static Fortran::lower::SomeExpr ignoreEvConvert(const A &x) {
5399     return toEvExpr(x);
5400   }
5401 
5402   //===--------------------------------------------------------------------===//
5403   // Get the `Se::Symbol*` for the subscript expression, `x`. This symbol can
5404   // be used to determine the lbound, ubound of the vector.
5405 
5406   template <typename A>
5407   static const Fortran::semantics::Symbol *
5408   extractSubscriptSymbol(const Fortran::evaluate::Expr<A> &x) {
5409     return std::visit([&](const auto &v) { return extractSubscriptSymbol(v); },
5410                       x.u);
5411   }
5412   template <typename A>
5413   static const Fortran::semantics::Symbol *
5414   extractSubscriptSymbol(const Fortran::evaluate::Designator<A> &x) {
5415     return Fortran::evaluate::UnwrapWholeSymbolDataRef(x);
5416   }
5417   template <typename A>
5418   static const Fortran::semantics::Symbol *extractSubscriptSymbol(const A &x) {
5419     return nullptr;
5420   }
5421 
5422   //===--------------------------------------------------------------------===//
5423 
5424   /// Get the declared lower bound value of the array `x` in dimension `dim`.
5425   /// The argument `one` must be an ssa-value for the constant 1.
5426   mlir::Value getLBound(const ExtValue &x, unsigned dim, mlir::Value one) {
5427     return fir::factory::readLowerBound(builder, getLoc(), x, dim, one);
5428   }
5429 
5430   /// Get the declared upper bound value of the array `x` in dimension `dim`.
5431   /// The argument `one` must be an ssa-value for the constant 1.
5432   mlir::Value getUBound(const ExtValue &x, unsigned dim, mlir::Value one) {
5433     mlir::Location loc = getLoc();
5434     mlir::Value lb = getLBound(x, dim, one);
5435     mlir::Value extent = fir::factory::readExtent(builder, loc, x, dim);
5436     auto add = builder.create<mlir::arith::AddIOp>(loc, lb, extent);
5437     return builder.create<mlir::arith::SubIOp>(loc, add, one);
5438   }
5439 
5440   /// Return the extent of the boxed array `x` in dimesion `dim`.
5441   mlir::Value getExtent(const ExtValue &x, unsigned dim) {
5442     return fir::factory::readExtent(builder, getLoc(), x, dim);
5443   }
5444 
5445   template <typename A>
5446   ExtValue genArrayBase(const A &base) {
5447     ScalarExprLowering sel{getLoc(), converter, symMap, stmtCtx};
5448     return base.IsSymbol() ? sel.gen(getFirstSym(base))
5449                            : sel.gen(base.GetComponent());
5450   }
5451 
5452   template <typename A>
5453   bool hasEvArrayRef(const A &x) {
5454     struct HasEvArrayRefHelper
5455         : public Fortran::evaluate::AnyTraverse<HasEvArrayRefHelper> {
5456       HasEvArrayRefHelper()
5457           : Fortran::evaluate::AnyTraverse<HasEvArrayRefHelper>(*this) {}
5458       using Fortran::evaluate::AnyTraverse<HasEvArrayRefHelper>::operator();
5459       bool operator()(const Fortran::evaluate::ArrayRef &) const {
5460         return true;
5461       }
5462     } helper;
5463     return helper(x);
5464   }
5465 
5466   CC genVectorSubscriptArrayFetch(const Fortran::lower::SomeExpr &expr,
5467                                   std::size_t dim) {
5468     PushSemantics(ConstituentSemantics::RefTransparent);
5469     auto saved = Fortran::common::ScopedSet(explicitSpace, nullptr);
5470     llvm::SmallVector<mlir::Value> savedDestShape = destShape;
5471     destShape.clear();
5472     auto result = genarr(expr);
5473     if (destShape.empty())
5474       TODO(getLoc(), "expected vector to have an extent");
5475     assert(destShape.size() == 1 && "vector has rank > 1");
5476     if (destShape[0] != savedDestShape[dim]) {
5477       // Not the same, so choose the smaller value.
5478       mlir::Location loc = getLoc();
5479       auto cmp = builder.create<mlir::arith::CmpIOp>(
5480           loc, mlir::arith::CmpIPredicate::sgt, destShape[0],
5481           savedDestShape[dim]);
5482       auto sel = builder.create<mlir::arith::SelectOp>(
5483           loc, cmp, savedDestShape[dim], destShape[0]);
5484       savedDestShape[dim] = sel;
5485       destShape = savedDestShape;
5486     }
5487     return result;
5488   }
5489 
5490   /// Generate an access by vector subscript using the index in the iteration
5491   /// vector at `dim`.
5492   mlir::Value genAccessByVector(mlir::Location loc, CC genArrFetch,
5493                                 IterSpace iters, std::size_t dim) {
5494     IterationSpace vecIters(iters,
5495                             llvm::ArrayRef<mlir::Value>{iters.iterValue(dim)});
5496     fir::ExtendedValue fetch = genArrFetch(vecIters);
5497     mlir::IndexType idxTy = builder.getIndexType();
5498     return builder.createConvert(loc, idxTy, fir::getBase(fetch));
5499   }
5500 
5501   /// When we have an array reference, the expressions specified in each
5502   /// dimension may be slice operations (e.g. `i:j:k`), vectors, or simple
5503   /// (loop-invarianet) scalar expressions. This returns the base entity, the
5504   /// resulting type, and a continuation to adjust the default iteration space.
5505   void genSliceIndices(ComponentPath &cmptData, const ExtValue &arrayExv,
5506                        const Fortran::evaluate::ArrayRef &x, bool atBase) {
5507     mlir::Location loc = getLoc();
5508     mlir::IndexType idxTy = builder.getIndexType();
5509     mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
5510     llvm::SmallVector<mlir::Value> &trips = cmptData.trips;
5511     LLVM_DEBUG(llvm::dbgs() << "array: " << arrayExv << '\n');
5512     auto &pc = cmptData.pc;
5513     const bool useTripsForSlice = !explicitSpaceIsActive();
5514     const bool createDestShape = destShape.empty();
5515     bool useSlice = false;
5516     std::size_t shapeIndex = 0;
5517     for (auto sub : llvm::enumerate(x.subscript())) {
5518       const std::size_t subsIndex = sub.index();
5519       std::visit(
5520           Fortran::common::visitors{
5521               [&](const Fortran::evaluate::Triplet &t) {
5522                 mlir::Value lowerBound;
5523                 if (auto optLo = t.lower())
5524                   lowerBound = fir::getBase(asScalar(*optLo));
5525                 else
5526                   lowerBound = getLBound(arrayExv, subsIndex, one);
5527                 lowerBound = builder.createConvert(loc, idxTy, lowerBound);
5528                 mlir::Value stride = fir::getBase(asScalar(t.stride()));
5529                 stride = builder.createConvert(loc, idxTy, stride);
5530                 if (useTripsForSlice || createDestShape) {
5531                   // Generate a slice operation for the triplet. The first and
5532                   // second position of the triplet may be omitted, and the
5533                   // declared lbound and/or ubound expression values,
5534                   // respectively, should be used instead.
5535                   trips.push_back(lowerBound);
5536                   mlir::Value upperBound;
5537                   if (auto optUp = t.upper())
5538                     upperBound = fir::getBase(asScalar(*optUp));
5539                   else
5540                     upperBound = getUBound(arrayExv, subsIndex, one);
5541                   upperBound = builder.createConvert(loc, idxTy, upperBound);
5542                   trips.push_back(upperBound);
5543                   trips.push_back(stride);
5544                   if (createDestShape) {
5545                     auto extent = builder.genExtentFromTriplet(
5546                         loc, lowerBound, upperBound, stride, idxTy);
5547                     destShape.push_back(extent);
5548                   }
5549                   useSlice = true;
5550                 }
5551                 if (!useTripsForSlice) {
5552                   auto currentPC = pc;
5553                   pc = [=](IterSpace iters) {
5554                     IterationSpace newIters = currentPC(iters);
5555                     mlir::Value impliedIter = newIters.iterValue(subsIndex);
5556                     // FIXME: must use the lower bound of this component.
5557                     auto arrLowerBound =
5558                         atBase ? getLBound(arrayExv, subsIndex, one) : one;
5559                     auto initial = builder.create<mlir::arith::SubIOp>(
5560                         loc, lowerBound, arrLowerBound);
5561                     auto prod = builder.create<mlir::arith::MulIOp>(
5562                         loc, impliedIter, stride);
5563                     auto result =
5564                         builder.create<mlir::arith::AddIOp>(loc, initial, prod);
5565                     newIters.setIndexValue(subsIndex, result);
5566                     return newIters;
5567                   };
5568                 }
5569                 shapeIndex++;
5570               },
5571               [&](const Fortran::evaluate::IndirectSubscriptIntegerExpr &ie) {
5572                 const auto &e = ie.value(); // dereference
5573                 if (isArray(e)) {
5574                   // This is a vector subscript. Use the index values as read
5575                   // from a vector to determine the temporary array value.
5576                   // Note: 9.5.3.3.3(3) specifies undefined behavior for
5577                   // multiple updates to any specific array element through a
5578                   // vector subscript with replicated values.
5579                   assert(!isBoxValue() &&
5580                          "fir.box cannot be created with vector subscripts");
5581                   auto arrExpr = ignoreEvConvert(e);
5582                   if (createDestShape)
5583                     destShape.push_back(fir::factory::getExtentAtDimension(
5584                         loc, builder, arrayExv, subsIndex));
5585                   auto genArrFetch =
5586                       genVectorSubscriptArrayFetch(arrExpr, shapeIndex);
5587                   auto currentPC = pc;
5588                   pc = [=](IterSpace iters) {
5589                     IterationSpace newIters = currentPC(iters);
5590                     auto val = genAccessByVector(loc, genArrFetch, newIters,
5591                                                  subsIndex);
5592                     // Value read from vector subscript array and normalized
5593                     // using the base array's lower bound value.
5594                     mlir::Value lb = fir::factory::readLowerBound(
5595                         builder, loc, arrayExv, subsIndex, one);
5596                     auto origin = builder.create<mlir::arith::SubIOp>(
5597                         loc, idxTy, val, lb);
5598                     newIters.setIndexValue(subsIndex, origin);
5599                     return newIters;
5600                   };
5601                   if (useTripsForSlice) {
5602                     LLVM_ATTRIBUTE_UNUSED auto vectorSubscriptShape =
5603                         getShape(arrayOperands.back());
5604                     auto undef = builder.create<fir::UndefOp>(loc, idxTy);
5605                     trips.push_back(undef);
5606                     trips.push_back(undef);
5607                     trips.push_back(undef);
5608                   }
5609                   shapeIndex++;
5610                 } else {
5611                   // This is a regular scalar subscript.
5612                   if (useTripsForSlice) {
5613                     // A regular scalar index, which does not yield an array
5614                     // section. Use a degenerate slice operation
5615                     // `(e:undef:undef)` in this dimension as a placeholder.
5616                     // This does not necessarily change the rank of the original
5617                     // array, so the iteration space must also be extended to
5618                     // include this expression in this dimension to adjust to
5619                     // the array's declared rank.
5620                     mlir::Value v = fir::getBase(asScalar(e));
5621                     trips.push_back(v);
5622                     auto undef = builder.create<fir::UndefOp>(loc, idxTy);
5623                     trips.push_back(undef);
5624                     trips.push_back(undef);
5625                     auto currentPC = pc;
5626                     // Cast `e` to index type.
5627                     mlir::Value iv = builder.createConvert(loc, idxTy, v);
5628                     // Normalize `e` by subtracting the declared lbound.
5629                     mlir::Value lb = fir::factory::readLowerBound(
5630                         builder, loc, arrayExv, subsIndex, one);
5631                     mlir::Value ivAdj =
5632                         builder.create<mlir::arith::SubIOp>(loc, idxTy, iv, lb);
5633                     // Add lbound adjusted value of `e` to the iteration vector
5634                     // (except when creating a box because the iteration vector
5635                     // is empty).
5636                     if (!isBoxValue())
5637                       pc = [=](IterSpace iters) {
5638                         IterationSpace newIters = currentPC(iters);
5639                         newIters.insertIndexValue(subsIndex, ivAdj);
5640                         return newIters;
5641                       };
5642                   } else {
5643                     auto currentPC = pc;
5644                     mlir::Value newValue = fir::getBase(asScalarArray(e));
5645                     mlir::Value result =
5646                         builder.createConvert(loc, idxTy, newValue);
5647                     mlir::Value lb = fir::factory::readLowerBound(
5648                         builder, loc, arrayExv, subsIndex, one);
5649                     result = builder.create<mlir::arith::SubIOp>(loc, idxTy,
5650                                                                  result, lb);
5651                     pc = [=](IterSpace iters) {
5652                       IterationSpace newIters = currentPC(iters);
5653                       newIters.insertIndexValue(subsIndex, result);
5654                       return newIters;
5655                     };
5656                   }
5657                 }
5658               }},
5659           sub.value().u);
5660     }
5661     if (!useSlice)
5662       trips.clear();
5663   }
5664 
5665   static mlir::Type unwrapBoxEleTy(mlir::Type ty) {
5666     if (auto boxTy = ty.dyn_cast<fir::BoxType>())
5667       return fir::unwrapRefType(boxTy.getEleTy());
5668     return ty;
5669   }
5670 
5671   llvm::SmallVector<mlir::Value> getShape(mlir::Type ty) {
5672     llvm::SmallVector<mlir::Value> result;
5673     ty = unwrapBoxEleTy(ty);
5674     mlir::Location loc = getLoc();
5675     mlir::IndexType idxTy = builder.getIndexType();
5676     for (auto extent : ty.cast<fir::SequenceType>().getShape()) {
5677       auto v = extent == fir::SequenceType::getUnknownExtent()
5678                    ? builder.create<fir::UndefOp>(loc, idxTy).getResult()
5679                    : builder.createIntegerConstant(loc, idxTy, extent);
5680       result.push_back(v);
5681     }
5682     return result;
5683   }
5684 
5685   CC genarr(const Fortran::semantics::SymbolRef &sym,
5686             ComponentPath &components) {
5687     return genarr(sym.get(), components);
5688   }
5689 
5690   ExtValue abstractArrayExtValue(mlir::Value val, mlir::Value len = {}) {
5691     return convertToArrayBoxValue(getLoc(), builder, val, len);
5692   }
5693 
5694   CC genarr(const ExtValue &extMemref) {
5695     ComponentPath dummy(/*isImplicit=*/true);
5696     return genarr(extMemref, dummy);
5697   }
5698 
5699   /// Base case of generating an array reference,
5700   CC genarr(const ExtValue &extMemref, ComponentPath &components) {
5701     mlir::Location loc = getLoc();
5702     mlir::Value memref = fir::getBase(extMemref);
5703     mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(memref.getType());
5704     assert(arrTy.isa<fir::SequenceType>() && "memory ref must be an array");
5705     mlir::Value shape = builder.createShape(loc, extMemref);
5706     mlir::Value slice;
5707     if (components.isSlice()) {
5708       if (isBoxValue() && components.substring) {
5709         // Append the substring operator to emboxing Op as it will become an
5710         // interior adjustment (add offset, adjust LEN) to the CHARACTER value
5711         // being referenced in the descriptor.
5712         llvm::SmallVector<mlir::Value> substringBounds;
5713         populateBounds(substringBounds, components.substring);
5714         // Convert to (offset, size)
5715         mlir::Type iTy = substringBounds[0].getType();
5716         if (substringBounds.size() != 2) {
5717           fir::CharacterType charTy =
5718               fir::factory::CharacterExprHelper::getCharType(arrTy);
5719           if (charTy.hasConstantLen()) {
5720             mlir::IndexType idxTy = builder.getIndexType();
5721             fir::CharacterType::LenType charLen = charTy.getLen();
5722             mlir::Value lenValue =
5723                 builder.createIntegerConstant(loc, idxTy, charLen);
5724             substringBounds.push_back(lenValue);
5725           } else {
5726             llvm::SmallVector<mlir::Value> typeparams =
5727                 fir::getTypeParams(extMemref);
5728             substringBounds.push_back(typeparams.back());
5729           }
5730         }
5731         // Convert the lower bound to 0-based substring.
5732         mlir::Value one =
5733             builder.createIntegerConstant(loc, substringBounds[0].getType(), 1);
5734         substringBounds[0] =
5735             builder.create<mlir::arith::SubIOp>(loc, substringBounds[0], one);
5736         // Convert the upper bound to a length.
5737         mlir::Value cast = builder.createConvert(loc, iTy, substringBounds[1]);
5738         mlir::Value zero = builder.createIntegerConstant(loc, iTy, 0);
5739         auto size =
5740             builder.create<mlir::arith::SubIOp>(loc, cast, substringBounds[0]);
5741         auto cmp = builder.create<mlir::arith::CmpIOp>(
5742             loc, mlir::arith::CmpIPredicate::sgt, size, zero);
5743         // size = MAX(upper - (lower - 1), 0)
5744         substringBounds[1] =
5745             builder.create<mlir::arith::SelectOp>(loc, cmp, size, zero);
5746         slice = builder.create<fir::SliceOp>(loc, components.trips,
5747                                              components.suffixComponents,
5748                                              substringBounds);
5749       } else {
5750         slice = builder.createSlice(loc, extMemref, components.trips,
5751                                     components.suffixComponents);
5752       }
5753       if (components.hasComponents()) {
5754         auto seqTy = arrTy.cast<fir::SequenceType>();
5755         mlir::Type eleTy =
5756             fir::applyPathToType(seqTy.getEleTy(), components.suffixComponents);
5757         if (!eleTy)
5758           fir::emitFatalError(loc, "slicing path is ill-formed");
5759         if (auto realTy = eleTy.dyn_cast<fir::RealType>())
5760           eleTy = Fortran::lower::convertReal(realTy.getContext(),
5761                                               realTy.getFKind());
5762 
5763         // create the type of the projected array.
5764         arrTy = fir::SequenceType::get(seqTy.getShape(), eleTy);
5765         LLVM_DEBUG(llvm::dbgs()
5766                    << "type of array projection from component slicing: "
5767                    << eleTy << ", " << arrTy << '\n');
5768       }
5769     }
5770     arrayOperands.push_back(ArrayOperand{memref, shape, slice});
5771     if (destShape.empty())
5772       destShape = getShape(arrayOperands.back());
5773     if (isBoxValue()) {
5774       // Semantics are a reference to a boxed array.
5775       // This case just requires that an embox operation be created to box the
5776       // value. The value of the box is forwarded in the continuation.
5777       mlir::Type reduceTy = reduceRank(arrTy, slice);
5778       auto boxTy = fir::BoxType::get(reduceTy);
5779       if (components.substring) {
5780         // Adjust char length to substring size.
5781         fir::CharacterType charTy =
5782             fir::factory::CharacterExprHelper::getCharType(reduceTy);
5783         auto seqTy = reduceTy.cast<fir::SequenceType>();
5784         // TODO: Use a constant for fir.char LEN if we can compute it.
5785         boxTy = fir::BoxType::get(
5786             fir::SequenceType::get(fir::CharacterType::getUnknownLen(
5787                                        builder.getContext(), charTy.getFKind()),
5788                                    seqTy.getDimension()));
5789       }
5790       mlir::Value embox =
5791           memref.getType().isa<fir::BoxType>()
5792               ? builder.create<fir::ReboxOp>(loc, boxTy, memref, shape, slice)
5793                     .getResult()
5794               : builder
5795                     .create<fir::EmboxOp>(loc, boxTy, memref, shape, slice,
5796                                           fir::getTypeParams(extMemref))
5797                     .getResult();
5798       return [=](IterSpace) -> ExtValue { return fir::BoxValue(embox); };
5799     }
5800     auto eleTy = arrTy.cast<fir::SequenceType>().getEleTy();
5801     if (isReferentiallyOpaque()) {
5802       // Semantics are an opaque reference to an array.
5803       // This case forwards a continuation that will generate the address
5804       // arithmetic to the array element. This does not have copy-in/copy-out
5805       // semantics. No attempt to copy the array value will be made during the
5806       // interpretation of the Fortran statement.
5807       mlir::Type refEleTy = builder.getRefType(eleTy);
5808       return [=](IterSpace iters) -> ExtValue {
5809         // ArrayCoorOp does not expect zero based indices.
5810         llvm::SmallVector<mlir::Value> indices = fir::factory::originateIndices(
5811             loc, builder, memref.getType(), shape, iters.iterVec());
5812         mlir::Value coor = builder.create<fir::ArrayCoorOp>(
5813             loc, refEleTy, memref, shape, slice, indices,
5814             fir::getTypeParams(extMemref));
5815         if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) {
5816           llvm::SmallVector<mlir::Value> substringBounds;
5817           populateBounds(substringBounds, components.substring);
5818           if (!substringBounds.empty()) {
5819             mlir::Value dstLen = fir::factory::genLenOfCharacter(
5820                 builder, loc, arrTy.cast<fir::SequenceType>(), memref,
5821                 fir::getTypeParams(extMemref), iters.iterVec(),
5822                 substringBounds);
5823             fir::CharBoxValue dstChar(coor, dstLen);
5824             return fir::factory::CharacterExprHelper{builder, loc}
5825                 .createSubstring(dstChar, substringBounds);
5826           }
5827         }
5828         return fir::factory::arraySectionElementToExtendedValue(
5829             builder, loc, extMemref, coor, slice);
5830       };
5831     }
5832     auto arrLoad = builder.create<fir::ArrayLoadOp>(
5833         loc, arrTy, memref, shape, slice, fir::getTypeParams(extMemref));
5834     mlir::Value arrLd = arrLoad.getResult();
5835     if (isProjectedCopyInCopyOut()) {
5836       // Semantics are projected copy-in copy-out.
5837       // The backing store of the destination of an array expression may be
5838       // partially modified. These updates are recorded in FIR by forwarding a
5839       // continuation that generates an `array_update` Op. The destination is
5840       // always loaded at the beginning of the statement and merged at the
5841       // end.
5842       destination = arrLoad;
5843       auto lambda = ccStoreToDest.hasValue()
5844                         ? ccStoreToDest.getValue()
5845                         : defaultStoreToDestination(components.substring);
5846       return [=](IterSpace iters) -> ExtValue { return lambda(iters); };
5847     }
5848     if (isCustomCopyInCopyOut()) {
5849       // Create an array_modify to get the LHS element address and indicate
5850       // the assignment, the actual assignment must be implemented in
5851       // ccStoreToDest.
5852       destination = arrLoad;
5853       return [=](IterSpace iters) -> ExtValue {
5854         mlir::Value innerArg = iters.innerArgument();
5855         mlir::Type resTy = innerArg.getType();
5856         mlir::Type eleTy = fir::applyPathToType(resTy, iters.iterVec());
5857         mlir::Type refEleTy =
5858             fir::isa_ref_type(eleTy) ? eleTy : builder.getRefType(eleTy);
5859         auto arrModify = builder.create<fir::ArrayModifyOp>(
5860             loc, mlir::TypeRange{refEleTy, resTy}, innerArg, iters.iterVec(),
5861             destination.getTypeparams());
5862         return abstractArrayExtValue(arrModify.getResult(1));
5863       };
5864     }
5865     if (isCopyInCopyOut()) {
5866       // Semantics are copy-in copy-out.
5867       // The continuation simply forwards the result of the `array_load` Op,
5868       // which is the value of the array as it was when loaded. All data
5869       // references with rank > 0 in an array expression typically have
5870       // copy-in copy-out semantics.
5871       return [=](IterSpace) -> ExtValue { return arrLd; };
5872     }
5873     mlir::Operation::operand_range arrLdTypeParams = arrLoad.getTypeparams();
5874     if (isValueAttribute()) {
5875       // Semantics are value attribute.
5876       // Here the continuation will `array_fetch` a value from an array and
5877       // then store that value in a temporary. One can thus imitate pass by
5878       // value even when the call is pass by reference.
5879       return [=](IterSpace iters) -> ExtValue {
5880         mlir::Value base;
5881         mlir::Type eleTy = fir::applyPathToType(arrTy, iters.iterVec());
5882         if (isAdjustedArrayElementType(eleTy)) {
5883           mlir::Type eleRefTy = builder.getRefType(eleTy);
5884           base = builder.create<fir::ArrayAccessOp>(
5885               loc, eleRefTy, arrLd, iters.iterVec(), arrLdTypeParams);
5886         } else {
5887           base = builder.create<fir::ArrayFetchOp>(
5888               loc, eleTy, arrLd, iters.iterVec(), arrLdTypeParams);
5889         }
5890         mlir::Value temp = builder.createTemporary(
5891             loc, base.getType(),
5892             llvm::ArrayRef<mlir::NamedAttribute>{
5893                 Fortran::lower::getAdaptToByRefAttr(builder)});
5894         builder.create<fir::StoreOp>(loc, base, temp);
5895         return fir::factory::arraySectionElementToExtendedValue(
5896             builder, loc, extMemref, temp, slice);
5897       };
5898     }
5899     // In the default case, the array reference forwards an `array_fetch` or
5900     // `array_access` Op in the continuation.
5901     return [=](IterSpace iters) -> ExtValue {
5902       mlir::Type eleTy = fir::applyPathToType(arrTy, iters.iterVec());
5903       if (isAdjustedArrayElementType(eleTy)) {
5904         mlir::Type eleRefTy = builder.getRefType(eleTy);
5905         mlir::Value arrayOp = builder.create<fir::ArrayAccessOp>(
5906             loc, eleRefTy, arrLd, iters.iterVec(), arrLdTypeParams);
5907         if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) {
5908           llvm::SmallVector<mlir::Value> substringBounds;
5909           populateBounds(substringBounds, components.substring);
5910           if (!substringBounds.empty()) {
5911             mlir::Value dstLen = fir::factory::genLenOfCharacter(
5912                 builder, loc, arrLoad, iters.iterVec(), substringBounds);
5913             fir::CharBoxValue dstChar(arrayOp, dstLen);
5914             return fir::factory::CharacterExprHelper{builder, loc}
5915                 .createSubstring(dstChar, substringBounds);
5916           }
5917         }
5918         return fir::factory::arraySectionElementToExtendedValue(
5919             builder, loc, extMemref, arrayOp, slice);
5920       }
5921       auto arrFetch = builder.create<fir::ArrayFetchOp>(
5922           loc, eleTy, arrLd, iters.iterVec(), arrLdTypeParams);
5923       return fir::factory::arraySectionElementToExtendedValue(
5924           builder, loc, extMemref, arrFetch, slice);
5925     };
5926   }
5927 
5928   /// Given an optional fir.box, returns an fir.box that is the original one if
5929   /// it is present and it otherwise an unallocated box.
5930   /// Absent fir.box are implemented as a null pointer descriptor. Generated
5931   /// code may need to unconditionally read a fir.box that can be absent.
5932   /// This helper allows creating a fir.box that can be read in all cases
5933   /// outside of a fir.if (isPresent) region. However, the usages of the value
5934   /// read from such box should still only be done in a fir.if(isPresent).
5935   static fir::ExtendedValue
5936   absentBoxToUnalllocatedBox(fir::FirOpBuilder &builder, mlir::Location loc,
5937                              const fir::ExtendedValue &exv,
5938                              mlir::Value isPresent) {
5939     mlir::Value box = fir::getBase(exv);
5940     mlir::Type boxType = box.getType();
5941     assert(boxType.isa<fir::BoxType>() && "argument must be a fir.box");
5942     mlir::Value emptyBox =
5943         fir::factory::createUnallocatedBox(builder, loc, boxType, llvm::None);
5944     auto safeToReadBox =
5945         builder.create<mlir::arith::SelectOp>(loc, isPresent, box, emptyBox);
5946     return fir::substBase(exv, safeToReadBox);
5947   }
5948 
5949   std::tuple<CC, mlir::Value, mlir::Type>
5950   genOptionalArrayFetch(const Fortran::lower::SomeExpr &expr) {
5951     assert(expr.Rank() > 0 && "expr must be an array");
5952     mlir::Location loc = getLoc();
5953     ExtValue optionalArg = asInquired(expr);
5954     mlir::Value isPresent = genActualIsPresentTest(builder, loc, optionalArg);
5955     // Generate an array load and access to an array that may be an absent
5956     // optional or an unallocated optional.
5957     mlir::Value base = getBase(optionalArg);
5958     const bool hasOptionalAttr =
5959         fir::valueHasFirAttribute(base, fir::getOptionalAttrName());
5960     mlir::Type baseType = fir::unwrapRefType(base.getType());
5961     const bool isBox = baseType.isa<fir::BoxType>();
5962     const bool isAllocOrPtr = Fortran::evaluate::IsAllocatableOrPointerObject(
5963         expr, converter.getFoldingContext());
5964     mlir::Type arrType = fir::unwrapPassByRefType(baseType);
5965     mlir::Type eleType = fir::unwrapSequenceType(arrType);
5966     ExtValue exv = optionalArg;
5967     if (hasOptionalAttr && isBox && !isAllocOrPtr) {
5968       // Elemental argument cannot be allocatable or pointers (C15100).
5969       // Hence, per 15.5.2.12 3 (8) and (9), the provided Allocatable and
5970       // Pointer optional arrays cannot be absent. The only kind of entities
5971       // that can get here are optional assumed shape and polymorphic entities.
5972       exv = absentBoxToUnalllocatedBox(builder, loc, exv, isPresent);
5973     }
5974     // All the properties can be read from any fir.box but the read values may
5975     // be undefined and should only be used inside a fir.if (canBeRead) region.
5976     if (const auto *mutableBox = exv.getBoxOf<fir::MutableBoxValue>())
5977       exv = fir::factory::genMutableBoxRead(builder, loc, *mutableBox);
5978 
5979     mlir::Value memref = fir::getBase(exv);
5980     mlir::Value shape = builder.createShape(loc, exv);
5981     mlir::Value noSlice;
5982     auto arrLoad = builder.create<fir::ArrayLoadOp>(
5983         loc, arrType, memref, shape, noSlice, fir::getTypeParams(exv));
5984     mlir::Operation::operand_range arrLdTypeParams = arrLoad.getTypeparams();
5985     mlir::Value arrLd = arrLoad.getResult();
5986     // Mark the load to tell later passes it is unsafe to use this array_load
5987     // shape unconditionally.
5988     arrLoad->setAttr(fir::getOptionalAttrName(), builder.getUnitAttr());
5989 
5990     // Place the array as optional on the arrayOperands stack so that its
5991     // shape will only be used as a fallback to induce the implicit loop nest
5992     // (that is if there is no non optional array arguments).
5993     arrayOperands.push_back(
5994         ArrayOperand{memref, shape, noSlice, /*mayBeAbsent=*/true});
5995 
5996     // By value semantics.
5997     auto cc = [=](IterSpace iters) -> ExtValue {
5998       auto arrFetch = builder.create<fir::ArrayFetchOp>(
5999           loc, eleType, arrLd, iters.iterVec(), arrLdTypeParams);
6000       return fir::factory::arraySectionElementToExtendedValue(
6001           builder, loc, exv, arrFetch, noSlice);
6002     };
6003     return {cc, isPresent, eleType};
6004   }
6005 
6006   /// Generate a continuation to pass \p expr to an OPTIONAL argument of an
6007   /// elemental procedure. This is meant to handle the cases where \p expr might
6008   /// be dynamically absent (i.e. when it is a POINTER, an ALLOCATABLE or an
6009   /// OPTIONAL variable). If p\ expr is guaranteed to be present genarr() can
6010   /// directly be called instead.
6011   CC genarrForwardOptionalArgumentToCall(const Fortran::lower::SomeExpr &expr) {
6012     mlir::Location loc = getLoc();
6013     // Only by-value numerical and logical so far.
6014     if (semant != ConstituentSemantics::RefTransparent)
6015       TODO(loc, "optional arguments in user defined elemental procedures");
6016 
6017     // Handle scalar argument case (the if-then-else is generated outside of the
6018     // implicit loop nest).
6019     if (expr.Rank() == 0) {
6020       ExtValue optionalArg = asInquired(expr);
6021       mlir::Value isPresent = genActualIsPresentTest(builder, loc, optionalArg);
6022       mlir::Value elementValue =
6023           fir::getBase(genOptionalValue(builder, loc, optionalArg, isPresent));
6024       return [=](IterSpace iters) -> ExtValue { return elementValue; };
6025     }
6026 
6027     CC cc;
6028     mlir::Value isPresent;
6029     mlir::Type eleType;
6030     std::tie(cc, isPresent, eleType) = genOptionalArrayFetch(expr);
6031     return [=](IterSpace iters) -> ExtValue {
6032       mlir::Value elementValue =
6033           builder
6034               .genIfOp(loc, {eleType}, isPresent,
6035                        /*withElseRegion=*/true)
6036               .genThen([&]() {
6037                 builder.create<fir::ResultOp>(loc, fir::getBase(cc(iters)));
6038               })
6039               .genElse([&]() {
6040                 mlir::Value zero =
6041                     fir::factory::createZeroValue(builder, loc, eleType);
6042                 builder.create<fir::ResultOp>(loc, zero);
6043               })
6044               .getResults()[0];
6045       return elementValue;
6046     };
6047   }
6048 
6049   /// Reduce the rank of a array to be boxed based on the slice's operands.
6050   static mlir::Type reduceRank(mlir::Type arrTy, mlir::Value slice) {
6051     if (slice) {
6052       auto slOp = mlir::dyn_cast<fir::SliceOp>(slice.getDefiningOp());
6053       assert(slOp && "expected slice op");
6054       auto seqTy = arrTy.dyn_cast<fir::SequenceType>();
6055       assert(seqTy && "expected array type");
6056       mlir::Operation::operand_range triples = slOp.getTriples();
6057       fir::SequenceType::Shape shape;
6058       // reduce the rank for each invariant dimension
6059       for (unsigned i = 1, end = triples.size(); i < end; i += 3)
6060         if (!mlir::isa_and_nonnull<fir::UndefOp>(triples[i].getDefiningOp()))
6061           shape.push_back(fir::SequenceType::getUnknownExtent());
6062       return fir::SequenceType::get(shape, seqTy.getEleTy());
6063     }
6064     // not sliced, so no change in rank
6065     return arrTy;
6066   }
6067 
6068   /// Example: <code>array%RE</code>
6069   CC genarr(const Fortran::evaluate::ComplexPart &x,
6070             ComponentPath &components) {
6071     components.reversePath.push_back(&x);
6072     return genarr(x.complex(), components);
6073   }
6074 
6075   template <typename A>
6076   CC genSlicePath(const A &x, ComponentPath &components) {
6077     return genarr(x, components);
6078   }
6079 
6080   CC genarr(const Fortran::evaluate::StaticDataObject::Pointer &,
6081             ComponentPath &components) {
6082     fir::emitFatalError(getLoc(), "substring of static array object");
6083   }
6084 
6085   /// Substrings (see 9.4.1)
6086   CC genarr(const Fortran::evaluate::Substring &x, ComponentPath &components) {
6087     components.substring = &x;
6088     return std::visit([&](const auto &v) { return genarr(v, components); },
6089                       x.parent());
6090   }
6091 
6092   template <typename T>
6093   CC genarr(const Fortran::evaluate::FunctionRef<T> &funRef) {
6094     // Note that it's possible that the function being called returns either an
6095     // array or a scalar.  In the first case, use the element type of the array.
6096     return genProcRef(
6097         funRef, fir::unwrapSequenceType(converter.genType(toEvExpr(funRef))));
6098   }
6099 
6100   //===--------------------------------------------------------------------===//
6101   // Array construction
6102   //===--------------------------------------------------------------------===//
6103 
6104   /// Target agnostic computation of the size of an element in the array.
6105   /// Returns the size in bytes with type `index` or a null Value if the element
6106   /// size is not constant.
6107   mlir::Value computeElementSize(const ExtValue &exv, mlir::Type eleTy,
6108                                  mlir::Type resTy) {
6109     mlir::Location loc = getLoc();
6110     mlir::IndexType idxTy = builder.getIndexType();
6111     mlir::Value multiplier = builder.createIntegerConstant(loc, idxTy, 1);
6112     if (fir::hasDynamicSize(eleTy)) {
6113       if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) {
6114         // Array of char with dynamic length parameter. Downcast to an array
6115         // of singleton char, and scale by the len type parameter from
6116         // `exv`.
6117         exv.match(
6118             [&](const fir::CharBoxValue &cb) { multiplier = cb.getLen(); },
6119             [&](const fir::CharArrayBoxValue &cb) { multiplier = cb.getLen(); },
6120             [&](const fir::BoxValue &box) {
6121               multiplier = fir::factory::CharacterExprHelper(builder, loc)
6122                                .readLengthFromBox(box.getAddr());
6123             },
6124             [&](const fir::MutableBoxValue &box) {
6125               multiplier = fir::factory::CharacterExprHelper(builder, loc)
6126                                .readLengthFromBox(box.getAddr());
6127             },
6128             [&](const auto &) {
6129               fir::emitFatalError(loc,
6130                                   "array constructor element has unknown size");
6131             });
6132         fir::CharacterType newEleTy = fir::CharacterType::getSingleton(
6133             eleTy.getContext(), charTy.getFKind());
6134         if (auto seqTy = resTy.dyn_cast<fir::SequenceType>()) {
6135           assert(eleTy == seqTy.getEleTy());
6136           resTy = fir::SequenceType::get(seqTy.getShape(), newEleTy);
6137         }
6138         eleTy = newEleTy;
6139       } else {
6140         TODO(loc, "dynamic sized type");
6141       }
6142     }
6143     mlir::Type eleRefTy = builder.getRefType(eleTy);
6144     mlir::Type resRefTy = builder.getRefType(resTy);
6145     mlir::Value nullPtr = builder.createNullConstant(loc, resRefTy);
6146     auto offset = builder.create<fir::CoordinateOp>(
6147         loc, eleRefTy, nullPtr, mlir::ValueRange{multiplier});
6148     return builder.createConvert(loc, idxTy, offset);
6149   }
6150 
6151   /// Get the function signature of the LLVM memcpy intrinsic.
6152   mlir::FunctionType memcpyType() {
6153     return fir::factory::getLlvmMemcpy(builder).getFunctionType();
6154   }
6155 
6156   /// Create a call to the LLVM memcpy intrinsic.
6157   void createCallMemcpy(llvm::ArrayRef<mlir::Value> args) {
6158     mlir::Location loc = getLoc();
6159     mlir::func::FuncOp memcpyFunc = fir::factory::getLlvmMemcpy(builder);
6160     mlir::SymbolRefAttr funcSymAttr =
6161         builder.getSymbolRefAttr(memcpyFunc.getName());
6162     mlir::FunctionType funcTy = memcpyFunc.getFunctionType();
6163     builder.create<fir::CallOp>(loc, funcTy.getResults(), funcSymAttr, args);
6164   }
6165 
6166   // Construct code to check for a buffer overrun and realloc the buffer when
6167   // space is depleted. This is done between each item in the ac-value-list.
6168   mlir::Value growBuffer(mlir::Value mem, mlir::Value needed,
6169                          mlir::Value bufferSize, mlir::Value buffSize,
6170                          mlir::Value eleSz) {
6171     mlir::Location loc = getLoc();
6172     mlir::func::FuncOp reallocFunc = fir::factory::getRealloc(builder);
6173     auto cond = builder.create<mlir::arith::CmpIOp>(
6174         loc, mlir::arith::CmpIPredicate::sle, bufferSize, needed);
6175     auto ifOp = builder.create<fir::IfOp>(loc, mem.getType(), cond,
6176                                           /*withElseRegion=*/true);
6177     auto insPt = builder.saveInsertionPoint();
6178     builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
6179     // Not enough space, resize the buffer.
6180     mlir::IndexType idxTy = builder.getIndexType();
6181     mlir::Value two = builder.createIntegerConstant(loc, idxTy, 2);
6182     auto newSz = builder.create<mlir::arith::MulIOp>(loc, needed, two);
6183     builder.create<fir::StoreOp>(loc, newSz, buffSize);
6184     mlir::Value byteSz = builder.create<mlir::arith::MulIOp>(loc, newSz, eleSz);
6185     mlir::SymbolRefAttr funcSymAttr =
6186         builder.getSymbolRefAttr(reallocFunc.getName());
6187     mlir::FunctionType funcTy = reallocFunc.getFunctionType();
6188     auto newMem = builder.create<fir::CallOp>(
6189         loc, funcTy.getResults(), funcSymAttr,
6190         llvm::ArrayRef<mlir::Value>{
6191             builder.createConvert(loc, funcTy.getInputs()[0], mem),
6192             builder.createConvert(loc, funcTy.getInputs()[1], byteSz)});
6193     mlir::Value castNewMem =
6194         builder.createConvert(loc, mem.getType(), newMem.getResult(0));
6195     builder.create<fir::ResultOp>(loc, castNewMem);
6196     builder.setInsertionPointToStart(&ifOp.getElseRegion().front());
6197     // Otherwise, just forward the buffer.
6198     builder.create<fir::ResultOp>(loc, mem);
6199     builder.restoreInsertionPoint(insPt);
6200     return ifOp.getResult(0);
6201   }
6202 
6203   /// Copy the next value (or vector of values) into the array being
6204   /// constructed.
6205   mlir::Value copyNextArrayCtorSection(const ExtValue &exv, mlir::Value buffPos,
6206                                        mlir::Value buffSize, mlir::Value mem,
6207                                        mlir::Value eleSz, mlir::Type eleTy,
6208                                        mlir::Type eleRefTy, mlir::Type resTy) {
6209     mlir::Location loc = getLoc();
6210     auto off = builder.create<fir::LoadOp>(loc, buffPos);
6211     auto limit = builder.create<fir::LoadOp>(loc, buffSize);
6212     mlir::IndexType idxTy = builder.getIndexType();
6213     mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
6214 
6215     if (fir::isRecordWithAllocatableMember(eleTy))
6216       TODO(loc, "deep copy on allocatable members");
6217 
6218     if (!eleSz) {
6219       // Compute the element size at runtime.
6220       assert(fir::hasDynamicSize(eleTy));
6221       if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) {
6222         auto charBytes =
6223             builder.getKindMap().getCharacterBitsize(charTy.getFKind()) / 8;
6224         mlir::Value bytes =
6225             builder.createIntegerConstant(loc, idxTy, charBytes);
6226         mlir::Value length = fir::getLen(exv);
6227         if (!length)
6228           fir::emitFatalError(loc, "result is not boxed character");
6229         eleSz = builder.create<mlir::arith::MulIOp>(loc, bytes, length);
6230       } else {
6231         TODO(loc, "PDT size");
6232         // Will call the PDT's size function with the type parameters.
6233       }
6234     }
6235 
6236     // Compute the coordinate using `fir.coordinate_of`, or, if the type has
6237     // dynamic size, generating the pointer arithmetic.
6238     auto computeCoordinate = [&](mlir::Value buff, mlir::Value off) {
6239       mlir::Type refTy = eleRefTy;
6240       if (fir::hasDynamicSize(eleTy)) {
6241         if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) {
6242           // Scale a simple pointer using dynamic length and offset values.
6243           auto chTy = fir::CharacterType::getSingleton(charTy.getContext(),
6244                                                        charTy.getFKind());
6245           refTy = builder.getRefType(chTy);
6246           mlir::Type toTy = builder.getRefType(builder.getVarLenSeqTy(chTy));
6247           buff = builder.createConvert(loc, toTy, buff);
6248           off = builder.create<mlir::arith::MulIOp>(loc, off, eleSz);
6249         } else {
6250           TODO(loc, "PDT offset");
6251         }
6252       }
6253       auto coor = builder.create<fir::CoordinateOp>(loc, refTy, buff,
6254                                                     mlir::ValueRange{off});
6255       return builder.createConvert(loc, eleRefTy, coor);
6256     };
6257 
6258     // Lambda to lower an abstract array box value.
6259     auto doAbstractArray = [&](const auto &v) {
6260       // Compute the array size.
6261       mlir::Value arrSz = one;
6262       for (auto ext : v.getExtents())
6263         arrSz = builder.create<mlir::arith::MulIOp>(loc, arrSz, ext);
6264 
6265       // Grow the buffer as needed.
6266       auto endOff = builder.create<mlir::arith::AddIOp>(loc, off, arrSz);
6267       mem = growBuffer(mem, endOff, limit, buffSize, eleSz);
6268 
6269       // Copy the elements to the buffer.
6270       mlir::Value byteSz =
6271           builder.create<mlir::arith::MulIOp>(loc, arrSz, eleSz);
6272       auto buff = builder.createConvert(loc, fir::HeapType::get(resTy), mem);
6273       mlir::Value buffi = computeCoordinate(buff, off);
6274       llvm::SmallVector<mlir::Value> args = fir::runtime::createArguments(
6275           builder, loc, memcpyType(), buffi, v.getAddr(), byteSz,
6276           /*volatile=*/builder.createBool(loc, false));
6277       createCallMemcpy(args);
6278 
6279       // Save the incremented buffer position.
6280       builder.create<fir::StoreOp>(loc, endOff, buffPos);
6281     };
6282 
6283     // Copy a trivial scalar value into the buffer.
6284     auto doTrivialScalar = [&](const ExtValue &v, mlir::Value len = {}) {
6285       // Increment the buffer position.
6286       auto plusOne = builder.create<mlir::arith::AddIOp>(loc, off, one);
6287 
6288       // Grow the buffer as needed.
6289       mem = growBuffer(mem, plusOne, limit, buffSize, eleSz);
6290 
6291       // Store the element in the buffer.
6292       mlir::Value buff =
6293           builder.createConvert(loc, fir::HeapType::get(resTy), mem);
6294       auto buffi = builder.create<fir::CoordinateOp>(loc, eleRefTy, buff,
6295                                                      mlir::ValueRange{off});
6296       fir::factory::genScalarAssignment(
6297           builder, loc,
6298           [&]() -> ExtValue {
6299             if (len)
6300               return fir::CharBoxValue(buffi, len);
6301             return buffi;
6302           }(),
6303           v);
6304       builder.create<fir::StoreOp>(loc, plusOne, buffPos);
6305     };
6306 
6307     // Copy the value.
6308     exv.match(
6309         [&](mlir::Value) { doTrivialScalar(exv); },
6310         [&](const fir::CharBoxValue &v) {
6311           auto buffer = v.getBuffer();
6312           if (fir::isa_char(buffer.getType())) {
6313             doTrivialScalar(exv, eleSz);
6314           } else {
6315             // Increment the buffer position.
6316             auto plusOne = builder.create<mlir::arith::AddIOp>(loc, off, one);
6317 
6318             // Grow the buffer as needed.
6319             mem = growBuffer(mem, plusOne, limit, buffSize, eleSz);
6320 
6321             // Store the element in the buffer.
6322             mlir::Value buff =
6323                 builder.createConvert(loc, fir::HeapType::get(resTy), mem);
6324             mlir::Value buffi = computeCoordinate(buff, off);
6325             llvm::SmallVector<mlir::Value> args = fir::runtime::createArguments(
6326                 builder, loc, memcpyType(), buffi, v.getAddr(), eleSz,
6327                 /*volatile=*/builder.createBool(loc, false));
6328             createCallMemcpy(args);
6329 
6330             builder.create<fir::StoreOp>(loc, plusOne, buffPos);
6331           }
6332         },
6333         [&](const fir::ArrayBoxValue &v) { doAbstractArray(v); },
6334         [&](const fir::CharArrayBoxValue &v) { doAbstractArray(v); },
6335         [&](const auto &) {
6336           TODO(loc, "unhandled array constructor expression");
6337         });
6338     return mem;
6339   }
6340 
6341   // Lower the expr cases in an ac-value-list.
6342   template <typename A>
6343   std::pair<ExtValue, bool>
6344   genArrayCtorInitializer(const Fortran::evaluate::Expr<A> &x, mlir::Type,
6345                           mlir::Value, mlir::Value, mlir::Value,
6346                           Fortran::lower::StatementContext &stmtCtx) {
6347     if (isArray(x))
6348       return {lowerNewArrayExpression(converter, symMap, stmtCtx, toEvExpr(x)),
6349               /*needCopy=*/true};
6350     return {asScalar(x), /*needCopy=*/true};
6351   }
6352 
6353   // Lower an ac-implied-do in an ac-value-list.
6354   template <typename A>
6355   std::pair<ExtValue, bool>
6356   genArrayCtorInitializer(const Fortran::evaluate::ImpliedDo<A> &x,
6357                           mlir::Type resTy, mlir::Value mem,
6358                           mlir::Value buffPos, mlir::Value buffSize,
6359                           Fortran::lower::StatementContext &) {
6360     mlir::Location loc = getLoc();
6361     mlir::IndexType idxTy = builder.getIndexType();
6362     mlir::Value lo =
6363         builder.createConvert(loc, idxTy, fir::getBase(asScalar(x.lower())));
6364     mlir::Value up =
6365         builder.createConvert(loc, idxTy, fir::getBase(asScalar(x.upper())));
6366     mlir::Value step =
6367         builder.createConvert(loc, idxTy, fir::getBase(asScalar(x.stride())));
6368     auto seqTy = resTy.template cast<fir::SequenceType>();
6369     mlir::Type eleTy = fir::unwrapSequenceType(seqTy);
6370     auto loop =
6371         builder.create<fir::DoLoopOp>(loc, lo, up, step, /*unordered=*/false,
6372                                       /*finalCount=*/false, mem);
6373     // create a new binding for x.name(), to ac-do-variable, to the iteration
6374     // value.
6375     symMap.pushImpliedDoBinding(toStringRef(x.name()), loop.getInductionVar());
6376     auto insPt = builder.saveInsertionPoint();
6377     builder.setInsertionPointToStart(loop.getBody());
6378     // Thread mem inside the loop via loop argument.
6379     mem = loop.getRegionIterArgs()[0];
6380 
6381     mlir::Type eleRefTy = builder.getRefType(eleTy);
6382 
6383     // Any temps created in the loop body must be freed inside the loop body.
6384     stmtCtx.pushScope();
6385     llvm::Optional<mlir::Value> charLen;
6386     for (const Fortran::evaluate::ArrayConstructorValue<A> &acv : x.values()) {
6387       auto [exv, copyNeeded] = std::visit(
6388           [&](const auto &v) {
6389             return genArrayCtorInitializer(v, resTy, mem, buffPos, buffSize,
6390                                            stmtCtx);
6391           },
6392           acv.u);
6393       mlir::Value eleSz = computeElementSize(exv, eleTy, resTy);
6394       mem = copyNeeded ? copyNextArrayCtorSection(exv, buffPos, buffSize, mem,
6395                                                   eleSz, eleTy, eleRefTy, resTy)
6396                        : fir::getBase(exv);
6397       if (fir::isa_char(seqTy.getEleTy()) && !charLen.hasValue()) {
6398         charLen = builder.createTemporary(loc, builder.getI64Type());
6399         mlir::Value castLen =
6400             builder.createConvert(loc, builder.getI64Type(), fir::getLen(exv));
6401         builder.create<fir::StoreOp>(loc, castLen, charLen.getValue());
6402       }
6403     }
6404     stmtCtx.finalize(/*popScope=*/true);
6405 
6406     builder.create<fir::ResultOp>(loc, mem);
6407     builder.restoreInsertionPoint(insPt);
6408     mem = loop.getResult(0);
6409     symMap.popImpliedDoBinding();
6410     llvm::SmallVector<mlir::Value> extents = {
6411         builder.create<fir::LoadOp>(loc, buffPos).getResult()};
6412 
6413     // Convert to extended value.
6414     if (fir::isa_char(seqTy.getEleTy())) {
6415       auto len = builder.create<fir::LoadOp>(loc, charLen.getValue());
6416       return {fir::CharArrayBoxValue{mem, len, extents}, /*needCopy=*/false};
6417     }
6418     return {fir::ArrayBoxValue{mem, extents}, /*needCopy=*/false};
6419   }
6420 
6421   // To simplify the handling and interaction between the various cases, array
6422   // constructors are always lowered to the incremental construction code
6423   // pattern, even if the extent of the array value is constant. After the
6424   // MemToReg pass and constant folding, the optimizer should be able to
6425   // determine that all the buffer overrun tests are false when the
6426   // incremental construction wasn't actually required.
6427   template <typename A>
6428   CC genarr(const Fortran::evaluate::ArrayConstructor<A> &x) {
6429     mlir::Location loc = getLoc();
6430     auto evExpr = toEvExpr(x);
6431     mlir::Type resTy = translateSomeExprToFIRType(converter, evExpr);
6432     mlir::IndexType idxTy = builder.getIndexType();
6433     auto seqTy = resTy.template cast<fir::SequenceType>();
6434     mlir::Type eleTy = fir::unwrapSequenceType(resTy);
6435     mlir::Value buffSize = builder.createTemporary(loc, idxTy, ".buff.size");
6436     mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
6437     mlir::Value buffPos = builder.createTemporary(loc, idxTy, ".buff.pos");
6438     builder.create<fir::StoreOp>(loc, zero, buffPos);
6439     // Allocate space for the array to be constructed.
6440     mlir::Value mem;
6441     if (fir::hasDynamicSize(resTy)) {
6442       if (fir::hasDynamicSize(eleTy)) {
6443         // The size of each element may depend on a general expression. Defer
6444         // creating the buffer until after the expression is evaluated.
6445         mem = builder.createNullConstant(loc, builder.getRefType(eleTy));
6446         builder.create<fir::StoreOp>(loc, zero, buffSize);
6447       } else {
6448         mlir::Value initBuffSz =
6449             builder.createIntegerConstant(loc, idxTy, clInitialBufferSize);
6450         mem = builder.create<fir::AllocMemOp>(
6451             loc, eleTy, /*typeparams=*/llvm::None, initBuffSz);
6452         builder.create<fir::StoreOp>(loc, initBuffSz, buffSize);
6453       }
6454     } else {
6455       mem = builder.create<fir::AllocMemOp>(loc, resTy);
6456       int64_t buffSz = 1;
6457       for (auto extent : seqTy.getShape())
6458         buffSz *= extent;
6459       mlir::Value initBuffSz =
6460           builder.createIntegerConstant(loc, idxTy, buffSz);
6461       builder.create<fir::StoreOp>(loc, initBuffSz, buffSize);
6462     }
6463     // Compute size of element
6464     mlir::Type eleRefTy = builder.getRefType(eleTy);
6465 
6466     // Populate the buffer with the elements, growing as necessary.
6467     llvm::Optional<mlir::Value> charLen;
6468     for (const auto &expr : x) {
6469       auto [exv, copyNeeded] = std::visit(
6470           [&](const auto &e) {
6471             return genArrayCtorInitializer(e, resTy, mem, buffPos, buffSize,
6472                                            stmtCtx);
6473           },
6474           expr.u);
6475       mlir::Value eleSz = computeElementSize(exv, eleTy, resTy);
6476       mem = copyNeeded ? copyNextArrayCtorSection(exv, buffPos, buffSize, mem,
6477                                                   eleSz, eleTy, eleRefTy, resTy)
6478                        : fir::getBase(exv);
6479       if (fir::isa_char(seqTy.getEleTy()) && !charLen.hasValue()) {
6480         charLen = builder.createTemporary(loc, builder.getI64Type());
6481         mlir::Value castLen =
6482             builder.createConvert(loc, builder.getI64Type(), fir::getLen(exv));
6483         builder.create<fir::StoreOp>(loc, castLen, charLen.getValue());
6484       }
6485     }
6486     mem = builder.createConvert(loc, fir::HeapType::get(resTy), mem);
6487     llvm::SmallVector<mlir::Value> extents = {
6488         builder.create<fir::LoadOp>(loc, buffPos)};
6489 
6490     // Cleanup the temporary.
6491     fir::FirOpBuilder *bldr = &converter.getFirOpBuilder();
6492     stmtCtx.attachCleanup(
6493         [bldr, loc, mem]() { bldr->create<fir::FreeMemOp>(loc, mem); });
6494 
6495     // Return the continuation.
6496     if (fir::isa_char(seqTy.getEleTy())) {
6497       if (charLen.hasValue()) {
6498         auto len = builder.create<fir::LoadOp>(loc, charLen.getValue());
6499         return genarr(fir::CharArrayBoxValue{mem, len, extents});
6500       }
6501       return genarr(fir::CharArrayBoxValue{mem, zero, extents});
6502     }
6503     return genarr(fir::ArrayBoxValue{mem, extents});
6504   }
6505 
6506   CC genarr(const Fortran::evaluate::ImpliedDoIndex &) {
6507     fir::emitFatalError(getLoc(), "implied do index cannot have rank > 0");
6508   }
6509   CC genarr(const Fortran::evaluate::TypeParamInquiry &x) {
6510     TODO(getLoc(), "array expr type parameter inquiry");
6511     return [](IterSpace iters) -> ExtValue { return mlir::Value{}; };
6512   }
6513   CC genarr(const Fortran::evaluate::DescriptorInquiry &x) {
6514     TODO(getLoc(), "array expr descriptor inquiry");
6515     return [](IterSpace iters) -> ExtValue { return mlir::Value{}; };
6516   }
6517   CC genarr(const Fortran::evaluate::StructureConstructor &x) {
6518     TODO(getLoc(), "structure constructor");
6519     return [](IterSpace iters) -> ExtValue { return mlir::Value{}; };
6520   }
6521 
6522   //===--------------------------------------------------------------------===//
6523   // LOCICAL operators (.NOT., .AND., .EQV., etc.)
6524   //===--------------------------------------------------------------------===//
6525 
6526   template <int KIND>
6527   CC genarr(const Fortran::evaluate::Not<KIND> &x) {
6528     mlir::Location loc = getLoc();
6529     mlir::IntegerType i1Ty = builder.getI1Type();
6530     auto lambda = genarr(x.left());
6531     mlir::Value truth = builder.createBool(loc, true);
6532     return [=](IterSpace iters) -> ExtValue {
6533       mlir::Value logical = fir::getBase(lambda(iters));
6534       mlir::Value val = builder.createConvert(loc, i1Ty, logical);
6535       return builder.create<mlir::arith::XOrIOp>(loc, val, truth);
6536     };
6537   }
6538   template <typename OP, typename A>
6539   CC createBinaryBoolOp(const A &x) {
6540     mlir::Location loc = getLoc();
6541     mlir::IntegerType i1Ty = builder.getI1Type();
6542     auto lf = genarr(x.left());
6543     auto rf = genarr(x.right());
6544     return [=](IterSpace iters) -> ExtValue {
6545       mlir::Value left = fir::getBase(lf(iters));
6546       mlir::Value right = fir::getBase(rf(iters));
6547       mlir::Value lhs = builder.createConvert(loc, i1Ty, left);
6548       mlir::Value rhs = builder.createConvert(loc, i1Ty, right);
6549       return builder.create<OP>(loc, lhs, rhs);
6550     };
6551   }
6552   template <typename OP, typename A>
6553   CC createCompareBoolOp(mlir::arith::CmpIPredicate pred, const A &x) {
6554     mlir::Location loc = getLoc();
6555     mlir::IntegerType i1Ty = builder.getI1Type();
6556     auto lf = genarr(x.left());
6557     auto rf = genarr(x.right());
6558     return [=](IterSpace iters) -> ExtValue {
6559       mlir::Value left = fir::getBase(lf(iters));
6560       mlir::Value right = fir::getBase(rf(iters));
6561       mlir::Value lhs = builder.createConvert(loc, i1Ty, left);
6562       mlir::Value rhs = builder.createConvert(loc, i1Ty, right);
6563       return builder.create<OP>(loc, pred, lhs, rhs);
6564     };
6565   }
6566   template <int KIND>
6567   CC genarr(const Fortran::evaluate::LogicalOperation<KIND> &x) {
6568     switch (x.logicalOperator) {
6569     case Fortran::evaluate::LogicalOperator::And:
6570       return createBinaryBoolOp<mlir::arith::AndIOp>(x);
6571     case Fortran::evaluate::LogicalOperator::Or:
6572       return createBinaryBoolOp<mlir::arith::OrIOp>(x);
6573     case Fortran::evaluate::LogicalOperator::Eqv:
6574       return createCompareBoolOp<mlir::arith::CmpIOp>(
6575           mlir::arith::CmpIPredicate::eq, x);
6576     case Fortran::evaluate::LogicalOperator::Neqv:
6577       return createCompareBoolOp<mlir::arith::CmpIOp>(
6578           mlir::arith::CmpIPredicate::ne, x);
6579     case Fortran::evaluate::LogicalOperator::Not:
6580       llvm_unreachable(".NOT. handled elsewhere");
6581     }
6582     llvm_unreachable("unhandled case");
6583   }
6584 
6585   //===--------------------------------------------------------------------===//
6586   // Relational operators (<, <=, ==, etc.)
6587   //===--------------------------------------------------------------------===//
6588 
6589   template <typename OP, typename PRED, typename A>
6590   CC createCompareOp(PRED pred, const A &x) {
6591     mlir::Location loc = getLoc();
6592     auto lf = genarr(x.left());
6593     auto rf = genarr(x.right());
6594     return [=](IterSpace iters) -> ExtValue {
6595       mlir::Value lhs = fir::getBase(lf(iters));
6596       mlir::Value rhs = fir::getBase(rf(iters));
6597       return builder.create<OP>(loc, pred, lhs, rhs);
6598     };
6599   }
6600   template <typename A>
6601   CC createCompareCharOp(mlir::arith::CmpIPredicate pred, const A &x) {
6602     mlir::Location loc = getLoc();
6603     auto lf = genarr(x.left());
6604     auto rf = genarr(x.right());
6605     return [=](IterSpace iters) -> ExtValue {
6606       auto lhs = lf(iters);
6607       auto rhs = rf(iters);
6608       return fir::runtime::genCharCompare(builder, loc, pred, lhs, rhs);
6609     };
6610   }
6611   template <int KIND>
6612   CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
6613                 Fortran::common::TypeCategory::Integer, KIND>> &x) {
6614     return createCompareOp<mlir::arith::CmpIOp>(translateRelational(x.opr), x);
6615   }
6616   template <int KIND>
6617   CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
6618                 Fortran::common::TypeCategory::Character, KIND>> &x) {
6619     return createCompareCharOp(translateRelational(x.opr), x);
6620   }
6621   template <int KIND>
6622   CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
6623                 Fortran::common::TypeCategory::Real, KIND>> &x) {
6624     return createCompareOp<mlir::arith::CmpFOp>(translateFloatRelational(x.opr),
6625                                                 x);
6626   }
6627   template <int KIND>
6628   CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
6629                 Fortran::common::TypeCategory::Complex, KIND>> &x) {
6630     return createCompareOp<fir::CmpcOp>(translateFloatRelational(x.opr), x);
6631   }
6632   CC genarr(
6633       const Fortran::evaluate::Relational<Fortran::evaluate::SomeType> &r) {
6634     return std::visit([&](const auto &x) { return genarr(x); }, r.u);
6635   }
6636 
6637   template <typename A>
6638   CC genarr(const Fortran::evaluate::Designator<A> &des) {
6639     ComponentPath components(des.Rank() > 0);
6640     return std::visit([&](const auto &x) { return genarr(x, components); },
6641                       des.u);
6642   }
6643 
6644   /// Is the path component rank > 0?
6645   static bool ranked(const PathComponent &x) {
6646     return std::visit(Fortran::common::visitors{
6647                           [](const ImplicitSubscripts &) { return false; },
6648                           [](const auto *v) { return v->Rank() > 0; }},
6649                       x);
6650   }
6651 
6652   void extendComponent(Fortran::lower::ComponentPath &component,
6653                        mlir::Type coorTy, mlir::ValueRange vals) {
6654     auto *bldr = &converter.getFirOpBuilder();
6655     llvm::SmallVector<mlir::Value> offsets(vals.begin(), vals.end());
6656     auto currentFunc = component.getExtendCoorRef();
6657     auto loc = getLoc();
6658     auto newCoorRef = [bldr, coorTy, offsets, currentFunc,
6659                        loc](mlir::Value val) -> mlir::Value {
6660       return bldr->create<fir::CoordinateOp>(loc, bldr->getRefType(coorTy),
6661                                              currentFunc(val), offsets);
6662     };
6663     component.extendCoorRef = newCoorRef;
6664   }
6665 
6666   //===-------------------------------------------------------------------===//
6667   // Array data references in an explicit iteration space.
6668   //
6669   // Use the base array that was loaded before the loop nest.
6670   //===-------------------------------------------------------------------===//
6671 
6672   /// Lower the path (`revPath`, in reverse) to be appended to an array_fetch or
6673   /// array_update op. \p ty is the initial type of the array
6674   /// (reference). Returns the type of the element after application of the
6675   /// path in \p components.
6676   ///
6677   /// TODO: This needs to deal with array's with initial bounds other than 1.
6678   /// TODO: Thread type parameters correctly.
6679   mlir::Type lowerPath(const ExtValue &arrayExv, ComponentPath &components) {
6680     mlir::Location loc = getLoc();
6681     mlir::Type ty = fir::getBase(arrayExv).getType();
6682     auto &revPath = components.reversePath;
6683     ty = fir::unwrapPassByRefType(ty);
6684     bool prefix = true;
6685     bool deref = false;
6686     auto addComponentList = [&](mlir::Type ty, mlir::ValueRange vals) {
6687       if (deref) {
6688         extendComponent(components, ty, vals);
6689       } else if (prefix) {
6690         for (auto v : vals)
6691           components.prefixComponents.push_back(v);
6692       } else {
6693         for (auto v : vals)
6694           components.suffixComponents.push_back(v);
6695       }
6696     };
6697     mlir::IndexType idxTy = builder.getIndexType();
6698     mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
6699     bool atBase = true;
6700     auto saveSemant = semant;
6701     if (isProjectedCopyInCopyOut())
6702       semant = ConstituentSemantics::RefTransparent;
6703     unsigned index = 0;
6704     for (const auto &v : llvm::reverse(revPath)) {
6705       std::visit(
6706           Fortran::common::visitors{
6707               [&](const ImplicitSubscripts &) {
6708                 prefix = false;
6709                 ty = fir::unwrapSequenceType(ty);
6710               },
6711               [&](const Fortran::evaluate::ComplexPart *x) {
6712                 assert(!prefix && "complex part must be at end");
6713                 mlir::Value offset = builder.createIntegerConstant(
6714                     loc, builder.getI32Type(),
6715                     x->part() == Fortran::evaluate::ComplexPart::Part::RE ? 0
6716                                                                           : 1);
6717                 components.suffixComponents.push_back(offset);
6718                 ty = fir::applyPathToType(ty, mlir::ValueRange{offset});
6719               },
6720               [&](const Fortran::evaluate::ArrayRef *x) {
6721                 if (Fortran::lower::isRankedArrayAccess(*x)) {
6722                   genSliceIndices(components, arrayExv, *x, atBase);
6723                   ty = fir::unwrapSeqOrBoxedSeqType(ty);
6724                 } else {
6725                   // Array access where the expressions are scalar and cannot
6726                   // depend upon the implied iteration space.
6727                   unsigned ssIndex = 0u;
6728                   llvm::SmallVector<mlir::Value> componentsToAdd;
6729                   for (const auto &ss : x->subscript()) {
6730                     std::visit(
6731                         Fortran::common::visitors{
6732                             [&](const Fortran::evaluate::
6733                                     IndirectSubscriptIntegerExpr &ie) {
6734                               const auto &e = ie.value();
6735                               if (isArray(e))
6736                                 fir::emitFatalError(
6737                                     loc,
6738                                     "multiple components along single path "
6739                                     "generating array subexpressions");
6740                               // Lower scalar index expression, append it to
6741                               // subs.
6742                               mlir::Value subscriptVal =
6743                                   fir::getBase(asScalarArray(e));
6744                               // arrayExv is the base array. It needs to reflect
6745                               // the current array component instead.
6746                               // FIXME: must use lower bound of this component,
6747                               // not just the constant 1.
6748                               mlir::Value lb =
6749                                   atBase ? fir::factory::readLowerBound(
6750                                                builder, loc, arrayExv, ssIndex,
6751                                                one)
6752                                          : one;
6753                               mlir::Value val = builder.createConvert(
6754                                   loc, idxTy, subscriptVal);
6755                               mlir::Value ivAdj =
6756                                   builder.create<mlir::arith::SubIOp>(
6757                                       loc, idxTy, val, lb);
6758                               componentsToAdd.push_back(
6759                                   builder.createConvert(loc, idxTy, ivAdj));
6760                             },
6761                             [&](const auto &) {
6762                               fir::emitFatalError(
6763                                   loc, "multiple components along single path "
6764                                        "generating array subexpressions");
6765                             }},
6766                         ss.u);
6767                     ssIndex++;
6768                   }
6769                   ty = fir::unwrapSeqOrBoxedSeqType(ty);
6770                   addComponentList(ty, componentsToAdd);
6771                 }
6772               },
6773               [&](const Fortran::evaluate::Component *x) {
6774                 auto fieldTy = fir::FieldType::get(builder.getContext());
6775                 llvm::StringRef name = toStringRef(getLastSym(*x).name());
6776                 if (auto recTy = ty.dyn_cast<fir::RecordType>()) {
6777                   ty = recTy.getType(name);
6778                   auto fld = builder.create<fir::FieldIndexOp>(
6779                       loc, fieldTy, name, recTy, fir::getTypeParams(arrayExv));
6780                   addComponentList(ty, {fld});
6781                   if (index != revPath.size() - 1 || !isPointerAssignment()) {
6782                     // Need an intermediate  dereference if the boxed value
6783                     // appears in the middle of the component path or if it is
6784                     // on the right and this is not a pointer assignment.
6785                     if (auto boxTy = ty.dyn_cast<fir::BoxType>()) {
6786                       auto currentFunc = components.getExtendCoorRef();
6787                       auto loc = getLoc();
6788                       auto *bldr = &converter.getFirOpBuilder();
6789                       auto newCoorRef = [=](mlir::Value val) -> mlir::Value {
6790                         return bldr->create<fir::LoadOp>(loc, currentFunc(val));
6791                       };
6792                       components.extendCoorRef = newCoorRef;
6793                       deref = true;
6794                     }
6795                   }
6796                 } else if (auto boxTy = ty.dyn_cast<fir::BoxType>()) {
6797                   ty = fir::unwrapRefType(boxTy.getEleTy());
6798                   auto recTy = ty.cast<fir::RecordType>();
6799                   ty = recTy.getType(name);
6800                   auto fld = builder.create<fir::FieldIndexOp>(
6801                       loc, fieldTy, name, recTy, fir::getTypeParams(arrayExv));
6802                   extendComponent(components, ty, {fld});
6803                 } else {
6804                   TODO(loc, "other component type");
6805                 }
6806               }},
6807           v);
6808       atBase = false;
6809       ++index;
6810     }
6811     semant = saveSemant;
6812     ty = fir::unwrapSequenceType(ty);
6813     components.applied = true;
6814     return ty;
6815   }
6816 
6817   llvm::SmallVector<mlir::Value> genSubstringBounds(ComponentPath &components) {
6818     llvm::SmallVector<mlir::Value> result;
6819     if (components.substring)
6820       populateBounds(result, components.substring);
6821     return result;
6822   }
6823 
6824   CC applyPathToArrayLoad(fir::ArrayLoadOp load, ComponentPath &components) {
6825     mlir::Location loc = getLoc();
6826     auto revPath = components.reversePath;
6827     fir::ExtendedValue arrayExv =
6828         arrayLoadExtValue(builder, loc, load, {}, load);
6829     mlir::Type eleTy = lowerPath(arrayExv, components);
6830     auto currentPC = components.pc;
6831     auto pc = [=, prefix = components.prefixComponents,
6832                suffix = components.suffixComponents](IterSpace iters) {
6833       // Add path prefix and suffix.
6834       return IterationSpace(currentPC(iters), prefix, suffix);
6835     };
6836     components.resetPC();
6837     llvm::SmallVector<mlir::Value> substringBounds =
6838         genSubstringBounds(components);
6839     if (isProjectedCopyInCopyOut()) {
6840       destination = load;
6841       auto lambda = [=, esp = this->explicitSpace](IterSpace iters) mutable {
6842         mlir::Value innerArg = esp->findArgumentOfLoad(load);
6843         if (isAdjustedArrayElementType(eleTy)) {
6844           mlir::Type eleRefTy = builder.getRefType(eleTy);
6845           auto arrayOp = builder.create<fir::ArrayAccessOp>(
6846               loc, eleRefTy, innerArg, iters.iterVec(), load.getTypeparams());
6847           if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) {
6848             mlir::Value dstLen = fir::factory::genLenOfCharacter(
6849                 builder, loc, load, iters.iterVec(), substringBounds);
6850             fir::ArrayAmendOp amend = createCharArrayAmend(
6851                 loc, builder, arrayOp, dstLen, iters.elementExv(), innerArg,
6852                 substringBounds);
6853             return arrayLoadExtValue(builder, loc, load, iters.iterVec(), amend,
6854                                      dstLen);
6855           }
6856           if (fir::isa_derived(eleTy)) {
6857             fir::ArrayAmendOp amend =
6858                 createDerivedArrayAmend(loc, load, builder, arrayOp,
6859                                         iters.elementExv(), eleTy, innerArg);
6860             return arrayLoadExtValue(builder, loc, load, iters.iterVec(),
6861                                      amend);
6862           }
6863           assert(eleTy.isa<fir::SequenceType>());
6864           TODO(loc, "array (as element) assignment");
6865         }
6866         if (components.hasExtendCoorRef()) {
6867           auto eleBoxTy =
6868               fir::applyPathToType(innerArg.getType(), iters.iterVec());
6869           assert(eleBoxTy && eleBoxTy.isa<fir::BoxType>());
6870           auto arrayOp = builder.create<fir::ArrayAccessOp>(
6871               loc, builder.getRefType(eleBoxTy), innerArg, iters.iterVec(),
6872               fir::factory::getTypeParams(loc, builder, load));
6873           mlir::Value addr = components.getExtendCoorRef()(arrayOp);
6874           components.resetExtendCoorRef();
6875           // When the lhs is a boxed value and the context is not a pointer
6876           // assignment, then insert the dereference of the box before any
6877           // conversion and store.
6878           if (!isPointerAssignment()) {
6879             if (auto boxTy = eleTy.dyn_cast<fir::BoxType>()) {
6880               eleTy = boxTy.getEleTy();
6881               if (!(eleTy.isa<fir::PointerType>() ||
6882                     eleTy.isa<fir::HeapType>()))
6883                 eleTy = builder.getRefType(eleTy);
6884               addr = builder.create<fir::BoxAddrOp>(loc, eleTy, addr);
6885               eleTy = fir::unwrapRefType(eleTy);
6886             }
6887           }
6888           auto ele = convertElementForUpdate(loc, eleTy, iters.getElement());
6889           builder.create<fir::StoreOp>(loc, ele, addr);
6890           auto amend = builder.create<fir::ArrayAmendOp>(
6891               loc, innerArg.getType(), innerArg, arrayOp);
6892           return arrayLoadExtValue(builder, loc, load, iters.iterVec(), amend);
6893         }
6894         auto ele = convertElementForUpdate(loc, eleTy, iters.getElement());
6895         auto update = builder.create<fir::ArrayUpdateOp>(
6896             loc, innerArg.getType(), innerArg, ele, iters.iterVec(),
6897             fir::factory::getTypeParams(loc, builder, load));
6898         return arrayLoadExtValue(builder, loc, load, iters.iterVec(), update);
6899       };
6900       return [=](IterSpace iters) mutable { return lambda(pc(iters)); };
6901     }
6902     if (isCustomCopyInCopyOut()) {
6903       // Create an array_modify to get the LHS element address and indicate
6904       // the assignment, and create the call to the user defined assignment.
6905       destination = load;
6906       auto lambda = [=](IterSpace iters) mutable {
6907         mlir::Value innerArg = explicitSpace->findArgumentOfLoad(load);
6908         mlir::Type refEleTy =
6909             fir::isa_ref_type(eleTy) ? eleTy : builder.getRefType(eleTy);
6910         auto arrModify = builder.create<fir::ArrayModifyOp>(
6911             loc, mlir::TypeRange{refEleTy, innerArg.getType()}, innerArg,
6912             iters.iterVec(), load.getTypeparams());
6913         return arrayLoadExtValue(builder, loc, load, iters.iterVec(),
6914                                  arrModify.getResult(1));
6915       };
6916       return [=](IterSpace iters) mutable { return lambda(pc(iters)); };
6917     }
6918     auto lambda = [=, semant = this->semant](IterSpace iters) mutable {
6919       if (semant == ConstituentSemantics::RefOpaque ||
6920           isAdjustedArrayElementType(eleTy)) {
6921         mlir::Type resTy = builder.getRefType(eleTy);
6922         // Use array element reference semantics.
6923         auto access = builder.create<fir::ArrayAccessOp>(
6924             loc, resTy, load, iters.iterVec(), load.getTypeparams());
6925         mlir::Value newBase = access;
6926         if (fir::isa_char(eleTy)) {
6927           mlir::Value dstLen = fir::factory::genLenOfCharacter(
6928               builder, loc, load, iters.iterVec(), substringBounds);
6929           if (!substringBounds.empty()) {
6930             fir::CharBoxValue charDst{access, dstLen};
6931             fir::factory::CharacterExprHelper helper{builder, loc};
6932             charDst = helper.createSubstring(charDst, substringBounds);
6933             newBase = charDst.getAddr();
6934           }
6935           return arrayLoadExtValue(builder, loc, load, iters.iterVec(), newBase,
6936                                    dstLen);
6937         }
6938         return arrayLoadExtValue(builder, loc, load, iters.iterVec(), newBase);
6939       }
6940       if (components.hasExtendCoorRef()) {
6941         auto eleBoxTy = fir::applyPathToType(load.getType(), iters.iterVec());
6942         assert(eleBoxTy && eleBoxTy.isa<fir::BoxType>());
6943         auto access = builder.create<fir::ArrayAccessOp>(
6944             loc, builder.getRefType(eleBoxTy), load, iters.iterVec(),
6945             fir::factory::getTypeParams(loc, builder, load));
6946         mlir::Value addr = components.getExtendCoorRef()(access);
6947         components.resetExtendCoorRef();
6948         return arrayLoadExtValue(builder, loc, load, iters.iterVec(), addr);
6949       }
6950       if (isPointerAssignment()) {
6951         auto eleTy = fir::applyPathToType(load.getType(), iters.iterVec());
6952         if (!eleTy.isa<fir::BoxType>()) {
6953           // Rhs is a regular expression that will need to be boxed before
6954           // assigning to the boxed variable.
6955           auto typeParams = fir::factory::getTypeParams(loc, builder, load);
6956           auto access = builder.create<fir::ArrayAccessOp>(
6957               loc, builder.getRefType(eleTy), load, iters.iterVec(),
6958               typeParams);
6959           auto addr = components.getExtendCoorRef()(access);
6960           components.resetExtendCoorRef();
6961           auto ptrEleTy = fir::PointerType::get(eleTy);
6962           auto ptrAddr = builder.createConvert(loc, ptrEleTy, addr);
6963           auto boxTy = fir::BoxType::get(ptrEleTy);
6964           // FIXME: The typeparams to the load may be different than those of
6965           // the subobject.
6966           if (components.hasExtendCoorRef())
6967             TODO(loc, "need to adjust typeparameter(s) to reflect the final "
6968                       "component");
6969           mlir::Value embox = builder.create<fir::EmboxOp>(
6970               loc, boxTy, ptrAddr, /*shape=*/mlir::Value{},
6971               /*slice=*/mlir::Value{}, typeParams);
6972           return arrayLoadExtValue(builder, loc, load, iters.iterVec(), embox);
6973         }
6974       }
6975       auto fetch = builder.create<fir::ArrayFetchOp>(
6976           loc, eleTy, load, iters.iterVec(), load.getTypeparams());
6977       return arrayLoadExtValue(builder, loc, load, iters.iterVec(), fetch);
6978     };
6979     return [=](IterSpace iters) mutable { return lambda(pc(iters)); };
6980   }
6981 
6982   template <typename A>
6983   CC genImplicitArrayAccess(const A &x, ComponentPath &components) {
6984     components.reversePath.push_back(ImplicitSubscripts{});
6985     ExtValue exv = asScalarRef(x);
6986     lowerPath(exv, components);
6987     auto lambda = genarr(exv, components);
6988     return [=](IterSpace iters) { return lambda(components.pc(iters)); };
6989   }
6990   CC genImplicitArrayAccess(const Fortran::evaluate::NamedEntity &x,
6991                             ComponentPath &components) {
6992     if (x.IsSymbol())
6993       return genImplicitArrayAccess(getFirstSym(x), components);
6994     return genImplicitArrayAccess(x.GetComponent(), components);
6995   }
6996 
6997   template <typename A>
6998   CC genAsScalar(const A &x) {
6999     mlir::Location loc = getLoc();
7000     if (isProjectedCopyInCopyOut()) {
7001       return [=, &x, builder = &converter.getFirOpBuilder()](
7002                  IterSpace iters) -> ExtValue {
7003         ExtValue exv = asScalarRef(x);
7004         mlir::Value val = fir::getBase(exv);
7005         mlir::Type eleTy = fir::unwrapRefType(val.getType());
7006         if (isAdjustedArrayElementType(eleTy)) {
7007           if (fir::isa_char(eleTy)) {
7008             fir::factory::CharacterExprHelper{*builder, loc}.createAssign(
7009                 exv, iters.elementExv());
7010           } else if (fir::isa_derived(eleTy)) {
7011             TODO(loc, "assignment of derived type");
7012           } else {
7013             fir::emitFatalError(loc, "array type not expected in scalar");
7014           }
7015         } else {
7016           builder->create<fir::StoreOp>(loc, iters.getElement(), val);
7017         }
7018         return exv;
7019       };
7020     }
7021     return [=, &x](IterSpace) { return asScalar(x); };
7022   }
7023 
7024   bool tailIsPointerInPointerAssignment(const Fortran::semantics::Symbol &x,
7025                                         ComponentPath &components) {
7026     return isPointerAssignment() && Fortran::semantics::IsPointer(x) &&
7027            !components.hasComponents();
7028   }
7029   bool tailIsPointerInPointerAssignment(const Fortran::evaluate::Component &x,
7030                                         ComponentPath &components) {
7031     return tailIsPointerInPointerAssignment(getLastSym(x), components);
7032   }
7033 
7034   CC genarr(const Fortran::semantics::Symbol &x, ComponentPath &components) {
7035     if (explicitSpaceIsActive()) {
7036       if (x.Rank() > 0 && !tailIsPointerInPointerAssignment(x, components))
7037         components.reversePath.push_back(ImplicitSubscripts{});
7038       if (fir::ArrayLoadOp load = explicitSpace->findBinding(&x))
7039         return applyPathToArrayLoad(load, components);
7040     } else {
7041       return genImplicitArrayAccess(x, components);
7042     }
7043     if (pathIsEmpty(components))
7044       return genAsScalar(x);
7045     mlir::Location loc = getLoc();
7046     return [=](IterSpace) -> ExtValue {
7047       fir::emitFatalError(loc, "reached symbol with path");
7048     };
7049   }
7050 
7051   /// Lower a component path with or without rank.
7052   /// Example: <code>array%baz%qux%waldo</code>
7053   CC genarr(const Fortran::evaluate::Component &x, ComponentPath &components) {
7054     if (explicitSpaceIsActive()) {
7055       if (x.base().Rank() == 0 && x.Rank() > 0 &&
7056           !tailIsPointerInPointerAssignment(x, components))
7057         components.reversePath.push_back(ImplicitSubscripts{});
7058       if (fir::ArrayLoadOp load = explicitSpace->findBinding(&x))
7059         return applyPathToArrayLoad(load, components);
7060     } else {
7061       if (x.base().Rank() == 0)
7062         return genImplicitArrayAccess(x, components);
7063     }
7064     bool atEnd = pathIsEmpty(components);
7065     if (!getLastSym(x).test(Fortran::semantics::Symbol::Flag::ParentComp))
7066       // Skip parent components; their components are placed directly in the
7067       // object.
7068       components.reversePath.push_back(&x);
7069     auto result = genarr(x.base(), components);
7070     if (components.applied)
7071       return result;
7072     if (atEnd)
7073       return genAsScalar(x);
7074     mlir::Location loc = getLoc();
7075     return [=](IterSpace) -> ExtValue {
7076       fir::emitFatalError(loc, "reached component with path");
7077     };
7078   }
7079 
7080   /// Array reference with subscripts. If this has rank > 0, this is a form
7081   /// of an array section (slice).
7082   ///
7083   /// There are two "slicing" primitives that may be applied on a dimension by
7084   /// dimension basis: (1) triple notation and (2) vector addressing. Since
7085   /// dimensions can be selectively sliced, some dimensions may contain
7086   /// regular scalar expressions and those dimensions do not participate in
7087   /// the array expression evaluation.
7088   CC genarr(const Fortran::evaluate::ArrayRef &x, ComponentPath &components) {
7089     if (explicitSpaceIsActive()) {
7090       if (Fortran::lower::isRankedArrayAccess(x))
7091         components.reversePath.push_back(ImplicitSubscripts{});
7092       if (fir::ArrayLoadOp load = explicitSpace->findBinding(&x)) {
7093         components.reversePath.push_back(&x);
7094         return applyPathToArrayLoad(load, components);
7095       }
7096     } else {
7097       if (Fortran::lower::isRankedArrayAccess(x)) {
7098         components.reversePath.push_back(&x);
7099         return genImplicitArrayAccess(x.base(), components);
7100       }
7101     }
7102     bool atEnd = pathIsEmpty(components);
7103     components.reversePath.push_back(&x);
7104     auto result = genarr(x.base(), components);
7105     if (components.applied)
7106       return result;
7107     mlir::Location loc = getLoc();
7108     if (atEnd) {
7109       if (x.Rank() == 0)
7110         return genAsScalar(x);
7111       fir::emitFatalError(loc, "expected scalar");
7112     }
7113     return [=](IterSpace) -> ExtValue {
7114       fir::emitFatalError(loc, "reached arrayref with path");
7115     };
7116   }
7117 
7118   CC genarr(const Fortran::evaluate::CoarrayRef &x, ComponentPath &components) {
7119     TODO(getLoc(), "coarray reference");
7120   }
7121 
7122   CC genarr(const Fortran::evaluate::NamedEntity &x,
7123             ComponentPath &components) {
7124     return x.IsSymbol() ? genarr(getFirstSym(x), components)
7125                         : genarr(x.GetComponent(), components);
7126   }
7127 
7128   CC genarr(const Fortran::evaluate::DataRef &x, ComponentPath &components) {
7129     return std::visit([&](const auto &v) { return genarr(v, components); },
7130                       x.u);
7131   }
7132 
7133   bool pathIsEmpty(const ComponentPath &components) {
7134     return components.reversePath.empty();
7135   }
7136 
7137   explicit ArrayExprLowering(Fortran::lower::AbstractConverter &converter,
7138                              Fortran::lower::StatementContext &stmtCtx,
7139                              Fortran::lower::SymMap &symMap)
7140       : converter{converter}, builder{converter.getFirOpBuilder()},
7141         stmtCtx{stmtCtx}, symMap{symMap} {}
7142 
7143   explicit ArrayExprLowering(Fortran::lower::AbstractConverter &converter,
7144                              Fortran::lower::StatementContext &stmtCtx,
7145                              Fortran::lower::SymMap &symMap,
7146                              ConstituentSemantics sem)
7147       : converter{converter}, builder{converter.getFirOpBuilder()},
7148         stmtCtx{stmtCtx}, symMap{symMap}, semant{sem} {}
7149 
7150   explicit ArrayExprLowering(Fortran::lower::AbstractConverter &converter,
7151                              Fortran::lower::StatementContext &stmtCtx,
7152                              Fortran::lower::SymMap &symMap,
7153                              ConstituentSemantics sem,
7154                              Fortran::lower::ExplicitIterSpace *expSpace,
7155                              Fortran::lower::ImplicitIterSpace *impSpace)
7156       : converter{converter}, builder{converter.getFirOpBuilder()},
7157         stmtCtx{stmtCtx}, symMap{symMap},
7158         explicitSpace(expSpace->isActive() ? expSpace : nullptr),
7159         implicitSpace(impSpace->empty() ? nullptr : impSpace), semant{sem} {
7160     // Generate any mask expressions, as necessary. This is the compute step
7161     // that creates the effective masks. See 10.2.3.2 in particular.
7162     genMasks();
7163   }
7164 
7165   mlir::Location getLoc() { return converter.getCurrentLocation(); }
7166 
7167   /// Array appears in a lhs context such that it is assigned after the rhs is
7168   /// fully evaluated.
7169   inline bool isCopyInCopyOut() {
7170     return semant == ConstituentSemantics::CopyInCopyOut;
7171   }
7172 
7173   /// Array appears in a lhs (or temp) context such that a projected,
7174   /// discontiguous subspace of the array is assigned after the rhs is fully
7175   /// evaluated. That is, the rhs array value is merged into a section of the
7176   /// lhs array.
7177   inline bool isProjectedCopyInCopyOut() {
7178     return semant == ConstituentSemantics::ProjectedCopyInCopyOut;
7179   }
7180 
7181   // ???: Do we still need this?
7182   inline bool isCustomCopyInCopyOut() {
7183     return semant == ConstituentSemantics::CustomCopyInCopyOut;
7184   }
7185 
7186   /// Array appears in a context where it must be boxed.
7187   inline bool isBoxValue() { return semant == ConstituentSemantics::BoxValue; }
7188 
7189   /// Array appears in a context where differences in the memory reference can
7190   /// be observable in the computational results. For example, an array
7191   /// element is passed to an impure procedure.
7192   inline bool isReferentiallyOpaque() {
7193     return semant == ConstituentSemantics::RefOpaque;
7194   }
7195 
7196   /// Array appears in a context where it is passed as a VALUE argument.
7197   inline bool isValueAttribute() {
7198     return semant == ConstituentSemantics::ByValueArg;
7199   }
7200 
7201   /// Can the loops over the expression be unordered?
7202   inline bool isUnordered() const { return unordered; }
7203 
7204   void setUnordered(bool b) { unordered = b; }
7205 
7206   inline bool isPointerAssignment() const { return lbounds.hasValue(); }
7207 
7208   inline bool isBoundsSpec() const {
7209     return isPointerAssignment() && !ubounds.hasValue();
7210   }
7211 
7212   inline bool isBoundsRemap() const {
7213     return isPointerAssignment() && ubounds.hasValue();
7214   }
7215 
7216   void setPointerAssignmentBounds(
7217       const llvm::SmallVector<mlir::Value> &lbs,
7218       llvm::Optional<llvm::SmallVector<mlir::Value>> ubs) {
7219     lbounds = lbs;
7220     ubounds = ubs;
7221   }
7222 
7223   Fortran::lower::AbstractConverter &converter;
7224   fir::FirOpBuilder &builder;
7225   Fortran::lower::StatementContext &stmtCtx;
7226   bool elementCtx = false;
7227   Fortran::lower::SymMap &symMap;
7228   /// The continuation to generate code to update the destination.
7229   llvm::Optional<CC> ccStoreToDest;
7230   llvm::Optional<std::function<void(llvm::ArrayRef<mlir::Value>)>> ccPrelude;
7231   llvm::Optional<std::function<fir::ArrayLoadOp(llvm::ArrayRef<mlir::Value>)>>
7232       ccLoadDest;
7233   /// The destination is the loaded array into which the results will be
7234   /// merged.
7235   fir::ArrayLoadOp destination;
7236   /// The shape of the destination.
7237   llvm::SmallVector<mlir::Value> destShape;
7238   /// List of arrays in the expression that have been loaded.
7239   llvm::SmallVector<ArrayOperand> arrayOperands;
7240   /// If there is a user-defined iteration space, explicitShape will hold the
7241   /// information from the front end.
7242   Fortran::lower::ExplicitIterSpace *explicitSpace = nullptr;
7243   Fortran::lower::ImplicitIterSpace *implicitSpace = nullptr;
7244   ConstituentSemantics semant = ConstituentSemantics::RefTransparent;
7245   /// `lbounds`, `ubounds` are used in POINTER value assignments, which may only
7246   /// occur in an explicit iteration space.
7247   llvm::Optional<llvm::SmallVector<mlir::Value>> lbounds;
7248   llvm::Optional<llvm::SmallVector<mlir::Value>> ubounds;
7249   // Can the array expression be evaluated in any order?
7250   // Will be set to false if any of the expression parts prevent this.
7251   bool unordered = true;
7252 };
7253 } // namespace
7254 
7255 fir::ExtendedValue Fortran::lower::createSomeExtendedExpression(
7256     mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7257     const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
7258     Fortran::lower::StatementContext &stmtCtx) {
7259   LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "expr: ") << '\n');
7260   return ScalarExprLowering{loc, converter, symMap, stmtCtx}.genval(expr);
7261 }
7262 
7263 fir::GlobalOp Fortran::lower::createDenseGlobal(
7264     mlir::Location loc, mlir::Type symTy, llvm::StringRef globalName,
7265     mlir::StringAttr linkage, bool isConst,
7266     const Fortran::lower::SomeExpr &expr,
7267     Fortran::lower::AbstractConverter &converter) {
7268 
7269   Fortran::lower::StatementContext stmtCtx(/*prohibited=*/true);
7270   Fortran::lower::SymMap emptyMap;
7271   InitializerData initData(/*genRawVals=*/true);
7272   ScalarExprLowering sel(loc, converter, emptyMap, stmtCtx,
7273                          /*initializer=*/&initData);
7274   sel.genval(expr);
7275 
7276   size_t sz = initData.rawVals.size();
7277   llvm::ArrayRef<mlir::Attribute> ar = {initData.rawVals.data(), sz};
7278 
7279   mlir::RankedTensorType tensorTy;
7280   auto &builder = converter.getFirOpBuilder();
7281   mlir::Type iTy = initData.rawType;
7282   if (!iTy)
7283     return 0; // array extent is probably 0 in this case, so just return 0.
7284   tensorTy = mlir::RankedTensorType::get(sz, iTy);
7285   auto init = mlir::DenseElementsAttr::get(tensorTy, ar);
7286   return builder.createGlobal(loc, symTy, globalName, linkage, init, isConst);
7287 }
7288 
7289 fir::ExtendedValue Fortran::lower::createSomeInitializerExpression(
7290     mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7291     const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
7292     Fortran::lower::StatementContext &stmtCtx) {
7293   LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "expr: ") << '\n');
7294   InitializerData initData; // needed for initializations
7295   return ScalarExprLowering{loc, converter, symMap, stmtCtx,
7296                             /*initializer=*/&initData}
7297       .genval(expr);
7298 }
7299 
7300 fir::ExtendedValue Fortran::lower::createSomeExtendedAddress(
7301     mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7302     const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
7303     Fortran::lower::StatementContext &stmtCtx) {
7304   LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "address: ") << '\n');
7305   return ScalarExprLowering(loc, converter, symMap, stmtCtx).gen(expr);
7306 }
7307 
7308 fir::ExtendedValue Fortran::lower::createInitializerAddress(
7309     mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7310     const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
7311     Fortran::lower::StatementContext &stmtCtx) {
7312   LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "address: ") << '\n');
7313   InitializerData init;
7314   return ScalarExprLowering(loc, converter, symMap, stmtCtx, &init).gen(expr);
7315 }
7316 
7317 void Fortran::lower::createSomeArrayAssignment(
7318     Fortran::lower::AbstractConverter &converter,
7319     const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
7320     Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
7321   LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "onto array: ") << '\n';
7322              rhs.AsFortran(llvm::dbgs() << "assign expression: ") << '\n';);
7323   ArrayExprLowering::lowerArrayAssignment(converter, symMap, stmtCtx, lhs, rhs);
7324 }
7325 
7326 void Fortran::lower::createSomeArrayAssignment(
7327     Fortran::lower::AbstractConverter &converter, const fir::ExtendedValue &lhs,
7328     const Fortran::lower::SomeExpr &rhs, Fortran::lower::SymMap &symMap,
7329     Fortran::lower::StatementContext &stmtCtx) {
7330   LLVM_DEBUG(llvm::dbgs() << "onto array: " << lhs << '\n';
7331              rhs.AsFortran(llvm::dbgs() << "assign expression: ") << '\n';);
7332   ArrayExprLowering::lowerArrayAssignment(converter, symMap, stmtCtx, lhs, rhs);
7333 }
7334 void Fortran::lower::createSomeArrayAssignment(
7335     Fortran::lower::AbstractConverter &converter, const fir::ExtendedValue &lhs,
7336     const fir::ExtendedValue &rhs, Fortran::lower::SymMap &symMap,
7337     Fortran::lower::StatementContext &stmtCtx) {
7338   LLVM_DEBUG(llvm::dbgs() << "onto array: " << lhs << '\n';
7339              llvm::dbgs() << "assign expression: " << rhs << '\n';);
7340   ArrayExprLowering::lowerArrayAssignment(converter, symMap, stmtCtx, lhs, rhs);
7341 }
7342 
7343 void Fortran::lower::createAnyMaskedArrayAssignment(
7344     Fortran::lower::AbstractConverter &converter,
7345     const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
7346     Fortran::lower::ExplicitIterSpace &explicitSpace,
7347     Fortran::lower::ImplicitIterSpace &implicitSpace,
7348     Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
7349   LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "onto array: ") << '\n';
7350              rhs.AsFortran(llvm::dbgs() << "assign expression: ")
7351              << " given the explicit iteration space:\n"
7352              << explicitSpace << "\n and implied mask conditions:\n"
7353              << implicitSpace << '\n';);
7354   ArrayExprLowering::lowerAnyMaskedArrayAssignment(
7355       converter, symMap, stmtCtx, lhs, rhs, explicitSpace, implicitSpace);
7356 }
7357 
7358 void Fortran::lower::createAllocatableArrayAssignment(
7359     Fortran::lower::AbstractConverter &converter,
7360     const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
7361     Fortran::lower::ExplicitIterSpace &explicitSpace,
7362     Fortran::lower::ImplicitIterSpace &implicitSpace,
7363     Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
7364   LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "defining array: ") << '\n';
7365              rhs.AsFortran(llvm::dbgs() << "assign expression: ")
7366              << " given the explicit iteration space:\n"
7367              << explicitSpace << "\n and implied mask conditions:\n"
7368              << implicitSpace << '\n';);
7369   ArrayExprLowering::lowerAllocatableArrayAssignment(
7370       converter, symMap, stmtCtx, lhs, rhs, explicitSpace, implicitSpace);
7371 }
7372 
7373 void Fortran::lower::createArrayOfPointerAssignment(
7374     Fortran::lower::AbstractConverter &converter,
7375     const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
7376     Fortran::lower::ExplicitIterSpace &explicitSpace,
7377     Fortran::lower::ImplicitIterSpace &implicitSpace,
7378     const llvm::SmallVector<mlir::Value> &lbounds,
7379     llvm::Optional<llvm::SmallVector<mlir::Value>> ubounds,
7380     Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
7381   LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "defining pointer: ") << '\n';
7382              rhs.AsFortran(llvm::dbgs() << "assign expression: ")
7383              << " given the explicit iteration space:\n"
7384              << explicitSpace << "\n and implied mask conditions:\n"
7385              << implicitSpace << '\n';);
7386   assert(explicitSpace.isActive() && "must be in FORALL construct");
7387   ArrayExprLowering::lowerArrayOfPointerAssignment(
7388       converter, symMap, stmtCtx, lhs, rhs, explicitSpace, implicitSpace,
7389       lbounds, ubounds);
7390 }
7391 
7392 fir::ExtendedValue Fortran::lower::createSomeArrayTempValue(
7393     Fortran::lower::AbstractConverter &converter,
7394     const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
7395     Fortran::lower::StatementContext &stmtCtx) {
7396   LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "array value: ") << '\n');
7397   return ArrayExprLowering::lowerNewArrayExpression(converter, symMap, stmtCtx,
7398                                                     expr);
7399 }
7400 
7401 void Fortran::lower::createLazyArrayTempValue(
7402     Fortran::lower::AbstractConverter &converter,
7403     const Fortran::lower::SomeExpr &expr, mlir::Value raggedHeader,
7404     Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
7405   LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "array value: ") << '\n');
7406   ArrayExprLowering::lowerLazyArrayExpression(converter, symMap, stmtCtx, expr,
7407                                               raggedHeader);
7408 }
7409 
7410 fir::ExtendedValue
7411 Fortran::lower::createSomeArrayBox(Fortran::lower::AbstractConverter &converter,
7412                                    const Fortran::lower::SomeExpr &expr,
7413                                    Fortran::lower::SymMap &symMap,
7414                                    Fortran::lower::StatementContext &stmtCtx) {
7415   LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "box designator: ") << '\n');
7416   return ArrayExprLowering::lowerBoxedArrayExpression(converter, symMap,
7417                                                       stmtCtx, expr);
7418 }
7419 
7420 fir::MutableBoxValue Fortran::lower::createMutableBox(
7421     mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7422     const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap) {
7423   // MutableBox lowering StatementContext does not need to be propagated
7424   // to the caller because the result value is a variable, not a temporary
7425   // expression. The StatementContext clean-up can occur before using the
7426   // resulting MutableBoxValue. Variables of all other types are handled in the
7427   // bridge.
7428   Fortran::lower::StatementContext dummyStmtCtx;
7429   return ScalarExprLowering{loc, converter, symMap, dummyStmtCtx}
7430       .genMutableBoxValue(expr);
7431 }
7432 
7433 fir::ExtendedValue Fortran::lower::createBoxValue(
7434     mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7435     const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
7436     Fortran::lower::StatementContext &stmtCtx) {
7437   if (expr.Rank() > 0 && Fortran::evaluate::IsVariable(expr) &&
7438       !Fortran::evaluate::HasVectorSubscript(expr))
7439     return Fortran::lower::createSomeArrayBox(converter, expr, symMap, stmtCtx);
7440   fir::ExtendedValue addr = Fortran::lower::createSomeExtendedAddress(
7441       loc, converter, expr, symMap, stmtCtx);
7442   return fir::BoxValue(converter.getFirOpBuilder().createBox(loc, addr));
7443 }
7444 
7445 mlir::Value Fortran::lower::createSubroutineCall(
7446     AbstractConverter &converter, const evaluate::ProcedureRef &call,
7447     ExplicitIterSpace &explicitIterSpace, ImplicitIterSpace &implicitIterSpace,
7448     SymMap &symMap, StatementContext &stmtCtx, bool isUserDefAssignment) {
7449   mlir::Location loc = converter.getCurrentLocation();
7450 
7451   if (isUserDefAssignment) {
7452     assert(call.arguments().size() == 2);
7453     const auto *lhs = call.arguments()[0].value().UnwrapExpr();
7454     const auto *rhs = call.arguments()[1].value().UnwrapExpr();
7455     assert(lhs && rhs &&
7456            "user defined assignment arguments must be expressions");
7457     if (call.IsElemental() && lhs->Rank() > 0) {
7458       // Elemental user defined assignment has special requirements to deal with
7459       // LHS/RHS overlaps. See 10.2.1.5 p2.
7460       ArrayExprLowering::lowerElementalUserAssignment(
7461           converter, symMap, stmtCtx, explicitIterSpace, implicitIterSpace,
7462           call);
7463     } else if (explicitIterSpace.isActive() && lhs->Rank() == 0) {
7464       // Scalar defined assignment (elemental or not) in a FORALL context.
7465       mlir::func::FuncOp func =
7466           Fortran::lower::CallerInterface(call, converter).getFuncOp();
7467       ArrayExprLowering::lowerScalarUserAssignment(
7468           converter, symMap, stmtCtx, explicitIterSpace, func, *lhs, *rhs);
7469     } else if (explicitIterSpace.isActive()) {
7470       // TODO: need to array fetch/modify sub-arrays?
7471       TODO(loc, "non elemental user defined array assignment inside FORALL");
7472     } else {
7473       if (!implicitIterSpace.empty())
7474         fir::emitFatalError(
7475             loc,
7476             "C1032: user defined assignment inside WHERE must be elemental");
7477       // Non elemental user defined assignment outside of FORALL and WHERE.
7478       // FIXME: The non elemental user defined assignment case with array
7479       // arguments must be take into account potential overlap. So far the front
7480       // end does not add parentheses around the RHS argument in the call as it
7481       // should according to 15.4.3.4.3 p2.
7482       Fortran::lower::createSomeExtendedExpression(
7483           loc, converter, toEvExpr(call), symMap, stmtCtx);
7484     }
7485     return {};
7486   }
7487 
7488   assert(implicitIterSpace.empty() && !explicitIterSpace.isActive() &&
7489          "subroutine calls are not allowed inside WHERE and FORALL");
7490 
7491   if (isElementalProcWithArrayArgs(call)) {
7492     ArrayExprLowering::lowerElementalSubroutine(converter, symMap, stmtCtx,
7493                                                 toEvExpr(call));
7494     return {};
7495   }
7496   // Simple subroutine call, with potential alternate return.
7497   auto res = Fortran::lower::createSomeExtendedExpression(
7498       loc, converter, toEvExpr(call), symMap, stmtCtx);
7499   return fir::getBase(res);
7500 }
7501 
7502 template <typename A>
7503 fir::ArrayLoadOp genArrayLoad(mlir::Location loc,
7504                               Fortran::lower::AbstractConverter &converter,
7505                               fir::FirOpBuilder &builder, const A *x,
7506                               Fortran::lower::SymMap &symMap,
7507                               Fortran::lower::StatementContext &stmtCtx) {
7508   auto exv = ScalarExprLowering{loc, converter, symMap, stmtCtx}.gen(*x);
7509   mlir::Value addr = fir::getBase(exv);
7510   mlir::Value shapeOp = builder.createShape(loc, exv);
7511   mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(addr.getType());
7512   return builder.create<fir::ArrayLoadOp>(loc, arrTy, addr, shapeOp,
7513                                           /*slice=*/mlir::Value{},
7514                                           fir::getTypeParams(exv));
7515 }
7516 template <>
7517 fir::ArrayLoadOp
7518 genArrayLoad(mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7519              fir::FirOpBuilder &builder, const Fortran::evaluate::ArrayRef *x,
7520              Fortran::lower::SymMap &symMap,
7521              Fortran::lower::StatementContext &stmtCtx) {
7522   if (x->base().IsSymbol())
7523     return genArrayLoad(loc, converter, builder, &getLastSym(x->base()), symMap,
7524                         stmtCtx);
7525   return genArrayLoad(loc, converter, builder, &x->base().GetComponent(),
7526                       symMap, stmtCtx);
7527 }
7528 
7529 void Fortran::lower::createArrayLoads(
7530     Fortran::lower::AbstractConverter &converter,
7531     Fortran::lower::ExplicitIterSpace &esp, Fortran::lower::SymMap &symMap) {
7532   std::size_t counter = esp.getCounter();
7533   fir::FirOpBuilder &builder = converter.getFirOpBuilder();
7534   mlir::Location loc = converter.getCurrentLocation();
7535   Fortran::lower::StatementContext &stmtCtx = esp.stmtContext();
7536   // Gen the fir.array_load ops.
7537   auto genLoad = [&](const auto *x) -> fir::ArrayLoadOp {
7538     return genArrayLoad(loc, converter, builder, x, symMap, stmtCtx);
7539   };
7540   if (esp.lhsBases[counter].hasValue()) {
7541     auto &base = esp.lhsBases[counter].getValue();
7542     auto load = std::visit(genLoad, base);
7543     esp.initialArgs.push_back(load);
7544     esp.resetInnerArgs();
7545     esp.bindLoad(base, load);
7546   }
7547   for (const auto &base : esp.rhsBases[counter])
7548     esp.bindLoad(base, std::visit(genLoad, base));
7549 }
7550 
7551 void Fortran::lower::createArrayMergeStores(
7552     Fortran::lower::AbstractConverter &converter,
7553     Fortran::lower::ExplicitIterSpace &esp) {
7554   fir::FirOpBuilder &builder = converter.getFirOpBuilder();
7555   mlir::Location loc = converter.getCurrentLocation();
7556   builder.setInsertionPointAfter(esp.getOuterLoop());
7557   // Gen the fir.array_merge_store ops for all LHS arrays.
7558   for (auto i : llvm::enumerate(esp.getOuterLoop().getResults()))
7559     if (llvm::Optional<fir::ArrayLoadOp> ldOpt = esp.getLhsLoad(i.index())) {
7560       fir::ArrayLoadOp load = ldOpt.getValue();
7561       builder.create<fir::ArrayMergeStoreOp>(loc, load, i.value(),
7562                                              load.getMemref(), load.getSlice(),
7563                                              load.getTypeparams());
7564     }
7565   if (esp.loopCleanup.hasValue()) {
7566     esp.loopCleanup.getValue()(builder);
7567     esp.loopCleanup = llvm::None;
7568   }
7569   esp.initialArgs.clear();
7570   esp.innerArgs.clear();
7571   esp.outerLoop = llvm::None;
7572   esp.resetBindings();
7573   esp.incrementCounter();
7574 }
7575 
7576 mlir::Value Fortran::lower::genMaxWithZero(fir::FirOpBuilder &builder,
7577                                            mlir::Location loc,
7578                                            mlir::Value value) {
7579   mlir::Value zero = builder.createIntegerConstant(loc, value.getType(), 0);
7580   if (mlir::Operation *definingOp = value.getDefiningOp())
7581     if (auto cst = mlir::dyn_cast<mlir::arith::ConstantOp>(definingOp))
7582       if (auto intAttr = cst.getValue().dyn_cast<mlir::IntegerAttr>())
7583         return intAttr.getInt() < 0 ? zero : value;
7584   return Fortran::lower::genMax(builder, loc,
7585                                 llvm::SmallVector<mlir::Value>{value, zero});
7586 }
7587