1 //===-- Bridge.cpp -- bridge to lower to MLIR -----------------------------===//
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/Bridge.h"
14 #include "flang/Lower/Allocatable.h"
15 #include "flang/Lower/CallInterface.h"
16 #include "flang/Lower/Coarray.h"
17 #include "flang/Lower/ConvertExpr.h"
18 #include "flang/Lower/ConvertType.h"
19 #include "flang/Lower/ConvertVariable.h"
20 #include "flang/Lower/HostAssociations.h"
21 #include "flang/Lower/IO.h"
22 #include "flang/Lower/IterationSpace.h"
23 #include "flang/Lower/Mangler.h"
24 #include "flang/Lower/OpenACC.h"
25 #include "flang/Lower/OpenMP.h"
26 #include "flang/Lower/PFTBuilder.h"
27 #include "flang/Lower/Runtime.h"
28 #include "flang/Lower/StatementContext.h"
29 #include "flang/Lower/Support/Utils.h"
30 #include "flang/Lower/Todo.h"
31 #include "flang/Optimizer/Builder/BoxValue.h"
32 #include "flang/Optimizer/Builder/Character.h"
33 #include "flang/Optimizer/Builder/FIRBuilder.h"
34 #include "flang/Optimizer/Builder/Runtime/Character.h"
35 #include "flang/Optimizer/Builder/Runtime/Ragged.h"
36 #include "flang/Optimizer/Dialect/FIRAttr.h"
37 #include "flang/Optimizer/Dialect/FIRDialect.h"
38 #include "flang/Optimizer/Dialect/FIROps.h"
39 #include "flang/Optimizer/Support/FIRContext.h"
40 #include "flang/Optimizer/Support/FatalError.h"
41 #include "flang/Optimizer/Support/InternalNames.h"
42 #include "flang/Optimizer/Transforms/Passes.h"
43 #include "flang/Parser/parse-tree.h"
44 #include "flang/Runtime/iostat.h"
45 #include "flang/Semantics/tools.h"
46 #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
47 #include "mlir/IR/PatternMatch.h"
48 #include "mlir/Parser/Parser.h"
49 #include "mlir/Transforms/RegionUtils.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 
54 #define DEBUG_TYPE "flang-lower-bridge"
55 
56 static llvm::cl::opt<bool> dumpBeforeFir(
57     "fdebug-dump-pre-fir", llvm::cl::init(false),
58     llvm::cl::desc("dump the Pre-FIR tree prior to FIR generation"));
59 
60 static llvm::cl::opt<bool> forceLoopToExecuteOnce(
61     "always-execute-loop-body", llvm::cl::init(false),
62     llvm::cl::desc("force the body of a loop to execute at least once"));
63 
64 namespace {
65 /// Information for generating a structured or unstructured increment loop.
66 struct IncrementLoopInfo {
67   template <typename T>
68   explicit IncrementLoopInfo(Fortran::semantics::Symbol &sym, const T &lower,
69                              const T &upper, const std::optional<T> &step,
70                              bool isUnordered = false)
71       : loopVariableSym{sym}, lowerExpr{Fortran::semantics::GetExpr(lower)},
72         upperExpr{Fortran::semantics::GetExpr(upper)},
73         stepExpr{Fortran::semantics::GetExpr(step)}, isUnordered{isUnordered} {}
74 
75   IncrementLoopInfo(IncrementLoopInfo &&) = default;
76   IncrementLoopInfo &operator=(IncrementLoopInfo &&x) { return x; }
77 
78   bool isStructured() const { return !headerBlock; }
79 
80   mlir::Type getLoopVariableType() const {
81     assert(loopVariable && "must be set");
82     return fir::unwrapRefType(loopVariable.getType());
83   }
84 
85   // Data members common to both structured and unstructured loops.
86   const Fortran::semantics::Symbol &loopVariableSym;
87   const Fortran::lower::SomeExpr *lowerExpr;
88   const Fortran::lower::SomeExpr *upperExpr;
89   const Fortran::lower::SomeExpr *stepExpr;
90   bool isUnordered; // do concurrent, forall
91   mlir::Value loopVariable = nullptr;
92   mlir::Value stepValue = nullptr; // possible uses in multiple blocks
93 
94   // Data members for structured loops.
95   fir::DoLoopOp doLoop = nullptr;
96 
97   // Data members for unstructured loops.
98   mlir::Value tripVariable = nullptr;
99   mlir::Block *headerBlock = nullptr; // loop entry and test block
100   mlir::Block *bodyBlock = nullptr;   // first loop body block
101   mlir::Block *exitBlock = nullptr;   // loop exit target block
102 };
103 
104 /// Helper class to generate the runtime type info global data. This data
105 /// is required to describe the derived type to the runtime so that it can
106 /// operate over it. It must be ensured this data will be generated for every
107 /// derived type lowered in the current translated unit. However, this data
108 /// cannot be generated before FuncOp have been created for functions since the
109 /// initializers may take their address (e.g for type bound procedures). This
110 /// class allows registering all the required runtime type info while it is not
111 /// possible to create globals, and to generate this data after function
112 /// lowering.
113 class RuntimeTypeInfoConverter {
114   /// Store the location and symbols of derived type info to be generated.
115   /// The location of the derived type instantiation is also stored because
116   /// runtime type descriptor symbol are compiler generated and cannot be mapped
117   /// to user code on their own.
118   struct TypeInfoSymbol {
119     Fortran::semantics::SymbolRef symbol;
120     mlir::Location loc;
121   };
122 
123 public:
124   void registerTypeInfoSymbol(Fortran::lower::AbstractConverter &converter,
125                               mlir::Location loc,
126                               Fortran::semantics::SymbolRef typeInfoSym) {
127     if (seen.contains(typeInfoSym))
128       return;
129     seen.insert(typeInfoSym);
130     if (!skipRegistration) {
131       registeredTypeInfoSymbols.emplace_back(TypeInfoSymbol{typeInfoSym, loc});
132       return;
133     }
134     // Once the registration is closed, symbols cannot be added to the
135     // registeredTypeInfoSymbols list because it may be iterated over.
136     // However, after registration is closed, it is safe to directly generate
137     // the globals because all FuncOps whose addresses may be required by the
138     // initializers have been generated.
139     Fortran::lower::createRuntimeTypeInfoGlobal(converter, loc,
140                                                 typeInfoSym.get());
141   }
142 
143   void createTypeInfoGlobals(Fortran::lower::AbstractConverter &converter) {
144     skipRegistration = true;
145     for (const TypeInfoSymbol &info : registeredTypeInfoSymbols)
146       Fortran::lower::createRuntimeTypeInfoGlobal(converter, info.loc,
147                                                   info.symbol.get());
148     registeredTypeInfoSymbols.clear();
149   }
150 
151 private:
152   /// Store the runtime type descriptors that will be required for the
153   /// derived type that have been converted to FIR derived types.
154   llvm::SmallVector<TypeInfoSymbol> registeredTypeInfoSymbols;
155   /// Create derived type runtime info global immediately without storing the
156   /// symbol in registeredTypeInfoSymbols.
157   bool skipRegistration = false;
158   /// Track symbols symbols processed during and after the registration
159   /// to avoid infinite loops between type conversions and global variable
160   /// creation.
161   llvm::SmallSetVector<Fortran::semantics::SymbolRef, 64> seen;
162 };
163 
164 using IncrementLoopNestInfo = llvm::SmallVector<IncrementLoopInfo>;
165 } // namespace
166 
167 //===----------------------------------------------------------------------===//
168 // FirConverter
169 //===----------------------------------------------------------------------===//
170 
171 namespace {
172 
173 /// Traverse the pre-FIR tree (PFT) to generate the FIR dialect of MLIR.
174 class FirConverter : public Fortran::lower::AbstractConverter {
175 public:
176   explicit FirConverter(Fortran::lower::LoweringBridge &bridge)
177       : bridge{bridge}, foldingContext{bridge.createFoldingContext()} {}
178   virtual ~FirConverter() = default;
179 
180   /// Convert the PFT to FIR.
181   void run(Fortran::lower::pft::Program &pft) {
182     // Preliminary translation pass.
183 
184     // - Lower common blocks from the PFT common block list that contains a
185     // consolidated list of the common blocks (with the initialization if any in
186     // the Program, and with the common block biggest size in all its
187     // appearance). This is done before lowering any scope declarations because
188     // it is not know at the local scope level what MLIR type common blocks
189     // should have to suit all its usage in the compilation unit.
190     lowerCommonBlocks(pft.getCommonBlocks());
191 
192     //  - Declare all functions that have definitions so that definition
193     //    signatures prevail over call site signatures.
194     //  - Define module variables and OpenMP/OpenACC declarative construct so
195     //    that they are available before lowering any function that may use
196     //    them.
197     for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) {
198       std::visit(Fortran::common::visitors{
199                      [&](Fortran::lower::pft::FunctionLikeUnit &f) {
200                        declareFunction(f);
201                      },
202                      [&](Fortran::lower::pft::ModuleLikeUnit &m) {
203                        lowerModuleDeclScope(m);
204                        for (Fortran::lower::pft::FunctionLikeUnit &f :
205                             m.nestedFunctions)
206                          declareFunction(f);
207                      },
208                      [&](Fortran::lower::pft::BlockDataUnit &b) {},
209                      [&](Fortran::lower::pft::CompilerDirectiveUnit &d) {},
210                  },
211                  u);
212     }
213 
214     // Primary translation pass.
215     for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) {
216       std::visit(
217           Fortran::common::visitors{
218               [&](Fortran::lower::pft::FunctionLikeUnit &f) { lowerFunc(f); },
219               [&](Fortran::lower::pft::ModuleLikeUnit &m) { lowerMod(m); },
220               [&](Fortran::lower::pft::BlockDataUnit &b) {},
221               [&](Fortran::lower::pft::CompilerDirectiveUnit &d) {
222                 setCurrentPosition(
223                     d.get<Fortran::parser::CompilerDirective>().source);
224                 mlir::emitWarning(toLocation(),
225                                   "ignoring all compiler directives");
226               },
227           },
228           u);
229     }
230 
231     /// Once all the code has been translated, create runtime type info
232     /// global data structure for the derived types that have been
233     /// processed.
234     createGlobalOutsideOfFunctionLowering(
235         [&]() { runtimeTypeInfoConverter.createTypeInfoGlobals(*this); });
236   }
237 
238   /// Declare a function.
239   void declareFunction(Fortran::lower::pft::FunctionLikeUnit &funit) {
240     setCurrentPosition(funit.getStartingSourceLoc());
241     for (int entryIndex = 0, last = funit.entryPointList.size();
242          entryIndex < last; ++entryIndex) {
243       funit.setActiveEntry(entryIndex);
244       // Calling CalleeInterface ctor will build a declaration
245       // mlir::func::FuncOp with no other side effects.
246       // TODO: when doing some compiler profiling on real apps, it may be worth
247       // to check it's better to save the CalleeInterface instead of recomputing
248       // it later when lowering the body. CalleeInterface ctor should be linear
249       // with the number of arguments, so it is not awful to do it that way for
250       // now, but the linear coefficient might be non negligible. Until
251       // measured, stick to the solution that impacts the code less.
252       Fortran::lower::CalleeInterface{funit, *this};
253     }
254     funit.setActiveEntry(0);
255 
256     // Compute the set of host associated entities from the nested functions.
257     llvm::SetVector<const Fortran::semantics::Symbol *> escapeHost;
258     for (Fortran::lower::pft::FunctionLikeUnit &f : funit.nestedFunctions)
259       collectHostAssociatedVariables(f, escapeHost);
260     funit.setHostAssociatedSymbols(escapeHost);
261 
262     // Declare internal procedures
263     for (Fortran::lower::pft::FunctionLikeUnit &f : funit.nestedFunctions)
264       declareFunction(f);
265   }
266 
267   /// Collects the canonical list of all host associated symbols. These bindings
268   /// must be aggregated into a tuple which can then be added to each of the
269   /// internal procedure declarations and passed at each call site.
270   void collectHostAssociatedVariables(
271       Fortran::lower::pft::FunctionLikeUnit &funit,
272       llvm::SetVector<const Fortran::semantics::Symbol *> &escapees) {
273     const Fortran::semantics::Scope *internalScope =
274         funit.getSubprogramSymbol().scope();
275     assert(internalScope && "internal procedures symbol must create a scope");
276     auto addToListIfEscapee = [&](const Fortran::semantics::Symbol &sym) {
277       const Fortran::semantics::Symbol &ultimate = sym.GetUltimate();
278       const auto *namelistDetails =
279           ultimate.detailsIf<Fortran::semantics::NamelistDetails>();
280       if (ultimate.has<Fortran::semantics::ObjectEntityDetails>() ||
281           Fortran::semantics::IsProcedurePointer(ultimate) ||
282           Fortran::semantics::IsDummy(sym) || namelistDetails) {
283         const Fortran::semantics::Scope &ultimateScope = ultimate.owner();
284         if (ultimateScope.kind() ==
285                 Fortran::semantics::Scope::Kind::MainProgram ||
286             ultimateScope.kind() == Fortran::semantics::Scope::Kind::Subprogram)
287           if (ultimateScope != *internalScope &&
288               ultimateScope.Contains(*internalScope)) {
289             if (namelistDetails) {
290               // So far, namelist symbols are processed on the fly in IO and
291               // the related namelist data structure is not added to the symbol
292               // map, so it cannot be passed to the internal procedures.
293               // Instead, all the symbols of the host namelist used in the
294               // internal procedure must be considered as host associated so
295               // that IO lowering can find them when needed.
296               for (const auto &namelistObject : namelistDetails->objects())
297                 escapees.insert(&*namelistObject);
298             } else {
299               escapees.insert(&ultimate);
300             }
301           }
302       }
303     };
304     Fortran::lower::pft::visitAllSymbols(funit, addToListIfEscapee);
305   }
306 
307   //===--------------------------------------------------------------------===//
308   // AbstractConverter overrides
309   //===--------------------------------------------------------------------===//
310 
311   mlir::Value getSymbolAddress(Fortran::lower::SymbolRef sym) override final {
312     return lookupSymbol(sym).getAddr();
313   }
314 
315   mlir::Value impliedDoBinding(llvm::StringRef name) override final {
316     mlir::Value val = localSymbols.lookupImpliedDo(name);
317     if (!val)
318       fir::emitFatalError(toLocation(), "ac-do-variable has no binding");
319     return val;
320   }
321 
322   void copySymbolBinding(Fortran::lower::SymbolRef src,
323                          Fortran::lower::SymbolRef target) override final {
324     localSymbols.addSymbol(target, lookupSymbol(src).toExtendedValue());
325   }
326 
327   /// Add the symbol binding to the inner-most level of the symbol map and
328   /// return true if it is not already present. Otherwise, return false.
329   bool bindIfNewSymbol(Fortran::lower::SymbolRef sym,
330                        const fir::ExtendedValue &exval) {
331     if (shallowLookupSymbol(sym))
332       return false;
333     bindSymbol(sym, exval);
334     return true;
335   }
336 
337   void bindSymbol(Fortran::lower::SymbolRef sym,
338                   const fir::ExtendedValue &exval) override final {
339     localSymbols.addSymbol(sym, exval, /*forced=*/true);
340   }
341 
342   bool lookupLabelSet(Fortran::lower::SymbolRef sym,
343                       Fortran::lower::pft::LabelSet &labelSet) override final {
344     Fortran::lower::pft::FunctionLikeUnit &owningProc =
345         *getEval().getOwningProcedure();
346     auto iter = owningProc.assignSymbolLabelMap.find(sym);
347     if (iter == owningProc.assignSymbolLabelMap.end())
348       return false;
349     labelSet = iter->second;
350     return true;
351   }
352 
353   Fortran::lower::pft::Evaluation *
354   lookupLabel(Fortran::lower::pft::Label label) override final {
355     Fortran::lower::pft::FunctionLikeUnit &owningProc =
356         *getEval().getOwningProcedure();
357     auto iter = owningProc.labelEvaluationMap.find(label);
358     if (iter == owningProc.labelEvaluationMap.end())
359       return nullptr;
360     return iter->second;
361   }
362 
363   fir::ExtendedValue genExprAddr(const Fortran::lower::SomeExpr &expr,
364                                  Fortran::lower::StatementContext &context,
365                                  mlir::Location *loc = nullptr) override final {
366     return Fortran::lower::createSomeExtendedAddress(
367         loc ? *loc : toLocation(), *this, expr, localSymbols, context);
368   }
369   fir::ExtendedValue
370   genExprValue(const Fortran::lower::SomeExpr &expr,
371                Fortran::lower::StatementContext &context,
372                mlir::Location *loc = nullptr) override final {
373     return Fortran::lower::createSomeExtendedExpression(
374         loc ? *loc : toLocation(), *this, expr, localSymbols, context);
375   }
376   fir::MutableBoxValue
377   genExprMutableBox(mlir::Location loc,
378                     const Fortran::lower::SomeExpr &expr) override final {
379     return Fortran::lower::createMutableBox(loc, *this, expr, localSymbols);
380   }
381   fir::ExtendedValue genExprBox(const Fortran::lower::SomeExpr &expr,
382                                 Fortran::lower::StatementContext &context,
383                                 mlir::Location loc) override final {
384     return Fortran::lower::createBoxValue(loc, *this, expr, localSymbols,
385                                           context);
386   }
387 
388   Fortran::evaluate::FoldingContext &getFoldingContext() override final {
389     return foldingContext;
390   }
391 
392   mlir::Type genType(const Fortran::lower::SomeExpr &expr) override final {
393     return Fortran::lower::translateSomeExprToFIRType(*this, expr);
394   }
395   mlir::Type genType(const Fortran::lower::pft::Variable &var) override final {
396     return Fortran::lower::translateVariableToFIRType(*this, var);
397   }
398   mlir::Type genType(Fortran::lower::SymbolRef sym) override final {
399     return Fortran::lower::translateSymbolToFIRType(*this, sym);
400   }
401   mlir::Type
402   genType(Fortran::common::TypeCategory tc, int kind,
403           llvm::ArrayRef<std::int64_t> lenParameters) override final {
404     return Fortran::lower::getFIRType(&getMLIRContext(), tc, kind,
405                                       lenParameters);
406   }
407   mlir::Type
408   genType(const Fortran::semantics::DerivedTypeSpec &tySpec) override final {
409     return Fortran::lower::translateDerivedTypeToFIRType(*this, tySpec);
410   }
411   mlir::Type genType(Fortran::common::TypeCategory tc) override final {
412     return Fortran::lower::getFIRType(
413         &getMLIRContext(), tc, bridge.getDefaultKinds().GetDefaultKind(tc),
414         llvm::None);
415   }
416 
417   bool createHostAssociateVarClone(
418       const Fortran::semantics::Symbol &sym) override final {
419     mlir::Location loc = genLocation(sym.name());
420     mlir::Type symType = genType(sym);
421     const auto *details = sym.detailsIf<Fortran::semantics::HostAssocDetails>();
422     assert(details && "No host-association found");
423     const Fortran::semantics::Symbol &hsym = details->symbol();
424     Fortran::lower::SymbolBox hsb = lookupSymbol(hsym);
425 
426     auto allocate = [&](llvm::ArrayRef<mlir::Value> shape,
427                         llvm::ArrayRef<mlir::Value> typeParams) -> mlir::Value {
428       mlir::Value allocVal = builder->allocateLocal(
429           loc, symType, mangleName(sym), toStringRef(sym.GetUltimate().name()),
430           /*pinned=*/true, shape, typeParams,
431           sym.GetUltimate().attrs().test(Fortran::semantics::Attr::TARGET));
432       return allocVal;
433     };
434 
435     fir::ExtendedValue hexv = getExtendedValue(hsb);
436     fir::ExtendedValue exv = hexv.match(
437         [&](const fir::BoxValue &box) -> fir::ExtendedValue {
438           const Fortran::semantics::DeclTypeSpec *type = sym.GetType();
439           if (type && type->IsPolymorphic())
440             TODO(loc, "create polymorphic host associated copy");
441           // Create a contiguous temp with the same shape and length as
442           // the original variable described by a fir.box.
443           llvm::SmallVector<mlir::Value> extents =
444               fir::factory::getExtents(*builder, loc, hexv);
445           if (box.isDerivedWithLengthParameters())
446             TODO(loc, "get length parameters from derived type BoxValue");
447           if (box.isCharacter()) {
448             mlir::Value len = fir::factory::readCharLen(*builder, loc, box);
449             mlir::Value temp = allocate(extents, {len});
450             return fir::CharArrayBoxValue{temp, len, extents};
451           }
452           return fir::ArrayBoxValue{allocate(extents, {}), extents};
453         },
454         [&](const fir::MutableBoxValue &box) -> fir::ExtendedValue {
455           // Allocate storage for a pointer/allocatble descriptor.
456           // No shape/lengths to be passed to the alloca.
457           return fir::MutableBoxValue(allocate({}, {}),
458                                       box.nonDeferredLenParams(), {});
459         },
460         [&](const auto &) -> fir::ExtendedValue {
461           mlir::Value temp =
462               allocate(fir::factory::getExtents(*builder, loc, hexv),
463                        fir::getTypeParams(hexv));
464           return fir::substBase(hexv, temp);
465         });
466 
467     return bindIfNewSymbol(sym, exv);
468   }
469 
470   void
471   copyHostAssociateVar(const Fortran::semantics::Symbol &sym) override final {
472     // 1) Fetch the original copy of the variable.
473     assert(sym.has<Fortran::semantics::HostAssocDetails>() &&
474            "No host-association found");
475     const Fortran::semantics::Symbol &hsym = sym.GetUltimate();
476     Fortran::lower::SymbolBox hsb = lookupSymbol(hsym);
477     fir::ExtendedValue hexv = getExtendedValue(hsb);
478 
479     // 2) Create a copy that will mask the original.
480     createHostAssociateVarClone(sym);
481     Fortran::lower::SymbolBox sb = lookupSymbol(sym);
482     fir::ExtendedValue exv = getExtendedValue(sb);
483 
484     // 3) Perform the assignment.
485     mlir::Location loc = genLocation(sym.name());
486     mlir::Type symType = genType(sym);
487     if (auto seqTy = symType.dyn_cast<fir::SequenceType>()) {
488       Fortran::lower::StatementContext stmtCtx;
489       Fortran::lower::createSomeArrayAssignment(*this, exv, hexv, localSymbols,
490                                                 stmtCtx);
491       stmtCtx.finalize();
492     } else if (hexv.getBoxOf<fir::CharBoxValue>()) {
493       fir::factory::CharacterExprHelper{*builder, loc}.createAssign(exv, hexv);
494     } else if (hexv.getBoxOf<fir::MutableBoxValue>()) {
495       TODO(loc, "firstprivatisation of allocatable variables");
496     } else {
497       auto loadVal = builder->create<fir::LoadOp>(loc, fir::getBase(hexv));
498       builder->create<fir::StoreOp>(loc, loadVal, fir::getBase(exv));
499     }
500   }
501 
502   //===--------------------------------------------------------------------===//
503   // Utility methods
504   //===--------------------------------------------------------------------===//
505 
506   mlir::Location getCurrentLocation() override final { return toLocation(); }
507 
508   /// Generate a dummy location.
509   mlir::Location genUnknownLocation() override final {
510     // Note: builder may not be instantiated yet
511     return mlir::UnknownLoc::get(&getMLIRContext());
512   }
513 
514   /// Generate a `Location` from the `CharBlock`.
515   mlir::Location
516   genLocation(const Fortran::parser::CharBlock &block) override final {
517     if (const Fortran::parser::AllCookedSources *cooked =
518             bridge.getCookedSource()) {
519       if (std::optional<std::pair<Fortran::parser::SourcePosition,
520                                   Fortran::parser::SourcePosition>>
521               loc = cooked->GetSourcePositionRange(block)) {
522         // loc is a pair (begin, end); use the beginning position
523         Fortran::parser::SourcePosition &filePos = loc->first;
524         return mlir::FileLineColLoc::get(&getMLIRContext(), filePos.file.path(),
525                                          filePos.line, filePos.column);
526       }
527     }
528     return genUnknownLocation();
529   }
530 
531   fir::FirOpBuilder &getFirOpBuilder() override final { return *builder; }
532 
533   mlir::ModuleOp &getModuleOp() override final { return bridge.getModule(); }
534 
535   mlir::MLIRContext &getMLIRContext() override final {
536     return bridge.getMLIRContext();
537   }
538   std::string
539   mangleName(const Fortran::semantics::Symbol &symbol) override final {
540     return Fortran::lower::mangle::mangleName(symbol);
541   }
542 
543   const fir::KindMapping &getKindMap() override final {
544     return bridge.getKindMap();
545   }
546 
547   mlir::Value hostAssocTupleValue() override final { return hostAssocTuple; }
548 
549   /// Record a binding for the ssa-value of the tuple for this function.
550   void bindHostAssocTuple(mlir::Value val) override final {
551     assert(!hostAssocTuple && val);
552     hostAssocTuple = val;
553   }
554 
555   void registerRuntimeTypeInfo(
556       mlir::Location loc,
557       Fortran::lower::SymbolRef typeInfoSym) override final {
558     runtimeTypeInfoConverter.registerTypeInfoSymbol(*this, loc, typeInfoSym);
559   }
560 
561 private:
562   FirConverter() = delete;
563   FirConverter(const FirConverter &) = delete;
564   FirConverter &operator=(const FirConverter &) = delete;
565 
566   //===--------------------------------------------------------------------===//
567   // Helper member functions
568   //===--------------------------------------------------------------------===//
569 
570   mlir::Value createFIRExpr(mlir::Location loc,
571                             const Fortran::lower::SomeExpr *expr,
572                             Fortran::lower::StatementContext &stmtCtx) {
573     return fir::getBase(genExprValue(*expr, stmtCtx, &loc));
574   }
575 
576   /// Find the symbol in the local map or return null.
577   Fortran::lower::SymbolBox
578   lookupSymbol(const Fortran::semantics::Symbol &sym) {
579     if (Fortran::lower::SymbolBox v = localSymbols.lookupSymbol(sym))
580       return v;
581     return {};
582   }
583 
584   /// Find the symbol in the inner-most level of the local map or return null.
585   Fortran::lower::SymbolBox
586   shallowLookupSymbol(const Fortran::semantics::Symbol &sym) {
587     if (Fortran::lower::SymbolBox v = localSymbols.shallowLookupSymbol(sym))
588       return v;
589     return {};
590   }
591 
592   /// Add the symbol to the local map and return `true`. If the symbol is
593   /// already in the map and \p forced is `false`, the map is not updated.
594   /// Instead the value `false` is returned.
595   bool addSymbol(const Fortran::semantics::SymbolRef sym, mlir::Value val,
596                  bool forced = false) {
597     if (!forced && lookupSymbol(sym))
598       return false;
599     localSymbols.addSymbol(sym, val, forced);
600     return true;
601   }
602 
603   bool addCharSymbol(const Fortran::semantics::SymbolRef sym, mlir::Value val,
604                      mlir::Value len, bool forced = false) {
605     if (!forced && lookupSymbol(sym))
606       return false;
607     // TODO: ensure val type is fir.array<len x fir.char<kind>> like. Insert
608     // cast if needed.
609     localSymbols.addCharSymbol(sym, val, len, forced);
610     return true;
611   }
612 
613   fir::ExtendedValue getExtendedValue(Fortran::lower::SymbolBox sb) {
614     return sb.match(
615         [&](const Fortran::lower::SymbolBox::PointerOrAllocatable &box) {
616           return fir::factory::genMutableBoxRead(*builder, getCurrentLocation(),
617                                                  box);
618         },
619         [&sb](auto &) { return sb.toExtendedValue(); });
620   }
621 
622   /// Generate the address of loop variable \p sym.
623   mlir::Value genLoopVariableAddress(mlir::Location loc,
624                                      const Fortran::semantics::Symbol &sym) {
625     assert(lookupSymbol(sym) && "loop control variable must already be in map");
626     Fortran::lower::StatementContext stmtCtx;
627     return fir::getBase(
628         genExprAddr(Fortran::evaluate::AsGenericExpr(sym).value(), stmtCtx));
629   }
630 
631   static bool isNumericScalarCategory(Fortran::common::TypeCategory cat) {
632     return cat == Fortran::common::TypeCategory::Integer ||
633            cat == Fortran::common::TypeCategory::Real ||
634            cat == Fortran::common::TypeCategory::Complex ||
635            cat == Fortran::common::TypeCategory::Logical;
636   }
637   static bool isLogicalCategory(Fortran::common::TypeCategory cat) {
638     return cat == Fortran::common::TypeCategory::Logical;
639   }
640   static bool isCharacterCategory(Fortran::common::TypeCategory cat) {
641     return cat == Fortran::common::TypeCategory::Character;
642   }
643   static bool isDerivedCategory(Fortran::common::TypeCategory cat) {
644     return cat == Fortran::common::TypeCategory::Derived;
645   }
646 
647   /// Insert a new block before \p block.  Leave the insertion point unchanged.
648   mlir::Block *insertBlock(mlir::Block *block) {
649     mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
650     mlir::Block *newBlock = builder->createBlock(block);
651     builder->restoreInsertionPoint(insertPt);
652     return newBlock;
653   }
654 
655   mlir::Block *blockOfLabel(Fortran::lower::pft::Evaluation &eval,
656                             Fortran::parser::Label label) {
657     const Fortran::lower::pft::LabelEvalMap &labelEvaluationMap =
658         eval.getOwningProcedure()->labelEvaluationMap;
659     const auto iter = labelEvaluationMap.find(label);
660     assert(iter != labelEvaluationMap.end() && "label missing from map");
661     mlir::Block *block = iter->second->block;
662     assert(block && "missing labeled evaluation block");
663     return block;
664   }
665 
666   void genFIRBranch(mlir::Block *targetBlock) {
667     assert(targetBlock && "missing unconditional target block");
668     builder->create<mlir::cf::BranchOp>(toLocation(), targetBlock);
669   }
670 
671   void genFIRConditionalBranch(mlir::Value cond, mlir::Block *trueTarget,
672                                mlir::Block *falseTarget) {
673     assert(trueTarget && "missing conditional branch true block");
674     assert(falseTarget && "missing conditional branch false block");
675     mlir::Location loc = toLocation();
676     mlir::Value bcc = builder->createConvert(loc, builder->getI1Type(), cond);
677     builder->create<mlir::cf::CondBranchOp>(loc, bcc, trueTarget, llvm::None,
678                                             falseTarget, llvm::None);
679   }
680   void genFIRConditionalBranch(mlir::Value cond,
681                                Fortran::lower::pft::Evaluation *trueTarget,
682                                Fortran::lower::pft::Evaluation *falseTarget) {
683     genFIRConditionalBranch(cond, trueTarget->block, falseTarget->block);
684   }
685   void genFIRConditionalBranch(const Fortran::parser::ScalarLogicalExpr &expr,
686                                mlir::Block *trueTarget,
687                                mlir::Block *falseTarget) {
688     Fortran::lower::StatementContext stmtCtx;
689     mlir::Value cond =
690         createFIRExpr(toLocation(), Fortran::semantics::GetExpr(expr), stmtCtx);
691     stmtCtx.finalize();
692     genFIRConditionalBranch(cond, trueTarget, falseTarget);
693   }
694   void genFIRConditionalBranch(const Fortran::parser::ScalarLogicalExpr &expr,
695                                Fortran::lower::pft::Evaluation *trueTarget,
696                                Fortran::lower::pft::Evaluation *falseTarget) {
697     Fortran::lower::StatementContext stmtCtx;
698     mlir::Value cond =
699         createFIRExpr(toLocation(), Fortran::semantics::GetExpr(expr), stmtCtx);
700     stmtCtx.finalize();
701     genFIRConditionalBranch(cond, trueTarget->block, falseTarget->block);
702   }
703 
704   //===--------------------------------------------------------------------===//
705   // Termination of symbolically referenced execution units
706   //===--------------------------------------------------------------------===//
707 
708   /// END of program
709   ///
710   /// Generate the cleanup block before the program exits
711   void genExitRoutine() {
712     if (blockIsUnterminated())
713       builder->create<mlir::func::ReturnOp>(toLocation());
714   }
715   void genFIR(const Fortran::parser::EndProgramStmt &) { genExitRoutine(); }
716 
717   /// END of procedure-like constructs
718   ///
719   /// Generate the cleanup block before the procedure exits
720   void genReturnSymbol(const Fortran::semantics::Symbol &functionSymbol) {
721     const Fortran::semantics::Symbol &resultSym =
722         functionSymbol.get<Fortran::semantics::SubprogramDetails>().result();
723     Fortran::lower::SymbolBox resultSymBox = lookupSymbol(resultSym);
724     mlir::Location loc = toLocation();
725     if (!resultSymBox) {
726       mlir::emitError(loc, "failed lowering function return");
727       return;
728     }
729     mlir::Value resultVal = resultSymBox.match(
730         [&](const fir::CharBoxValue &x) -> mlir::Value {
731           return fir::factory::CharacterExprHelper{*builder, loc}
732               .createEmboxChar(x.getBuffer(), x.getLen());
733         },
734         [&](const auto &) -> mlir::Value {
735           mlir::Value resultRef = resultSymBox.getAddr();
736           mlir::Type resultType = genType(resultSym);
737           mlir::Type resultRefType = builder->getRefType(resultType);
738           // A function with multiple entry points returning different types
739           // tags all result variables with one of the largest types to allow
740           // them to share the same storage.  Convert this to the actual type.
741           if (resultRef.getType() != resultRefType)
742             resultRef = builder->createConvert(loc, resultRefType, resultRef);
743           return builder->create<fir::LoadOp>(loc, resultRef);
744         });
745     builder->create<mlir::func::ReturnOp>(loc, resultVal);
746   }
747 
748   /// Get the return value of a call to \p symbol, which is a subroutine entry
749   /// point that has alternative return specifiers.
750   const mlir::Value
751   getAltReturnResult(const Fortran::semantics::Symbol &symbol) {
752     assert(Fortran::semantics::HasAlternateReturns(symbol) &&
753            "subroutine does not have alternate returns");
754     return getSymbolAddress(symbol);
755   }
756 
757   void genFIRProcedureExit(Fortran::lower::pft::FunctionLikeUnit &funit,
758                            const Fortran::semantics::Symbol &symbol) {
759     if (mlir::Block *finalBlock = funit.finalBlock) {
760       // The current block must end with a terminator.
761       if (blockIsUnterminated())
762         builder->create<mlir::cf::BranchOp>(toLocation(), finalBlock);
763       // Set insertion point to final block.
764       builder->setInsertionPoint(finalBlock, finalBlock->end());
765     }
766     if (Fortran::semantics::IsFunction(symbol)) {
767       genReturnSymbol(symbol);
768     } else if (Fortran::semantics::HasAlternateReturns(symbol)) {
769       mlir::Value retval = builder->create<fir::LoadOp>(
770           toLocation(), getAltReturnResult(symbol));
771       builder->create<mlir::func::ReturnOp>(toLocation(), retval);
772     } else {
773       genExitRoutine();
774     }
775   }
776 
777   //
778   // Statements that have control-flow semantics
779   //
780 
781   /// Generate an If[Then]Stmt condition or its negation.
782   template <typename A>
783   mlir::Value genIfCondition(const A *stmt, bool negate = false) {
784     mlir::Location loc = toLocation();
785     Fortran::lower::StatementContext stmtCtx;
786     mlir::Value condExpr = createFIRExpr(
787         loc,
788         Fortran::semantics::GetExpr(
789             std::get<Fortran::parser::ScalarLogicalExpr>(stmt->t)),
790         stmtCtx);
791     stmtCtx.finalize();
792     mlir::Value cond =
793         builder->createConvert(loc, builder->getI1Type(), condExpr);
794     if (negate)
795       cond = builder->create<mlir::arith::XOrIOp>(
796           loc, cond, builder->createIntegerConstant(loc, cond.getType(), 1));
797     return cond;
798   }
799 
800   mlir::func::FuncOp getFunc(llvm::StringRef name, mlir::FunctionType ty) {
801     if (mlir::func::FuncOp func = builder->getNamedFunction(name)) {
802       assert(func.getFunctionType() == ty);
803       return func;
804     }
805     return builder->createFunction(toLocation(), name, ty);
806   }
807 
808   /// Lowering of CALL statement
809   void genFIR(const Fortran::parser::CallStmt &stmt) {
810     Fortran::lower::StatementContext stmtCtx;
811     Fortran::lower::pft::Evaluation &eval = getEval();
812     setCurrentPosition(stmt.v.source);
813     assert(stmt.typedCall && "Call was not analyzed");
814     // Call statement lowering shares code with function call lowering.
815     mlir::Value res = Fortran::lower::createSubroutineCall(
816         *this, *stmt.typedCall, explicitIterSpace, implicitIterSpace,
817         localSymbols, stmtCtx, /*isUserDefAssignment=*/false);
818     if (!res)
819       return; // "Normal" subroutine call.
820     // Call with alternate return specifiers.
821     // The call returns an index that selects an alternate return branch target.
822     llvm::SmallVector<int64_t> indexList;
823     llvm::SmallVector<mlir::Block *> blockList;
824     int64_t index = 0;
825     for (const Fortran::parser::ActualArgSpec &arg :
826          std::get<std::list<Fortran::parser::ActualArgSpec>>(stmt.v.t)) {
827       const auto &actual = std::get<Fortran::parser::ActualArg>(arg.t);
828       if (const auto *altReturn =
829               std::get_if<Fortran::parser::AltReturnSpec>(&actual.u)) {
830         indexList.push_back(++index);
831         blockList.push_back(blockOfLabel(eval, altReturn->v));
832       }
833     }
834     blockList.push_back(eval.nonNopSuccessor().block); // default = fallthrough
835     stmtCtx.finalize();
836     builder->create<fir::SelectOp>(toLocation(), res, indexList, blockList);
837   }
838 
839   void genFIR(const Fortran::parser::ComputedGotoStmt &stmt) {
840     Fortran::lower::StatementContext stmtCtx;
841     Fortran::lower::pft::Evaluation &eval = getEval();
842     mlir::Value selectExpr =
843         createFIRExpr(toLocation(),
844                       Fortran::semantics::GetExpr(
845                           std::get<Fortran::parser::ScalarIntExpr>(stmt.t)),
846                       stmtCtx);
847     stmtCtx.finalize();
848     llvm::SmallVector<int64_t> indexList;
849     llvm::SmallVector<mlir::Block *> blockList;
850     int64_t index = 0;
851     for (Fortran::parser::Label label :
852          std::get<std::list<Fortran::parser::Label>>(stmt.t)) {
853       indexList.push_back(++index);
854       blockList.push_back(blockOfLabel(eval, label));
855     }
856     blockList.push_back(eval.nonNopSuccessor().block); // default
857     builder->create<fir::SelectOp>(toLocation(), selectExpr, indexList,
858                                    blockList);
859   }
860 
861   void genFIR(const Fortran::parser::ArithmeticIfStmt &stmt) {
862     Fortran::lower::StatementContext stmtCtx;
863     Fortran::lower::pft::Evaluation &eval = getEval();
864     mlir::Value expr = createFIRExpr(
865         toLocation(),
866         Fortran::semantics::GetExpr(std::get<Fortran::parser::Expr>(stmt.t)),
867         stmtCtx);
868     stmtCtx.finalize();
869     mlir::Type exprType = expr.getType();
870     mlir::Location loc = toLocation();
871     if (exprType.isSignlessInteger()) {
872       // Arithmetic expression has Integer type.  Generate a SelectCaseOp
873       // with ranges {(-inf:-1], 0=default, [1:inf)}.
874       mlir::MLIRContext *context = builder->getContext();
875       llvm::SmallVector<mlir::Attribute> attrList;
876       llvm::SmallVector<mlir::Value> valueList;
877       llvm::SmallVector<mlir::Block *> blockList;
878       attrList.push_back(fir::UpperBoundAttr::get(context));
879       valueList.push_back(builder->createIntegerConstant(loc, exprType, -1));
880       blockList.push_back(blockOfLabel(eval, std::get<1>(stmt.t)));
881       attrList.push_back(fir::LowerBoundAttr::get(context));
882       valueList.push_back(builder->createIntegerConstant(loc, exprType, 1));
883       blockList.push_back(blockOfLabel(eval, std::get<3>(stmt.t)));
884       attrList.push_back(mlir::UnitAttr::get(context)); // 0 is the "default"
885       blockList.push_back(blockOfLabel(eval, std::get<2>(stmt.t)));
886       builder->create<fir::SelectCaseOp>(loc, expr, attrList, valueList,
887                                          blockList);
888       return;
889     }
890     // Arithmetic expression has Real type.  Generate
891     //   sum = expr + expr  [ raise an exception if expr is a NaN ]
892     //   if (sum < 0.0) goto L1 else if (sum > 0.0) goto L3 else goto L2
893     auto sum = builder->create<mlir::arith::AddFOp>(loc, expr, expr);
894     auto zero = builder->create<mlir::arith::ConstantOp>(
895         loc, exprType, builder->getFloatAttr(exprType, 0.0));
896     auto cond1 = builder->create<mlir::arith::CmpFOp>(
897         loc, mlir::arith::CmpFPredicate::OLT, sum, zero);
898     mlir::Block *elseIfBlock =
899         builder->getBlock()->splitBlock(builder->getInsertionPoint());
900     genFIRConditionalBranch(cond1, blockOfLabel(eval, std::get<1>(stmt.t)),
901                             elseIfBlock);
902     startBlock(elseIfBlock);
903     auto cond2 = builder->create<mlir::arith::CmpFOp>(
904         loc, mlir::arith::CmpFPredicate::OGT, sum, zero);
905     genFIRConditionalBranch(cond2, blockOfLabel(eval, std::get<3>(stmt.t)),
906                             blockOfLabel(eval, std::get<2>(stmt.t)));
907   }
908 
909   void genFIR(const Fortran::parser::AssignedGotoStmt &stmt) {
910     // Program requirement 1990 8.2.4 -
911     //
912     //   At the time of execution of an assigned GOTO statement, the integer
913     //   variable must be defined with the value of a statement label of a
914     //   branch target statement that appears in the same scoping unit.
915     //   Note that the variable may be defined with a statement label value
916     //   only by an ASSIGN statement in the same scoping unit as the assigned
917     //   GOTO statement.
918 
919     mlir::Location loc = toLocation();
920     Fortran::lower::pft::Evaluation &eval = getEval();
921     const Fortran::lower::pft::SymbolLabelMap &symbolLabelMap =
922         eval.getOwningProcedure()->assignSymbolLabelMap;
923     const Fortran::semantics::Symbol &symbol =
924         *std::get<Fortran::parser::Name>(stmt.t).symbol;
925     auto selectExpr =
926         builder->create<fir::LoadOp>(loc, getSymbolAddress(symbol));
927     auto iter = symbolLabelMap.find(symbol);
928     if (iter == symbolLabelMap.end()) {
929       // Fail for a nonconforming program unit that does not have any ASSIGN
930       // statements.  The front end should check for this.
931       mlir::emitError(loc, "(semantics issue) no assigned goto targets");
932       exit(1);
933     }
934     auto labelSet = iter->second;
935     llvm::SmallVector<int64_t> indexList;
936     llvm::SmallVector<mlir::Block *> blockList;
937     auto addLabel = [&](Fortran::parser::Label label) {
938       indexList.push_back(label);
939       blockList.push_back(blockOfLabel(eval, label));
940     };
941     // Add labels from an explicit list.  The list may have duplicates.
942     for (Fortran::parser::Label label :
943          std::get<std::list<Fortran::parser::Label>>(stmt.t)) {
944       if (labelSet.count(label) &&
945           std::find(indexList.begin(), indexList.end(), label) ==
946               indexList.end()) { // ignore duplicates
947         addLabel(label);
948       }
949     }
950     // Absent an explicit list, add all possible label targets.
951     if (indexList.empty())
952       for (auto &label : labelSet)
953         addLabel(label);
954     // Add a nop/fallthrough branch to the switch for a nonconforming program
955     // unit that violates the program requirement above.
956     blockList.push_back(eval.nonNopSuccessor().block); // default
957     builder->create<fir::SelectOp>(loc, selectExpr, indexList, blockList);
958   }
959 
960   /// Generate FIR for a DO construct.  There are six variants:
961   ///  - unstructured infinite and while loops
962   ///  - structured and unstructured increment loops
963   ///  - structured and unstructured concurrent loops
964   void genFIR(const Fortran::parser::DoConstruct &doConstruct) {
965     setCurrentPositionAt(doConstruct);
966     // Collect loop nest information.
967     // Generate begin loop code directly for infinite and while loops.
968     Fortran::lower::pft::Evaluation &eval = getEval();
969     bool unstructuredContext = eval.lowerAsUnstructured();
970     Fortran::lower::pft::Evaluation &doStmtEval =
971         eval.getFirstNestedEvaluation();
972     auto *doStmt = doStmtEval.getIf<Fortran::parser::NonLabelDoStmt>();
973     const auto &loopControl =
974         std::get<std::optional<Fortran::parser::LoopControl>>(doStmt->t);
975     mlir::Block *preheaderBlock = doStmtEval.block;
976     mlir::Block *beginBlock =
977         preheaderBlock ? preheaderBlock : builder->getBlock();
978     auto createNextBeginBlock = [&]() {
979       // Step beginBlock through unstructured preheader, header, and mask
980       // blocks, created in outermost to innermost order.
981       return beginBlock = beginBlock->splitBlock(beginBlock->end());
982     };
983     mlir::Block *headerBlock =
984         unstructuredContext ? createNextBeginBlock() : nullptr;
985     mlir::Block *bodyBlock = doStmtEval.lexicalSuccessor->block;
986     mlir::Block *exitBlock = doStmtEval.parentConstruct->constructExit->block;
987     IncrementLoopNestInfo incrementLoopNestInfo;
988     if (const auto *bounds = std::get_if<Fortran::parser::LoopControl::Bounds>(
989             &loopControl->u)) {
990       // Non-concurrent increment loop.
991       IncrementLoopInfo &info = incrementLoopNestInfo.emplace_back(
992           *bounds->name.thing.symbol, bounds->lower, bounds->upper,
993           bounds->step);
994       if (unstructuredContext) {
995         maybeStartBlock(preheaderBlock);
996         info.headerBlock = headerBlock;
997         info.bodyBlock = bodyBlock;
998         info.exitBlock = exitBlock;
999       }
1000     } else {
1001       TODO(toLocation(), "infinite/unstructured loop/concurrent loop");
1002     }
1003 
1004     // Increment loop begin code.  (TODO: Infinite/while code was already
1005     // generated.)
1006     genFIRIncrementLoopBegin(incrementLoopNestInfo);
1007 
1008     // Loop body code - NonLabelDoStmt and EndDoStmt code is generated here.
1009     // Their genFIR calls are nops except for block management in some cases.
1010     for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations())
1011       genFIR(e, unstructuredContext);
1012 
1013     // Loop end code. (TODO: infinite/while loop)
1014     genFIRIncrementLoopEnd(incrementLoopNestInfo);
1015   }
1016 
1017   /// Generate FIR to begin a structured or unstructured increment loop nest.
1018   void genFIRIncrementLoopBegin(IncrementLoopNestInfo &incrementLoopNestInfo) {
1019     assert(!incrementLoopNestInfo.empty() && "empty loop nest");
1020     mlir::Location loc = toLocation();
1021     auto genControlValue = [&](const Fortran::lower::SomeExpr *expr,
1022                                const IncrementLoopInfo &info) {
1023       mlir::Type controlType = info.isStructured() ? builder->getIndexType()
1024                                                    : info.getLoopVariableType();
1025       Fortran::lower::StatementContext stmtCtx;
1026       if (expr)
1027         return builder->createConvert(loc, controlType,
1028                                       createFIRExpr(loc, expr, stmtCtx));
1029       return builder->createIntegerConstant(loc, controlType, 1); // step
1030     };
1031     for (IncrementLoopInfo &info : incrementLoopNestInfo) {
1032       info.loopVariable = genLoopVariableAddress(loc, info.loopVariableSym);
1033       mlir::Value lowerValue = genControlValue(info.lowerExpr, info);
1034       mlir::Value upperValue = genControlValue(info.upperExpr, info);
1035       info.stepValue = genControlValue(info.stepExpr, info);
1036 
1037       // Structured loop - generate fir.do_loop.
1038       if (info.isStructured()) {
1039         info.doLoop = builder->create<fir::DoLoopOp>(
1040             loc, lowerValue, upperValue, info.stepValue, info.isUnordered,
1041             /*finalCountValue=*/!info.isUnordered);
1042         builder->setInsertionPointToStart(info.doLoop.getBody());
1043         // Update the loop variable value, as it may have non-index references.
1044         mlir::Value value = builder->createConvert(
1045             loc, info.getLoopVariableType(), info.doLoop.getInductionVar());
1046         builder->create<fir::StoreOp>(loc, value, info.loopVariable);
1047         // TODO: Mask expr
1048         // TODO: handle Locality Spec
1049         continue;
1050       }
1051 
1052       // Unstructured loop preheader - initialize tripVariable and loopVariable.
1053       mlir::Value tripCount;
1054       auto diff1 =
1055           builder->create<mlir::arith::SubIOp>(loc, upperValue, lowerValue);
1056       auto diff2 =
1057           builder->create<mlir::arith::AddIOp>(loc, diff1, info.stepValue);
1058       tripCount =
1059           builder->create<mlir::arith::DivSIOp>(loc, diff2, info.stepValue);
1060       info.tripVariable = builder->createTemporary(loc, tripCount.getType());
1061       builder->create<fir::StoreOp>(loc, tripCount, info.tripVariable);
1062       builder->create<fir::StoreOp>(loc, lowerValue, info.loopVariable);
1063 
1064       // Unstructured loop header - generate loop condition and mask.
1065       startBlock(info.headerBlock);
1066       tripCount = builder->create<fir::LoadOp>(loc, info.tripVariable);
1067       mlir::Value zero =
1068           builder->createIntegerConstant(loc, tripCount.getType(), 0);
1069       auto cond = builder->create<mlir::arith::CmpIOp>(
1070           loc, mlir::arith::CmpIPredicate::sgt, tripCount, zero);
1071       // TODO: mask expression
1072       genFIRConditionalBranch(cond, info.bodyBlock, info.exitBlock);
1073       if (&info != &incrementLoopNestInfo.back()) // not innermost
1074         startBlock(info.bodyBlock); // preheader block of enclosed dimension
1075     }
1076   }
1077 
1078   /// Generate FIR to end a structured or unstructured increment loop nest.
1079   void genFIRIncrementLoopEnd(IncrementLoopNestInfo &incrementLoopNestInfo) {
1080     assert(!incrementLoopNestInfo.empty() && "empty loop nest");
1081     mlir::Location loc = toLocation();
1082     for (auto it = incrementLoopNestInfo.rbegin(),
1083               rend = incrementLoopNestInfo.rend();
1084          it != rend; ++it) {
1085       IncrementLoopInfo &info = *it;
1086       if (info.isStructured()) {
1087         // End fir.do_loop.
1088         if (!info.isUnordered) {
1089           builder->setInsertionPointToEnd(info.doLoop.getBody());
1090           mlir::Value result = builder->create<mlir::arith::AddIOp>(
1091               loc, info.doLoop.getInductionVar(), info.doLoop.getStep());
1092           builder->create<fir::ResultOp>(loc, result);
1093         }
1094         builder->setInsertionPointAfter(info.doLoop);
1095         if (info.isUnordered)
1096           continue;
1097         // The loop control variable may be used after loop execution.
1098         mlir::Value lcv = builder->createConvert(
1099             loc, info.getLoopVariableType(), info.doLoop.getResult(0));
1100         builder->create<fir::StoreOp>(loc, lcv, info.loopVariable);
1101         continue;
1102       }
1103 
1104       // Unstructured loop - decrement tripVariable and step loopVariable.
1105       mlir::Value tripCount =
1106           builder->create<fir::LoadOp>(loc, info.tripVariable);
1107       mlir::Value one =
1108           builder->createIntegerConstant(loc, tripCount.getType(), 1);
1109       tripCount = builder->create<mlir::arith::SubIOp>(loc, tripCount, one);
1110       builder->create<fir::StoreOp>(loc, tripCount, info.tripVariable);
1111       mlir::Value value = builder->create<fir::LoadOp>(loc, info.loopVariable);
1112       value = builder->create<mlir::arith::AddIOp>(loc, value, info.stepValue);
1113       builder->create<fir::StoreOp>(loc, value, info.loopVariable);
1114 
1115       genFIRBranch(info.headerBlock);
1116       if (&info != &incrementLoopNestInfo.front()) // not outermost
1117         startBlock(info.exitBlock); // latch block of enclosing dimension
1118     }
1119   }
1120 
1121   /// Generate structured or unstructured FIR for an IF construct.
1122   /// The initial statement may be either an IfStmt or an IfThenStmt.
1123   void genFIR(const Fortran::parser::IfConstruct &) {
1124     mlir::Location loc = toLocation();
1125     Fortran::lower::pft::Evaluation &eval = getEval();
1126     if (eval.lowerAsStructured()) {
1127       // Structured fir.if nest.
1128       fir::IfOp topIfOp, currentIfOp;
1129       for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) {
1130         auto genIfOp = [&](mlir::Value cond) {
1131           auto ifOp = builder->create<fir::IfOp>(loc, cond, /*withElse=*/true);
1132           builder->setInsertionPointToStart(&ifOp.getThenRegion().front());
1133           return ifOp;
1134         };
1135         if (auto *s = e.getIf<Fortran::parser::IfThenStmt>()) {
1136           topIfOp = currentIfOp = genIfOp(genIfCondition(s, e.negateCondition));
1137         } else if (auto *s = e.getIf<Fortran::parser::IfStmt>()) {
1138           topIfOp = currentIfOp = genIfOp(genIfCondition(s, e.negateCondition));
1139         } else if (auto *s = e.getIf<Fortran::parser::ElseIfStmt>()) {
1140           builder->setInsertionPointToStart(
1141               &currentIfOp.getElseRegion().front());
1142           currentIfOp = genIfOp(genIfCondition(s));
1143         } else if (e.isA<Fortran::parser::ElseStmt>()) {
1144           builder->setInsertionPointToStart(
1145               &currentIfOp.getElseRegion().front());
1146         } else if (e.isA<Fortran::parser::EndIfStmt>()) {
1147           builder->setInsertionPointAfter(topIfOp);
1148         } else {
1149           genFIR(e, /*unstructuredContext=*/false);
1150         }
1151       }
1152       return;
1153     }
1154 
1155     // Unstructured branch sequence.
1156     for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) {
1157       auto genIfBranch = [&](mlir::Value cond) {
1158         if (e.lexicalSuccessor == e.controlSuccessor) // empty block -> exit
1159           genFIRConditionalBranch(cond, e.parentConstruct->constructExit,
1160                                   e.controlSuccessor);
1161         else // non-empty block
1162           genFIRConditionalBranch(cond, e.lexicalSuccessor, e.controlSuccessor);
1163       };
1164       if (auto *s = e.getIf<Fortran::parser::IfThenStmt>()) {
1165         maybeStartBlock(e.block);
1166         genIfBranch(genIfCondition(s, e.negateCondition));
1167       } else if (auto *s = e.getIf<Fortran::parser::IfStmt>()) {
1168         maybeStartBlock(e.block);
1169         genIfBranch(genIfCondition(s, e.negateCondition));
1170       } else if (auto *s = e.getIf<Fortran::parser::ElseIfStmt>()) {
1171         startBlock(e.block);
1172         genIfBranch(genIfCondition(s));
1173       } else {
1174         genFIR(e);
1175       }
1176     }
1177   }
1178 
1179   void genFIR(const Fortran::parser::CaseConstruct &) {
1180     for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations())
1181       genFIR(e);
1182   }
1183 
1184   template <typename A>
1185   void genNestedStatement(const Fortran::parser::Statement<A> &stmt) {
1186     setCurrentPosition(stmt.source);
1187     genFIR(stmt.statement);
1188   }
1189 
1190   /// Force the binding of an explicit symbol. This is used to bind and re-bind
1191   /// a concurrent control symbol to its value.
1192   void forceControlVariableBinding(const Fortran::semantics::Symbol *sym,
1193                                    mlir::Value inducVar) {
1194     mlir::Location loc = toLocation();
1195     assert(sym && "There must be a symbol to bind");
1196     mlir::Type toTy = genType(*sym);
1197     // FIXME: this should be a "per iteration" temporary.
1198     mlir::Value tmp = builder->createTemporary(
1199         loc, toTy, toStringRef(sym->name()),
1200         llvm::ArrayRef<mlir::NamedAttribute>{
1201             Fortran::lower::getAdaptToByRefAttr(*builder)});
1202     mlir::Value cast = builder->createConvert(loc, toTy, inducVar);
1203     builder->create<fir::StoreOp>(loc, cast, tmp);
1204     localSymbols.addSymbol(*sym, tmp, /*force=*/true);
1205   }
1206 
1207   /// Process a concurrent header for a FORALL. (Concurrent headers for DO
1208   /// CONCURRENT loops are lowered elsewhere.)
1209   void genFIR(const Fortran::parser::ConcurrentHeader &header) {
1210     llvm::SmallVector<mlir::Value> lows;
1211     llvm::SmallVector<mlir::Value> highs;
1212     llvm::SmallVector<mlir::Value> steps;
1213     if (explicitIterSpace.isOutermostForall()) {
1214       // For the outermost forall, we evaluate the bounds expressions once.
1215       // Contrastingly, if this forall is nested, the bounds expressions are
1216       // assumed to be pure, possibly dependent on outer concurrent control
1217       // variables, possibly variant with respect to arguments, and will be
1218       // re-evaluated.
1219       mlir::Location loc = toLocation();
1220       mlir::Type idxTy = builder->getIndexType();
1221       Fortran::lower::StatementContext &stmtCtx =
1222           explicitIterSpace.stmtContext();
1223       auto lowerExpr = [&](auto &e) {
1224         return fir::getBase(genExprValue(e, stmtCtx));
1225       };
1226       for (const Fortran::parser::ConcurrentControl &ctrl :
1227            std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) {
1228         const Fortran::lower::SomeExpr *lo =
1229             Fortran::semantics::GetExpr(std::get<1>(ctrl.t));
1230         const Fortran::lower::SomeExpr *hi =
1231             Fortran::semantics::GetExpr(std::get<2>(ctrl.t));
1232         auto &optStep =
1233             std::get<std::optional<Fortran::parser::ScalarIntExpr>>(ctrl.t);
1234         lows.push_back(builder->createConvert(loc, idxTy, lowerExpr(*lo)));
1235         highs.push_back(builder->createConvert(loc, idxTy, lowerExpr(*hi)));
1236         steps.push_back(
1237             optStep.has_value()
1238                 ? builder->createConvert(
1239                       loc, idxTy,
1240                       lowerExpr(*Fortran::semantics::GetExpr(*optStep)))
1241                 : builder->createIntegerConstant(loc, idxTy, 1));
1242       }
1243     }
1244     auto lambda = [&, lows, highs, steps]() {
1245       // Create our iteration space from the header spec.
1246       mlir::Location loc = toLocation();
1247       mlir::Type idxTy = builder->getIndexType();
1248       llvm::SmallVector<fir::DoLoopOp> loops;
1249       Fortran::lower::StatementContext &stmtCtx =
1250           explicitIterSpace.stmtContext();
1251       auto lowerExpr = [&](auto &e) {
1252         return fir::getBase(genExprValue(e, stmtCtx));
1253       };
1254       const bool outermost = !lows.empty();
1255       std::size_t headerIndex = 0;
1256       for (const Fortran::parser::ConcurrentControl &ctrl :
1257            std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) {
1258         const Fortran::semantics::Symbol *ctrlVar =
1259             std::get<Fortran::parser::Name>(ctrl.t).symbol;
1260         mlir::Value lb;
1261         mlir::Value ub;
1262         mlir::Value by;
1263         if (outermost) {
1264           assert(headerIndex < lows.size());
1265           if (headerIndex == 0)
1266             explicitIterSpace.resetInnerArgs();
1267           lb = lows[headerIndex];
1268           ub = highs[headerIndex];
1269           by = steps[headerIndex++];
1270         } else {
1271           const Fortran::lower::SomeExpr *lo =
1272               Fortran::semantics::GetExpr(std::get<1>(ctrl.t));
1273           const Fortran::lower::SomeExpr *hi =
1274               Fortran::semantics::GetExpr(std::get<2>(ctrl.t));
1275           auto &optStep =
1276               std::get<std::optional<Fortran::parser::ScalarIntExpr>>(ctrl.t);
1277           lb = builder->createConvert(loc, idxTy, lowerExpr(*lo));
1278           ub = builder->createConvert(loc, idxTy, lowerExpr(*hi));
1279           by = optStep.has_value()
1280                    ? builder->createConvert(
1281                          loc, idxTy,
1282                          lowerExpr(*Fortran::semantics::GetExpr(*optStep)))
1283                    : builder->createIntegerConstant(loc, idxTy, 1);
1284         }
1285         auto lp = builder->create<fir::DoLoopOp>(
1286             loc, lb, ub, by, /*unordered=*/true,
1287             /*finalCount=*/false, explicitIterSpace.getInnerArgs());
1288         if (!loops.empty() || !outermost)
1289           builder->create<fir::ResultOp>(loc, lp.getResults());
1290         explicitIterSpace.setInnerArgs(lp.getRegionIterArgs());
1291         builder->setInsertionPointToStart(lp.getBody());
1292         forceControlVariableBinding(ctrlVar, lp.getInductionVar());
1293         loops.push_back(lp);
1294       }
1295       if (outermost)
1296         explicitIterSpace.setOuterLoop(loops[0]);
1297       explicitIterSpace.appendLoops(loops);
1298       if (const auto &mask =
1299               std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>(
1300                   header.t);
1301           mask.has_value()) {
1302         mlir::Type i1Ty = builder->getI1Type();
1303         fir::ExtendedValue maskExv =
1304             genExprValue(*Fortran::semantics::GetExpr(mask.value()), stmtCtx);
1305         mlir::Value cond =
1306             builder->createConvert(loc, i1Ty, fir::getBase(maskExv));
1307         auto ifOp = builder->create<fir::IfOp>(
1308             loc, explicitIterSpace.innerArgTypes(), cond,
1309             /*withElseRegion=*/true);
1310         builder->create<fir::ResultOp>(loc, ifOp.getResults());
1311         builder->setInsertionPointToStart(&ifOp.getElseRegion().front());
1312         builder->create<fir::ResultOp>(loc, explicitIterSpace.getInnerArgs());
1313         builder->setInsertionPointToStart(&ifOp.getThenRegion().front());
1314       }
1315     };
1316     // Push the lambda to gen the loop nest context.
1317     explicitIterSpace.pushLoopNest(lambda);
1318   }
1319 
1320   void genFIR(const Fortran::parser::ForallAssignmentStmt &stmt) {
1321     std::visit([&](const auto &x) { genFIR(x); }, stmt.u);
1322   }
1323 
1324   void genFIR(const Fortran::parser::EndForallStmt &) {
1325     cleanupExplicitSpace();
1326   }
1327 
1328   template <typename A>
1329   void prepareExplicitSpace(const A &forall) {
1330     if (!explicitIterSpace.isActive())
1331       analyzeExplicitSpace(forall);
1332     localSymbols.pushScope();
1333     explicitIterSpace.enter();
1334   }
1335 
1336   /// Cleanup all the FORALL context information when we exit.
1337   void cleanupExplicitSpace() {
1338     explicitIterSpace.leave();
1339     localSymbols.popScope();
1340   }
1341 
1342   /// Generate FIR for a FORALL statement.
1343   void genFIR(const Fortran::parser::ForallStmt &stmt) {
1344     prepareExplicitSpace(stmt);
1345     genFIR(std::get<
1346                Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
1347                stmt.t)
1348                .value());
1349     genFIR(std::get<Fortran::parser::UnlabeledStatement<
1350                Fortran::parser::ForallAssignmentStmt>>(stmt.t)
1351                .statement);
1352     cleanupExplicitSpace();
1353   }
1354 
1355   /// Generate FIR for a FORALL construct.
1356   void genFIR(const Fortran::parser::ForallConstruct &forall) {
1357     prepareExplicitSpace(forall);
1358     genNestedStatement(
1359         std::get<
1360             Fortran::parser::Statement<Fortran::parser::ForallConstructStmt>>(
1361             forall.t));
1362     for (const Fortran::parser::ForallBodyConstruct &s :
1363          std::get<std::list<Fortran::parser::ForallBodyConstruct>>(forall.t)) {
1364       std::visit(
1365           Fortran::common::visitors{
1366               [&](const Fortran::parser::WhereConstruct &b) { genFIR(b); },
1367               [&](const Fortran::common::Indirection<
1368                   Fortran::parser::ForallConstruct> &b) { genFIR(b.value()); },
1369               [&](const auto &b) { genNestedStatement(b); }},
1370           s.u);
1371     }
1372     genNestedStatement(
1373         std::get<Fortran::parser::Statement<Fortran::parser::EndForallStmt>>(
1374             forall.t));
1375   }
1376 
1377   /// Lower the concurrent header specification.
1378   void genFIR(const Fortran::parser::ForallConstructStmt &stmt) {
1379     genFIR(std::get<
1380                Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
1381                stmt.t)
1382                .value());
1383   }
1384 
1385   void genFIR(const Fortran::parser::CompilerDirective &) {
1386     TODO(toLocation(), "CompilerDirective lowering");
1387   }
1388 
1389   void genFIR(const Fortran::parser::OpenACCConstruct &acc) {
1390     mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
1391     genOpenACCConstruct(*this, getEval(), acc);
1392     for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations())
1393       genFIR(e);
1394     builder->restoreInsertionPoint(insertPt);
1395   }
1396 
1397   void genFIR(const Fortran::parser::OpenACCDeclarativeConstruct &accDecl) {
1398     mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
1399     genOpenACCDeclarativeConstruct(*this, getEval(), accDecl);
1400     for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations())
1401       genFIR(e);
1402     builder->restoreInsertionPoint(insertPt);
1403   }
1404 
1405   void genFIR(const Fortran::parser::OpenMPConstruct &omp) {
1406     mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
1407     localSymbols.pushScope();
1408     Fortran::lower::genOpenMPConstruct(*this, getEval(), omp);
1409 
1410     // If loop is part of an OpenMP Construct then the OpenMP dialect
1411     // workshare loop operation has already been created. Only the
1412     // body needs to be created here and the do_loop can be skipped.
1413     Fortran::lower::pft::Evaluation *curEval =
1414         std::get_if<Fortran::parser::OpenMPLoopConstruct>(&omp.u)
1415             ? &getEval().getFirstNestedEvaluation()
1416             : &getEval();
1417 
1418     for (Fortran::lower::pft::Evaluation &e : curEval->getNestedEvaluations())
1419       genFIR(e);
1420     localSymbols.popScope();
1421     builder->restoreInsertionPoint(insertPt);
1422   }
1423 
1424   void genFIR(const Fortran::parser::OpenMPDeclarativeConstruct &ompDecl) {
1425     mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
1426     genOpenMPDeclarativeConstruct(*this, getEval(), ompDecl);
1427     for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations())
1428       genFIR(e);
1429     builder->restoreInsertionPoint(insertPt);
1430   }
1431 
1432   /// Generate FIR for a SELECT CASE statement.
1433   /// The type may be CHARACTER, INTEGER, or LOGICAL.
1434   void genFIR(const Fortran::parser::SelectCaseStmt &stmt) {
1435     Fortran::lower::pft::Evaluation &eval = getEval();
1436     mlir::MLIRContext *context = builder->getContext();
1437     mlir::Location loc = toLocation();
1438     Fortran::lower::StatementContext stmtCtx;
1439     const Fortran::lower::SomeExpr *expr = Fortran::semantics::GetExpr(
1440         std::get<Fortran::parser::Scalar<Fortran::parser::Expr>>(stmt.t));
1441     bool isCharSelector = isCharacterCategory(expr->GetType()->category());
1442     bool isLogicalSelector = isLogicalCategory(expr->GetType()->category());
1443     auto charValue = [&](const Fortran::lower::SomeExpr *expr) {
1444       fir::ExtendedValue exv = genExprAddr(*expr, stmtCtx, &loc);
1445       return exv.match(
1446           [&](const fir::CharBoxValue &cbv) {
1447             return fir::factory::CharacterExprHelper{*builder, loc}
1448                 .createEmboxChar(cbv.getAddr(), cbv.getLen());
1449           },
1450           [&](auto) {
1451             fir::emitFatalError(loc, "not a character");
1452             return mlir::Value{};
1453           });
1454     };
1455     mlir::Value selector;
1456     if (isCharSelector) {
1457       selector = charValue(expr);
1458     } else {
1459       selector = createFIRExpr(loc, expr, stmtCtx);
1460       if (isLogicalSelector)
1461         selector = builder->createConvert(loc, builder->getI1Type(), selector);
1462     }
1463     mlir::Type selectType = selector.getType();
1464     llvm::SmallVector<mlir::Attribute> attrList;
1465     llvm::SmallVector<mlir::Value> valueList;
1466     llvm::SmallVector<mlir::Block *> blockList;
1467     mlir::Block *defaultBlock = eval.parentConstruct->constructExit->block;
1468     using CaseValue = Fortran::parser::Scalar<Fortran::parser::ConstantExpr>;
1469     auto addValue = [&](const CaseValue &caseValue) {
1470       const Fortran::lower::SomeExpr *expr =
1471           Fortran::semantics::GetExpr(caseValue.thing);
1472       if (isCharSelector)
1473         valueList.push_back(charValue(expr));
1474       else if (isLogicalSelector)
1475         valueList.push_back(builder->createConvert(
1476             loc, selectType, createFIRExpr(toLocation(), expr, stmtCtx)));
1477       else
1478         valueList.push_back(builder->createIntegerConstant(
1479             loc, selectType, *Fortran::evaluate::ToInt64(*expr)));
1480     };
1481     for (Fortran::lower::pft::Evaluation *e = eval.controlSuccessor; e;
1482          e = e->controlSuccessor) {
1483       const auto &caseStmt = e->getIf<Fortran::parser::CaseStmt>();
1484       assert(e->block && "missing CaseStmt block");
1485       const auto &caseSelector =
1486           std::get<Fortran::parser::CaseSelector>(caseStmt->t);
1487       const auto *caseValueRangeList =
1488           std::get_if<std::list<Fortran::parser::CaseValueRange>>(
1489               &caseSelector.u);
1490       if (!caseValueRangeList) {
1491         defaultBlock = e->block;
1492         continue;
1493       }
1494       for (const Fortran::parser::CaseValueRange &caseValueRange :
1495            *caseValueRangeList) {
1496         blockList.push_back(e->block);
1497         if (const auto *caseValue = std::get_if<CaseValue>(&caseValueRange.u)) {
1498           attrList.push_back(fir::PointIntervalAttr::get(context));
1499           addValue(*caseValue);
1500           continue;
1501         }
1502         const auto &caseRange =
1503             std::get<Fortran::parser::CaseValueRange::Range>(caseValueRange.u);
1504         if (caseRange.lower && caseRange.upper) {
1505           attrList.push_back(fir::ClosedIntervalAttr::get(context));
1506           addValue(*caseRange.lower);
1507           addValue(*caseRange.upper);
1508         } else if (caseRange.lower) {
1509           attrList.push_back(fir::LowerBoundAttr::get(context));
1510           addValue(*caseRange.lower);
1511         } else {
1512           attrList.push_back(fir::UpperBoundAttr::get(context));
1513           addValue(*caseRange.upper);
1514         }
1515       }
1516     }
1517     // Skip a logical default block that can never be referenced.
1518     if (isLogicalSelector && attrList.size() == 2)
1519       defaultBlock = eval.parentConstruct->constructExit->block;
1520     attrList.push_back(mlir::UnitAttr::get(context));
1521     blockList.push_back(defaultBlock);
1522 
1523     // Generate a fir::SelectCaseOp.
1524     // Explicit branch code is better for the LOGICAL type.  The CHARACTER type
1525     // does not yet have downstream support, and also uses explicit branch code.
1526     // The -no-structured-fir option can be used to force generation of INTEGER
1527     // type branch code.
1528     if (!isLogicalSelector && !isCharSelector && eval.lowerAsStructured()) {
1529       // Numeric selector is a ssa register, all temps that may have
1530       // been generated while evaluating it can be cleaned-up before the
1531       // fir.select_case.
1532       stmtCtx.finalize();
1533       builder->create<fir::SelectCaseOp>(loc, selector, attrList, valueList,
1534                                          blockList);
1535       return;
1536     }
1537 
1538     // Generate a sequence of case value comparisons and branches.
1539     auto caseValue = valueList.begin();
1540     auto caseBlock = blockList.begin();
1541     for (mlir::Attribute attr : attrList) {
1542       if (attr.isa<mlir::UnitAttr>()) {
1543         genFIRBranch(*caseBlock++);
1544         break;
1545       }
1546       auto genCond = [&](mlir::Value rhs,
1547                          mlir::arith::CmpIPredicate pred) -> mlir::Value {
1548         if (!isCharSelector)
1549           return builder->create<mlir::arith::CmpIOp>(loc, pred, selector, rhs);
1550         fir::factory::CharacterExprHelper charHelper{*builder, loc};
1551         std::pair<mlir::Value, mlir::Value> lhsVal =
1552             charHelper.createUnboxChar(selector);
1553         mlir::Value &lhsAddr = lhsVal.first;
1554         mlir::Value &lhsLen = lhsVal.second;
1555         std::pair<mlir::Value, mlir::Value> rhsVal =
1556             charHelper.createUnboxChar(rhs);
1557         mlir::Value &rhsAddr = rhsVal.first;
1558         mlir::Value &rhsLen = rhsVal.second;
1559         return fir::runtime::genCharCompare(*builder, loc, pred, lhsAddr,
1560                                             lhsLen, rhsAddr, rhsLen);
1561       };
1562       mlir::Block *newBlock = insertBlock(*caseBlock);
1563       if (attr.isa<fir::ClosedIntervalAttr>()) {
1564         mlir::Block *newBlock2 = insertBlock(*caseBlock);
1565         mlir::Value cond =
1566             genCond(*caseValue++, mlir::arith::CmpIPredicate::sge);
1567         genFIRConditionalBranch(cond, newBlock, newBlock2);
1568         builder->setInsertionPointToEnd(newBlock);
1569         mlir::Value cond2 =
1570             genCond(*caseValue++, mlir::arith::CmpIPredicate::sle);
1571         genFIRConditionalBranch(cond2, *caseBlock++, newBlock2);
1572         builder->setInsertionPointToEnd(newBlock2);
1573         continue;
1574       }
1575       mlir::arith::CmpIPredicate pred;
1576       if (attr.isa<fir::PointIntervalAttr>()) {
1577         pred = mlir::arith::CmpIPredicate::eq;
1578       } else if (attr.isa<fir::LowerBoundAttr>()) {
1579         pred = mlir::arith::CmpIPredicate::sge;
1580       } else {
1581         assert(attr.isa<fir::UpperBoundAttr>() && "unexpected predicate");
1582         pred = mlir::arith::CmpIPredicate::sle;
1583       }
1584       mlir::Value cond = genCond(*caseValue++, pred);
1585       genFIRConditionalBranch(cond, *caseBlock++, newBlock);
1586       builder->setInsertionPointToEnd(newBlock);
1587     }
1588     assert(caseValue == valueList.end() && caseBlock == blockList.end() &&
1589            "select case list mismatch");
1590     // Clean-up the selector at the end of the construct if it is a temporary
1591     // (which is possible with characters).
1592     mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
1593     builder->setInsertionPointToEnd(eval.parentConstruct->constructExit->block);
1594     stmtCtx.finalize();
1595     builder->restoreInsertionPoint(insertPt);
1596   }
1597 
1598   fir::ExtendedValue
1599   genAssociateSelector(const Fortran::lower::SomeExpr &selector,
1600                        Fortran::lower::StatementContext &stmtCtx) {
1601     return isArraySectionWithoutVectorSubscript(selector)
1602                ? Fortran::lower::createSomeArrayBox(*this, selector,
1603                                                     localSymbols, stmtCtx)
1604                : genExprAddr(selector, stmtCtx);
1605   }
1606 
1607   void genFIR(const Fortran::parser::AssociateConstruct &) {
1608     Fortran::lower::StatementContext stmtCtx;
1609     Fortran::lower::pft::Evaluation &eval = getEval();
1610     for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) {
1611       if (auto *stmt = e.getIf<Fortran::parser::AssociateStmt>()) {
1612         if (eval.lowerAsUnstructured())
1613           maybeStartBlock(e.block);
1614         localSymbols.pushScope();
1615         for (const Fortran::parser::Association &assoc :
1616              std::get<std::list<Fortran::parser::Association>>(stmt->t)) {
1617           Fortran::semantics::Symbol &sym =
1618               *std::get<Fortran::parser::Name>(assoc.t).symbol;
1619           const Fortran::lower::SomeExpr &selector =
1620               *sym.get<Fortran::semantics::AssocEntityDetails>().expr();
1621           localSymbols.addSymbol(sym, genAssociateSelector(selector, stmtCtx));
1622         }
1623       } else if (e.getIf<Fortran::parser::EndAssociateStmt>()) {
1624         if (eval.lowerAsUnstructured())
1625           maybeStartBlock(e.block);
1626         stmtCtx.finalize();
1627         localSymbols.popScope();
1628       } else {
1629         genFIR(e);
1630       }
1631     }
1632   }
1633 
1634   void genFIR(const Fortran::parser::BlockConstruct &blockConstruct) {
1635     setCurrentPositionAt(blockConstruct);
1636     TODO(toLocation(), "BlockConstruct lowering");
1637   }
1638   void genFIR(const Fortran::parser::BlockStmt &) {
1639     TODO(toLocation(), "BlockStmt lowering");
1640   }
1641   void genFIR(const Fortran::parser::EndBlockStmt &) {
1642     TODO(toLocation(), "EndBlockStmt lowering");
1643   }
1644 
1645   void genFIR(const Fortran::parser::ChangeTeamConstruct &construct) {
1646     TODO(toLocation(), "ChangeTeamConstruct lowering");
1647   }
1648   void genFIR(const Fortran::parser::ChangeTeamStmt &stmt) {
1649     TODO(toLocation(), "ChangeTeamStmt lowering");
1650   }
1651   void genFIR(const Fortran::parser::EndChangeTeamStmt &stmt) {
1652     TODO(toLocation(), "EndChangeTeamStmt lowering");
1653   }
1654 
1655   void genFIR(const Fortran::parser::CriticalConstruct &criticalConstruct) {
1656     setCurrentPositionAt(criticalConstruct);
1657     TODO(toLocation(), "CriticalConstruct lowering");
1658   }
1659   void genFIR(const Fortran::parser::CriticalStmt &) {
1660     TODO(toLocation(), "CriticalStmt lowering");
1661   }
1662   void genFIR(const Fortran::parser::EndCriticalStmt &) {
1663     TODO(toLocation(), "EndCriticalStmt lowering");
1664   }
1665 
1666   void genFIR(const Fortran::parser::SelectRankConstruct &selectRankConstruct) {
1667     setCurrentPositionAt(selectRankConstruct);
1668     TODO(toLocation(), "SelectRankConstruct lowering");
1669   }
1670   void genFIR(const Fortran::parser::SelectRankStmt &) {
1671     TODO(toLocation(), "SelectRankStmt lowering");
1672   }
1673   void genFIR(const Fortran::parser::SelectRankCaseStmt &) {
1674     TODO(toLocation(), "SelectRankCaseStmt lowering");
1675   }
1676 
1677   void genFIR(const Fortran::parser::SelectTypeConstruct &selectTypeConstruct) {
1678     setCurrentPositionAt(selectTypeConstruct);
1679     TODO(toLocation(), "SelectTypeConstruct lowering");
1680   }
1681   void genFIR(const Fortran::parser::SelectTypeStmt &) {
1682     TODO(toLocation(), "SelectTypeStmt lowering");
1683   }
1684   void genFIR(const Fortran::parser::TypeGuardStmt &) {
1685     TODO(toLocation(), "TypeGuardStmt lowering");
1686   }
1687 
1688   //===--------------------------------------------------------------------===//
1689   // IO statements (see io.h)
1690   //===--------------------------------------------------------------------===//
1691 
1692   void genFIR(const Fortran::parser::BackspaceStmt &stmt) {
1693     mlir::Value iostat = genBackspaceStatement(*this, stmt);
1694     genIoConditionBranches(getEval(), stmt.v, iostat);
1695   }
1696   void genFIR(const Fortran::parser::CloseStmt &stmt) {
1697     mlir::Value iostat = genCloseStatement(*this, stmt);
1698     genIoConditionBranches(getEval(), stmt.v, iostat);
1699   }
1700   void genFIR(const Fortran::parser::EndfileStmt &stmt) {
1701     mlir::Value iostat = genEndfileStatement(*this, stmt);
1702     genIoConditionBranches(getEval(), stmt.v, iostat);
1703   }
1704   void genFIR(const Fortran::parser::FlushStmt &stmt) {
1705     mlir::Value iostat = genFlushStatement(*this, stmt);
1706     genIoConditionBranches(getEval(), stmt.v, iostat);
1707   }
1708   void genFIR(const Fortran::parser::InquireStmt &stmt) {
1709     mlir::Value iostat = genInquireStatement(*this, stmt);
1710     if (const auto *specs =
1711             std::get_if<std::list<Fortran::parser::InquireSpec>>(&stmt.u))
1712       genIoConditionBranches(getEval(), *specs, iostat);
1713   }
1714   void genFIR(const Fortran::parser::OpenStmt &stmt) {
1715     mlir::Value iostat = genOpenStatement(*this, stmt);
1716     genIoConditionBranches(getEval(), stmt.v, iostat);
1717   }
1718   void genFIR(const Fortran::parser::PrintStmt &stmt) {
1719     genPrintStatement(*this, stmt);
1720   }
1721   void genFIR(const Fortran::parser::ReadStmt &stmt) {
1722     mlir::Value iostat = genReadStatement(*this, stmt);
1723     genIoConditionBranches(getEval(), stmt.controls, iostat);
1724   }
1725   void genFIR(const Fortran::parser::RewindStmt &stmt) {
1726     mlir::Value iostat = genRewindStatement(*this, stmt);
1727     genIoConditionBranches(getEval(), stmt.v, iostat);
1728   }
1729   void genFIR(const Fortran::parser::WaitStmt &stmt) {
1730     mlir::Value iostat = genWaitStatement(*this, stmt);
1731     genIoConditionBranches(getEval(), stmt.v, iostat);
1732   }
1733   void genFIR(const Fortran::parser::WriteStmt &stmt) {
1734     mlir::Value iostat = genWriteStatement(*this, stmt);
1735     genIoConditionBranches(getEval(), stmt.controls, iostat);
1736   }
1737 
1738   template <typename A>
1739   void genIoConditionBranches(Fortran::lower::pft::Evaluation &eval,
1740                               const A &specList, mlir::Value iostat) {
1741     if (!iostat)
1742       return;
1743 
1744     mlir::Block *endBlock = nullptr;
1745     mlir::Block *eorBlock = nullptr;
1746     mlir::Block *errBlock = nullptr;
1747     for (const auto &spec : specList) {
1748       std::visit(Fortran::common::visitors{
1749                      [&](const Fortran::parser::EndLabel &label) {
1750                        endBlock = blockOfLabel(eval, label.v);
1751                      },
1752                      [&](const Fortran::parser::EorLabel &label) {
1753                        eorBlock = blockOfLabel(eval, label.v);
1754                      },
1755                      [&](const Fortran::parser::ErrLabel &label) {
1756                        errBlock = blockOfLabel(eval, label.v);
1757                      },
1758                      [](const auto &) {}},
1759                  spec.u);
1760     }
1761     if (!endBlock && !eorBlock && !errBlock)
1762       return;
1763 
1764     mlir::Location loc = toLocation();
1765     mlir::Type indexType = builder->getIndexType();
1766     mlir::Value selector = builder->createConvert(loc, indexType, iostat);
1767     llvm::SmallVector<int64_t> indexList;
1768     llvm::SmallVector<mlir::Block *> blockList;
1769     if (eorBlock) {
1770       indexList.push_back(Fortran::runtime::io::IostatEor);
1771       blockList.push_back(eorBlock);
1772     }
1773     if (endBlock) {
1774       indexList.push_back(Fortran::runtime::io::IostatEnd);
1775       blockList.push_back(endBlock);
1776     }
1777     if (errBlock) {
1778       indexList.push_back(0);
1779       blockList.push_back(eval.nonNopSuccessor().block);
1780       // ERR label statement is the default successor.
1781       blockList.push_back(errBlock);
1782     } else {
1783       // Fallthrough successor statement is the default successor.
1784       blockList.push_back(eval.nonNopSuccessor().block);
1785     }
1786     builder->create<fir::SelectOp>(loc, selector, indexList, blockList);
1787   }
1788 
1789   //===--------------------------------------------------------------------===//
1790   // Memory allocation and deallocation
1791   //===--------------------------------------------------------------------===//
1792 
1793   void genFIR(const Fortran::parser::AllocateStmt &stmt) {
1794     Fortran::lower::genAllocateStmt(*this, stmt, toLocation());
1795   }
1796 
1797   void genFIR(const Fortran::parser::DeallocateStmt &stmt) {
1798     Fortran::lower::genDeallocateStmt(*this, stmt, toLocation());
1799   }
1800 
1801   /// Nullify pointer object list
1802   ///
1803   /// For each pointer object, reset the pointer to a disassociated status.
1804   /// We do this by setting each pointer to null.
1805   void genFIR(const Fortran::parser::NullifyStmt &stmt) {
1806     mlir::Location loc = toLocation();
1807     for (auto &pointerObject : stmt.v) {
1808       const Fortran::lower::SomeExpr *expr =
1809           Fortran::semantics::GetExpr(pointerObject);
1810       assert(expr);
1811       fir::MutableBoxValue box = genExprMutableBox(loc, *expr);
1812       fir::factory::disassociateMutableBox(*builder, loc, box);
1813     }
1814   }
1815 
1816   //===--------------------------------------------------------------------===//
1817 
1818   void genFIR(const Fortran::parser::EventPostStmt &stmt) {
1819     genEventPostStatement(*this, stmt);
1820   }
1821 
1822   void genFIR(const Fortran::parser::EventWaitStmt &stmt) {
1823     genEventWaitStatement(*this, stmt);
1824   }
1825 
1826   void genFIR(const Fortran::parser::FormTeamStmt &stmt) {
1827     genFormTeamStatement(*this, getEval(), stmt);
1828   }
1829 
1830   void genFIR(const Fortran::parser::LockStmt &stmt) {
1831     genLockStatement(*this, stmt);
1832   }
1833 
1834   fir::ExtendedValue
1835   genInitializerExprValue(const Fortran::lower::SomeExpr &expr,
1836                           Fortran::lower::StatementContext &stmtCtx) {
1837     return Fortran::lower::createSomeInitializerExpression(
1838         toLocation(), *this, expr, localSymbols, stmtCtx);
1839   }
1840 
1841   /// Return true if the current context is a conditionalized and implied
1842   /// iteration space.
1843   bool implicitIterationSpace() { return !implicitIterSpace.empty(); }
1844 
1845   /// Return true if context is currently an explicit iteration space. A scalar
1846   /// assignment expression may be contextually within a user-defined iteration
1847   /// space, transforming it into an array expression.
1848   bool explicitIterationSpace() { return explicitIterSpace.isActive(); }
1849 
1850   /// Generate an array assignment.
1851   /// This is an assignment expression with rank > 0. The assignment may or may
1852   /// not be in a WHERE and/or FORALL context.
1853   void genArrayAssignment(const Fortran::evaluate::Assignment &assign,
1854                           Fortran::lower::StatementContext &stmtCtx) {
1855     if (isWholeAllocatable(assign.lhs)) {
1856       // Assignment to allocatables may require the lhs to be
1857       // deallocated/reallocated. See Fortran 2018 10.2.1.3 p3
1858       Fortran::lower::createAllocatableArrayAssignment(
1859           *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace,
1860           localSymbols, stmtCtx);
1861       return;
1862     }
1863 
1864     if (!implicitIterationSpace() && !explicitIterationSpace()) {
1865       // No masks and the iteration space is implied by the array, so create a
1866       // simple array assignment.
1867       Fortran::lower::createSomeArrayAssignment(*this, assign.lhs, assign.rhs,
1868                                                 localSymbols, stmtCtx);
1869       return;
1870     }
1871 
1872     // If there is an explicit iteration space, generate an array assignment
1873     // with a user-specified iteration space and possibly with masks. These
1874     // assignments may *appear* to be scalar expressions, but the scalar
1875     // expression is evaluated at all points in the user-defined space much like
1876     // an ordinary array assignment. More specifically, the semantics inside the
1877     // FORALL much more closely resembles that of WHERE than a scalar
1878     // assignment.
1879     // Otherwise, generate a masked array assignment. The iteration space is
1880     // implied by the lhs array expression.
1881     Fortran::lower::createAnyMaskedArrayAssignment(
1882         *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace,
1883         localSymbols,
1884         explicitIterationSpace() ? explicitIterSpace.stmtContext()
1885                                  : implicitIterSpace.stmtContext());
1886   }
1887 
1888   static bool
1889   isArraySectionWithoutVectorSubscript(const Fortran::lower::SomeExpr &expr) {
1890     return expr.Rank() > 0 && Fortran::evaluate::IsVariable(expr) &&
1891            !Fortran::evaluate::UnwrapWholeSymbolDataRef(expr) &&
1892            !Fortran::evaluate::HasVectorSubscript(expr);
1893   }
1894 
1895 #if !defined(NDEBUG)
1896   static bool isFuncResultDesignator(const Fortran::lower::SomeExpr &expr) {
1897     const Fortran::semantics::Symbol *sym =
1898         Fortran::evaluate::GetFirstSymbol(expr);
1899     return sym && sym->IsFuncResult();
1900   }
1901 #endif
1902 
1903   static bool isWholeAllocatable(const Fortran::lower::SomeExpr &expr) {
1904     const Fortran::semantics::Symbol *sym =
1905         Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(expr);
1906     return sym && Fortran::semantics::IsAllocatable(*sym);
1907   }
1908 
1909   /// Shared for both assignments and pointer assignments.
1910   void genAssignment(const Fortran::evaluate::Assignment &assign) {
1911     Fortran::lower::StatementContext stmtCtx;
1912     mlir::Location loc = toLocation();
1913     if (explicitIterationSpace()) {
1914       Fortran::lower::createArrayLoads(*this, explicitIterSpace, localSymbols);
1915       explicitIterSpace.genLoopNest();
1916     }
1917     std::visit(
1918         Fortran::common::visitors{
1919             // [1] Plain old assignment.
1920             [&](const Fortran::evaluate::Assignment::Intrinsic &) {
1921               const Fortran::semantics::Symbol *sym =
1922                   Fortran::evaluate::GetLastSymbol(assign.lhs);
1923 
1924               if (!sym)
1925                 TODO(loc, "assignment to pointer result of function reference");
1926 
1927               std::optional<Fortran::evaluate::DynamicType> lhsType =
1928                   assign.lhs.GetType();
1929               assert(lhsType && "lhs cannot be typeless");
1930               // Assignment to polymorphic allocatables may require changing the
1931               // variable dynamic type (See Fortran 2018 10.2.1.3 p3).
1932               if (lhsType->IsPolymorphic() && isWholeAllocatable(assign.lhs))
1933                 TODO(loc, "assignment to polymorphic allocatable");
1934 
1935               // Note: No ad-hoc handling for pointers is required here. The
1936               // target will be assigned as per 2018 10.2.1.3 p2. genExprAddr
1937               // on a pointer returns the target address and not the address of
1938               // the pointer variable.
1939 
1940               if (assign.lhs.Rank() > 0 || explicitIterationSpace()) {
1941                 // Array assignment
1942                 // See Fortran 2018 10.2.1.3 p5, p6, and p7
1943                 genArrayAssignment(assign, stmtCtx);
1944                 return;
1945               }
1946 
1947               // Scalar assignment
1948               const bool isNumericScalar =
1949                   isNumericScalarCategory(lhsType->category());
1950               fir::ExtendedValue rhs = isNumericScalar
1951                                            ? genExprValue(assign.rhs, stmtCtx)
1952                                            : genExprAddr(assign.rhs, stmtCtx);
1953               bool lhsIsWholeAllocatable = isWholeAllocatable(assign.lhs);
1954               llvm::Optional<fir::factory::MutableBoxReallocation> lhsRealloc;
1955               llvm::Optional<fir::MutableBoxValue> lhsMutableBox;
1956               auto lhs = [&]() -> fir::ExtendedValue {
1957                 if (lhsIsWholeAllocatable) {
1958                   lhsMutableBox = genExprMutableBox(loc, assign.lhs);
1959                   llvm::SmallVector<mlir::Value> lengthParams;
1960                   if (const fir::CharBoxValue *charBox = rhs.getCharBox())
1961                     lengthParams.push_back(charBox->getLen());
1962                   else if (fir::isDerivedWithLengthParameters(rhs))
1963                     TODO(loc, "assignment to derived type allocatable with "
1964                               "length parameters");
1965                   lhsRealloc = fir::factory::genReallocIfNeeded(
1966                       *builder, loc, *lhsMutableBox,
1967                       /*shape=*/llvm::None, lengthParams);
1968                   return lhsRealloc->newValue;
1969                 }
1970                 return genExprAddr(assign.lhs, stmtCtx);
1971               }();
1972 
1973               if (isNumericScalar) {
1974                 // Fortran 2018 10.2.1.3 p8 and p9
1975                 // Conversions should have been inserted by semantic analysis,
1976                 // but they can be incorrect between the rhs and lhs. Correct
1977                 // that here.
1978                 mlir::Value addr = fir::getBase(lhs);
1979                 mlir::Value val = fir::getBase(rhs);
1980                 // A function with multiple entry points returning different
1981                 // types tags all result variables with one of the largest
1982                 // types to allow them to share the same storage.  Assignment
1983                 // to a result variable of one of the other types requires
1984                 // conversion to the actual type.
1985                 mlir::Type toTy = genType(assign.lhs);
1986                 mlir::Value cast =
1987                     builder->convertWithSemantics(loc, toTy, val);
1988                 if (fir::dyn_cast_ptrEleTy(addr.getType()) != toTy) {
1989                   assert(isFuncResultDesignator(assign.lhs) && "type mismatch");
1990                   addr = builder->createConvert(
1991                       toLocation(), builder->getRefType(toTy), addr);
1992                 }
1993                 builder->create<fir::StoreOp>(loc, cast, addr);
1994               } else if (isCharacterCategory(lhsType->category())) {
1995                 // Fortran 2018 10.2.1.3 p10 and p11
1996                 fir::factory::CharacterExprHelper{*builder, loc}.createAssign(
1997                     lhs, rhs);
1998               } else if (isDerivedCategory(lhsType->category())) {
1999                 // Fortran 2018 10.2.1.3 p13 and p14
2000                 // Recursively gen an assignment on each element pair.
2001                 fir::factory::genRecordAssignment(*builder, loc, lhs, rhs);
2002               } else {
2003                 llvm_unreachable("unknown category");
2004               }
2005               if (lhsIsWholeAllocatable)
2006                 fir::factory::finalizeRealloc(
2007                     *builder, loc, lhsMutableBox.getValue(),
2008                     /*lbounds=*/llvm::None, /*takeLboundsIfRealloc=*/false,
2009                     lhsRealloc.getValue());
2010             },
2011 
2012             // [2] User defined assignment. If the context is a scalar
2013             // expression then call the procedure.
2014             [&](const Fortran::evaluate::ProcedureRef &procRef) {
2015               Fortran::lower::StatementContext &ctx =
2016                   explicitIterationSpace() ? explicitIterSpace.stmtContext()
2017                                            : stmtCtx;
2018               Fortran::lower::createSubroutineCall(
2019                   *this, procRef, explicitIterSpace, implicitIterSpace,
2020                   localSymbols, ctx, /*isUserDefAssignment=*/true);
2021             },
2022 
2023             // [3] Pointer assignment with possibly empty bounds-spec. R1035: a
2024             // bounds-spec is a lower bound value.
2025             [&](const Fortran::evaluate::Assignment::BoundsSpec &lbExprs) {
2026               if (IsProcedure(assign.rhs))
2027                 TODO(loc, "procedure pointer assignment");
2028               std::optional<Fortran::evaluate::DynamicType> lhsType =
2029                   assign.lhs.GetType();
2030               std::optional<Fortran::evaluate::DynamicType> rhsType =
2031                   assign.rhs.GetType();
2032               // Polymorphic lhs/rhs may need more care. See F2018 10.2.2.3.
2033               if ((lhsType && lhsType->IsPolymorphic()) ||
2034                   (rhsType && rhsType->IsPolymorphic()))
2035                 TODO(loc, "pointer assignment involving polymorphic entity");
2036 
2037               // FIXME: in the explicit space context, we want to use
2038               // ScalarArrayExprLowering here.
2039               fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs);
2040               llvm::SmallVector<mlir::Value> lbounds;
2041               for (const Fortran::evaluate::ExtentExpr &lbExpr : lbExprs)
2042                 lbounds.push_back(
2043                     fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx)));
2044               Fortran::lower::associateMutableBox(*this, loc, lhs, assign.rhs,
2045                                                   lbounds, stmtCtx);
2046               if (explicitIterationSpace()) {
2047                 mlir::ValueRange inners = explicitIterSpace.getInnerArgs();
2048                 if (!inners.empty()) {
2049                   // TODO: should force a copy-in/copy-out here.
2050                   // e.g., obj%ptr(i+1) => obj%ptr(i)
2051                   builder->create<fir::ResultOp>(loc, inners);
2052                 }
2053               }
2054             },
2055 
2056             // [4] Pointer assignment with bounds-remapping. R1036: a
2057             // bounds-remapping is a pair, lower bound and upper bound.
2058             [&](const Fortran::evaluate::Assignment::BoundsRemapping
2059                     &boundExprs) {
2060               std::optional<Fortran::evaluate::DynamicType> lhsType =
2061                   assign.lhs.GetType();
2062               std::optional<Fortran::evaluate::DynamicType> rhsType =
2063                   assign.rhs.GetType();
2064               // Polymorphic lhs/rhs may need more care. See F2018 10.2.2.3.
2065               if ((lhsType && lhsType->IsPolymorphic()) ||
2066                   (rhsType && rhsType->IsPolymorphic()))
2067                 TODO(loc, "pointer assignment involving polymorphic entity");
2068 
2069               // FIXME: in the explicit space context, we want to use
2070               // ScalarArrayExprLowering here.
2071               fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs);
2072               if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
2073                       assign.rhs)) {
2074                 fir::factory::disassociateMutableBox(*builder, loc, lhs);
2075                 return;
2076               }
2077               llvm::SmallVector<mlir::Value> lbounds;
2078               llvm::SmallVector<mlir::Value> ubounds;
2079               for (const std::pair<Fortran::evaluate::ExtentExpr,
2080                                    Fortran::evaluate::ExtentExpr> &pair :
2081                    boundExprs) {
2082                 const Fortran::evaluate::ExtentExpr &lbExpr = pair.first;
2083                 const Fortran::evaluate::ExtentExpr &ubExpr = pair.second;
2084                 lbounds.push_back(
2085                     fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx)));
2086                 ubounds.push_back(
2087                     fir::getBase(genExprValue(toEvExpr(ubExpr), stmtCtx)));
2088               }
2089               // Do not generate a temp in case rhs is an array section.
2090               fir::ExtendedValue rhs =
2091                   isArraySectionWithoutVectorSubscript(assign.rhs)
2092                       ? Fortran::lower::createSomeArrayBox(
2093                             *this, assign.rhs, localSymbols, stmtCtx)
2094                       : genExprAddr(assign.rhs, stmtCtx);
2095               fir::factory::associateMutableBoxWithRemap(*builder, loc, lhs,
2096                                                          rhs, lbounds, ubounds);
2097               if (explicitIterationSpace()) {
2098                 mlir::ValueRange inners = explicitIterSpace.getInnerArgs();
2099                 if (!inners.empty()) {
2100                   // TODO: should force a copy-in/copy-out here.
2101                   // e.g., obj%ptr(i+1) => obj%ptr(i)
2102                   builder->create<fir::ResultOp>(loc, inners);
2103                 }
2104               }
2105             },
2106         },
2107         assign.u);
2108     if (explicitIterationSpace())
2109       Fortran::lower::createArrayMergeStores(*this, explicitIterSpace);
2110   }
2111 
2112   void genFIR(const Fortran::parser::WhereConstruct &c) {
2113     implicitIterSpace.growStack();
2114     genNestedStatement(
2115         std::get<
2116             Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>(
2117             c.t));
2118     for (const auto &body :
2119          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t))
2120       genFIR(body);
2121     for (const auto &e :
2122          std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>(
2123              c.t))
2124       genFIR(e);
2125     if (const auto &e =
2126             std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>(
2127                 c.t);
2128         e.has_value())
2129       genFIR(*e);
2130     genNestedStatement(
2131         std::get<Fortran::parser::Statement<Fortran::parser::EndWhereStmt>>(
2132             c.t));
2133   }
2134   void genFIR(const Fortran::parser::WhereBodyConstruct &body) {
2135     std::visit(
2136         Fortran::common::visitors{
2137             [&](const Fortran::parser::Statement<
2138                 Fortran::parser::AssignmentStmt> &stmt) {
2139               genNestedStatement(stmt);
2140             },
2141             [&](const Fortran::parser::Statement<Fortran::parser::WhereStmt>
2142                     &stmt) { genNestedStatement(stmt); },
2143             [&](const Fortran::common::Indirection<
2144                 Fortran::parser::WhereConstruct> &c) { genFIR(c.value()); },
2145         },
2146         body.u);
2147   }
2148   void genFIR(const Fortran::parser::WhereConstructStmt &stmt) {
2149     implicitIterSpace.append(Fortran::semantics::GetExpr(
2150         std::get<Fortran::parser::LogicalExpr>(stmt.t)));
2151   }
2152   void genFIR(const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) {
2153     genNestedStatement(
2154         std::get<
2155             Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>(
2156             ew.t));
2157     for (const auto &body :
2158          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t))
2159       genFIR(body);
2160   }
2161   void genFIR(const Fortran::parser::MaskedElsewhereStmt &stmt) {
2162     implicitIterSpace.append(Fortran::semantics::GetExpr(
2163         std::get<Fortran::parser::LogicalExpr>(stmt.t)));
2164   }
2165   void genFIR(const Fortran::parser::WhereConstruct::Elsewhere &ew) {
2166     genNestedStatement(
2167         std::get<Fortran::parser::Statement<Fortran::parser::ElsewhereStmt>>(
2168             ew.t));
2169     for (const auto &body :
2170          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t))
2171       genFIR(body);
2172   }
2173   void genFIR(const Fortran::parser::ElsewhereStmt &stmt) {
2174     implicitIterSpace.append(nullptr);
2175   }
2176   void genFIR(const Fortran::parser::EndWhereStmt &) {
2177     implicitIterSpace.shrinkStack();
2178   }
2179 
2180   void genFIR(const Fortran::parser::WhereStmt &stmt) {
2181     Fortran::lower::StatementContext stmtCtx;
2182     const auto &assign = std::get<Fortran::parser::AssignmentStmt>(stmt.t);
2183     implicitIterSpace.growStack();
2184     implicitIterSpace.append(Fortran::semantics::GetExpr(
2185         std::get<Fortran::parser::LogicalExpr>(stmt.t)));
2186     genAssignment(*assign.typedAssignment->v);
2187     implicitIterSpace.shrinkStack();
2188   }
2189 
2190   void genFIR(const Fortran::parser::PointerAssignmentStmt &stmt) {
2191     genAssignment(*stmt.typedAssignment->v);
2192   }
2193 
2194   void genFIR(const Fortran::parser::AssignmentStmt &stmt) {
2195     genAssignment(*stmt.typedAssignment->v);
2196   }
2197 
2198   void genFIR(const Fortran::parser::SyncAllStmt &stmt) {
2199     genSyncAllStatement(*this, stmt);
2200   }
2201 
2202   void genFIR(const Fortran::parser::SyncImagesStmt &stmt) {
2203     genSyncImagesStatement(*this, stmt);
2204   }
2205 
2206   void genFIR(const Fortran::parser::SyncMemoryStmt &stmt) {
2207     genSyncMemoryStatement(*this, stmt);
2208   }
2209 
2210   void genFIR(const Fortran::parser::SyncTeamStmt &stmt) {
2211     genSyncTeamStatement(*this, stmt);
2212   }
2213 
2214   void genFIR(const Fortran::parser::UnlockStmt &stmt) {
2215     genUnlockStatement(*this, stmt);
2216   }
2217 
2218   void genFIR(const Fortran::parser::AssignStmt &stmt) {
2219     const Fortran::semantics::Symbol &symbol =
2220         *std::get<Fortran::parser::Name>(stmt.t).symbol;
2221     mlir::Location loc = toLocation();
2222     mlir::Value labelValue = builder->createIntegerConstant(
2223         loc, genType(symbol), std::get<Fortran::parser::Label>(stmt.t));
2224     builder->create<fir::StoreOp>(loc, labelValue, getSymbolAddress(symbol));
2225   }
2226 
2227   void genFIR(const Fortran::parser::FormatStmt &) {
2228     // do nothing.
2229 
2230     // FORMAT statements have no semantics. They may be lowered if used by a
2231     // data transfer statement.
2232   }
2233 
2234   void genFIR(const Fortran::parser::PauseStmt &stmt) {
2235     genPauseStatement(*this, stmt);
2236   }
2237 
2238   // call FAIL IMAGE in runtime
2239   void genFIR(const Fortran::parser::FailImageStmt &stmt) {
2240     genFailImageStatement(*this);
2241   }
2242 
2243   // call STOP, ERROR STOP in runtime
2244   void genFIR(const Fortran::parser::StopStmt &stmt) {
2245     genStopStatement(*this, stmt);
2246   }
2247 
2248   void genFIR(const Fortran::parser::ReturnStmt &stmt) {
2249     Fortran::lower::pft::FunctionLikeUnit *funit =
2250         getEval().getOwningProcedure();
2251     assert(funit && "not inside main program, function or subroutine");
2252     if (funit->isMainProgram()) {
2253       genExitRoutine();
2254       return;
2255     }
2256     mlir::Location loc = toLocation();
2257     if (stmt.v) {
2258       // Alternate return statement - If this is a subroutine where some
2259       // alternate entries have alternate returns, but the active entry point
2260       // does not, ignore the alternate return value.  Otherwise, assign it
2261       // to the compiler-generated result variable.
2262       const Fortran::semantics::Symbol &symbol = funit->getSubprogramSymbol();
2263       if (Fortran::semantics::HasAlternateReturns(symbol)) {
2264         Fortran::lower::StatementContext stmtCtx;
2265         const Fortran::lower::SomeExpr *expr =
2266             Fortran::semantics::GetExpr(*stmt.v);
2267         assert(expr && "missing alternate return expression");
2268         mlir::Value altReturnIndex = builder->createConvert(
2269             loc, builder->getIndexType(), createFIRExpr(loc, expr, stmtCtx));
2270         builder->create<fir::StoreOp>(loc, altReturnIndex,
2271                                       getAltReturnResult(symbol));
2272       }
2273     }
2274     // Branch to the last block of the SUBROUTINE, which has the actual return.
2275     if (!funit->finalBlock) {
2276       mlir::OpBuilder::InsertPoint insPt = builder->saveInsertionPoint();
2277       funit->finalBlock = builder->createBlock(&builder->getRegion());
2278       builder->restoreInsertionPoint(insPt);
2279     }
2280     builder->create<mlir::cf::BranchOp>(loc, funit->finalBlock);
2281   }
2282 
2283   void genFIR(const Fortran::parser::CycleStmt &) {
2284     genFIRBranch(getEval().controlSuccessor->block);
2285   }
2286   void genFIR(const Fortran::parser::ExitStmt &) {
2287     genFIRBranch(getEval().controlSuccessor->block);
2288   }
2289   void genFIR(const Fortran::parser::GotoStmt &) {
2290     genFIRBranch(getEval().controlSuccessor->block);
2291   }
2292 
2293   // Nop statements - No code, or code is generated at the construct level.
2294   void genFIR(const Fortran::parser::AssociateStmt &) {}       // nop
2295   void genFIR(const Fortran::parser::CaseStmt &) {}            // nop
2296   void genFIR(const Fortran::parser::ContinueStmt &) {}        // nop
2297   void genFIR(const Fortran::parser::ElseIfStmt &) {}          // nop
2298   void genFIR(const Fortran::parser::ElseStmt &) {}            // nop
2299   void genFIR(const Fortran::parser::EndAssociateStmt &) {}    // nop
2300   void genFIR(const Fortran::parser::EndDoStmt &) {}           // nop
2301   void genFIR(const Fortran::parser::EndFunctionStmt &) {}     // nop
2302   void genFIR(const Fortran::parser::EndIfStmt &) {}           // nop
2303   void genFIR(const Fortran::parser::EndMpSubprogramStmt &) {} // nop
2304   void genFIR(const Fortran::parser::EndSelectStmt &) {}       // nop
2305   void genFIR(const Fortran::parser::EndSubroutineStmt &) {}   // nop
2306   void genFIR(const Fortran::parser::EntryStmt &) {}           // nop
2307   void genFIR(const Fortran::parser::IfStmt &) {}              // nop
2308   void genFIR(const Fortran::parser::IfThenStmt &) {}          // nop
2309   void genFIR(const Fortran::parser::NonLabelDoStmt &) {}      // nop
2310   void genFIR(const Fortran::parser::OmpEndLoopDirective &) {} // nop
2311 
2312   void genFIR(const Fortran::parser::NamelistStmt &) {
2313     TODO(toLocation(), "NamelistStmt lowering");
2314   }
2315 
2316   /// Generate FIR for the Evaluation `eval`.
2317   void genFIR(Fortran::lower::pft::Evaluation &eval,
2318               bool unstructuredContext = true) {
2319     if (unstructuredContext) {
2320       // When transitioning from unstructured to structured code,
2321       // the structured code could be a target that starts a new block.
2322       maybeStartBlock(eval.isConstruct() && eval.lowerAsStructured()
2323                           ? eval.getFirstNestedEvaluation().block
2324                           : eval.block);
2325     }
2326 
2327     setCurrentEval(eval);
2328     setCurrentPosition(eval.position);
2329     eval.visit([&](const auto &stmt) { genFIR(stmt); });
2330 
2331     if (unstructuredContext && blockIsUnterminated()) {
2332       // Exit from an unstructured IF or SELECT construct block.
2333       Fortran::lower::pft::Evaluation *successor{};
2334       if (eval.isActionStmt())
2335         successor = eval.controlSuccessor;
2336       else if (eval.isConstruct() &&
2337                eval.getLastNestedEvaluation()
2338                    .lexicalSuccessor->isIntermediateConstructStmt())
2339         successor = eval.constructExit;
2340       if (successor && successor->block)
2341         genFIRBranch(successor->block);
2342     }
2343   }
2344 
2345   /// Map mlir function block arguments to the corresponding Fortran dummy
2346   /// variables. When the result is passed as a hidden argument, the Fortran
2347   /// result is also mapped. The symbol map is used to hold this mapping.
2348   void mapDummiesAndResults(Fortran::lower::pft::FunctionLikeUnit &funit,
2349                             const Fortran::lower::CalleeInterface &callee) {
2350     assert(builder && "require a builder object at this point");
2351     using PassBy = Fortran::lower::CalleeInterface::PassEntityBy;
2352     auto mapPassedEntity = [&](const auto arg) -> void {
2353       if (arg.passBy == PassBy::AddressAndLength) {
2354         // TODO: now that fir call has some attributes regarding character
2355         // return, PassBy::AddressAndLength should be retired.
2356         mlir::Location loc = toLocation();
2357         fir::factory::CharacterExprHelper charHelp{*builder, loc};
2358         mlir::Value box =
2359             charHelp.createEmboxChar(arg.firArgument, arg.firLength);
2360         addSymbol(arg.entity->get(), box);
2361       } else {
2362         if (arg.entity.has_value()) {
2363           addSymbol(arg.entity->get(), arg.firArgument);
2364         } else {
2365           assert(funit.parentHasHostAssoc());
2366           funit.parentHostAssoc().internalProcedureBindings(*this,
2367                                                             localSymbols);
2368         }
2369       }
2370     };
2371     for (const Fortran::lower::CalleeInterface::PassedEntity &arg :
2372          callee.getPassedArguments())
2373       mapPassedEntity(arg);
2374 
2375     // Allocate local skeleton instances of dummies from other entry points.
2376     // Most of these locals will not survive into final generated code, but
2377     // some will.  It is illegal to reference them at run time if they do.
2378     for (const Fortran::semantics::Symbol *arg :
2379          funit.nonUniversalDummyArguments) {
2380       if (lookupSymbol(*arg))
2381         continue;
2382       mlir::Type type = genType(*arg);
2383       // TODO: Account for VALUE arguments (and possibly other variants).
2384       type = builder->getRefType(type);
2385       addSymbol(*arg, builder->create<fir::UndefOp>(toLocation(), type));
2386     }
2387     if (std::optional<Fortran::lower::CalleeInterface::PassedEntity>
2388             passedResult = callee.getPassedResult()) {
2389       mapPassedEntity(*passedResult);
2390       // FIXME: need to make sure things are OK here. addSymbol may not be OK
2391       if (funit.primaryResult &&
2392           passedResult->entity->get() != *funit.primaryResult)
2393         addSymbol(*funit.primaryResult,
2394                   getSymbolAddress(passedResult->entity->get()));
2395     }
2396   }
2397 
2398   /// Instantiate variable \p var and add it to the symbol map.
2399   /// See ConvertVariable.cpp.
2400   void instantiateVar(const Fortran::lower::pft::Variable &var,
2401                       Fortran::lower::AggregateStoreMap &storeMap) {
2402     Fortran::lower::instantiateVariable(*this, var, localSymbols, storeMap);
2403   }
2404 
2405   /// Prepare to translate a new function
2406   void startNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) {
2407     assert(!builder && "expected nullptr");
2408     Fortran::lower::CalleeInterface callee(funit, *this);
2409     mlir::func::FuncOp func = callee.addEntryBlockAndMapArguments();
2410     builder = new fir::FirOpBuilder(func, bridge.getKindMap());
2411     assert(builder && "FirOpBuilder did not instantiate");
2412     builder->setInsertionPointToStart(&func.front());
2413     func.setVisibility(mlir::SymbolTable::Visibility::Public);
2414 
2415     mapDummiesAndResults(funit, callee);
2416 
2417     // Note: not storing Variable references because getOrderedSymbolTable
2418     // below returns a temporary.
2419     llvm::SmallVector<Fortran::lower::pft::Variable> deferredFuncResultList;
2420 
2421     // Backup actual argument for entry character results
2422     // with different lengths. It needs to be added to the non
2423     // primary results symbol before mapSymbolAttributes is called.
2424     Fortran::lower::SymbolBox resultArg;
2425     if (std::optional<Fortran::lower::CalleeInterface::PassedEntity>
2426             passedResult = callee.getPassedResult())
2427       resultArg = lookupSymbol(passedResult->entity->get());
2428 
2429     Fortran::lower::AggregateStoreMap storeMap;
2430     // The front-end is currently not adding module variables referenced
2431     // in a module procedure as host associated. As a result we need to
2432     // instantiate all module variables here if this is a module procedure.
2433     // It is likely that the front-end behavior should change here.
2434     // This also applies to internal procedures inside module procedures.
2435     if (auto *module = Fortran::lower::pft::getAncestor<
2436             Fortran::lower::pft::ModuleLikeUnit>(funit))
2437       for (const Fortran::lower::pft::Variable &var :
2438            module->getOrderedSymbolTable())
2439         instantiateVar(var, storeMap);
2440 
2441     mlir::Value primaryFuncResultStorage;
2442     for (const Fortran::lower::pft::Variable &var :
2443          funit.getOrderedSymbolTable()) {
2444       // Always instantiate aggregate storage blocks.
2445       if (var.isAggregateStore()) {
2446         instantiateVar(var, storeMap);
2447         continue;
2448       }
2449       const Fortran::semantics::Symbol &sym = var.getSymbol();
2450       if (funit.parentHasHostAssoc()) {
2451         // Never instantitate host associated variables, as they are already
2452         // instantiated from an argument tuple. Instead, just bind the symbol to
2453         // the reference to the host variable, which must be in the map.
2454         const Fortran::semantics::Symbol &ultimate = sym.GetUltimate();
2455         if (funit.parentHostAssoc().isAssociated(ultimate)) {
2456           Fortran::lower::SymbolBox hostBox =
2457               localSymbols.lookupSymbol(ultimate);
2458           assert(hostBox && "host association is not in map");
2459           localSymbols.addSymbol(sym, hostBox.toExtendedValue());
2460           continue;
2461         }
2462       }
2463       if (!sym.IsFuncResult() || !funit.primaryResult) {
2464         instantiateVar(var, storeMap);
2465       } else if (&sym == funit.primaryResult) {
2466         instantiateVar(var, storeMap);
2467         primaryFuncResultStorage = getSymbolAddress(sym);
2468       } else {
2469         deferredFuncResultList.push_back(var);
2470       }
2471     }
2472 
2473     // If this is a host procedure with host associations, then create the tuple
2474     // of pointers for passing to the internal procedures.
2475     if (!funit.getHostAssoc().empty())
2476       funit.getHostAssoc().hostProcedureBindings(*this, localSymbols);
2477 
2478     /// TODO: should use same mechanism as equivalence?
2479     /// One blocking point is character entry returns that need special handling
2480     /// since they are not locally allocated but come as argument. CHARACTER(*)
2481     /// is not something that fit wells with equivalence lowering.
2482     for (const Fortran::lower::pft::Variable &altResult :
2483          deferredFuncResultList) {
2484       if (std::optional<Fortran::lower::CalleeInterface::PassedEntity>
2485               passedResult = callee.getPassedResult())
2486         addSymbol(altResult.getSymbol(), resultArg.getAddr());
2487       Fortran::lower::StatementContext stmtCtx;
2488       Fortran::lower::mapSymbolAttributes(*this, altResult, localSymbols,
2489                                           stmtCtx, primaryFuncResultStorage);
2490     }
2491 
2492     // Create most function blocks in advance.
2493     createEmptyBlocks(funit.evaluationList);
2494 
2495     // Reinstate entry block as the current insertion point.
2496     builder->setInsertionPointToEnd(&func.front());
2497 
2498     if (callee.hasAlternateReturns()) {
2499       // Create a local temp to hold the alternate return index.
2500       // Give it an integer index type and the subroutine name (for dumps).
2501       // Attach it to the subroutine symbol in the localSymbols map.
2502       // Initialize it to zero, the "fallthrough" alternate return value.
2503       const Fortran::semantics::Symbol &symbol = funit.getSubprogramSymbol();
2504       mlir::Location loc = toLocation();
2505       mlir::Type idxTy = builder->getIndexType();
2506       mlir::Value altResult =
2507           builder->createTemporary(loc, idxTy, toStringRef(symbol.name()));
2508       addSymbol(symbol, altResult);
2509       mlir::Value zero = builder->createIntegerConstant(loc, idxTy, 0);
2510       builder->create<fir::StoreOp>(loc, zero, altResult);
2511     }
2512 
2513     if (Fortran::lower::pft::Evaluation *alternateEntryEval =
2514             funit.getEntryEval())
2515       genFIRBranch(alternateEntryEval->lexicalSuccessor->block);
2516   }
2517 
2518   /// Create global blocks for the current function.  This eliminates the
2519   /// distinction between forward and backward targets when generating
2520   /// branches.  A block is "global" if it can be the target of a GOTO or
2521   /// other source code branch.  A block that can only be targeted by a
2522   /// compiler generated branch is "local".  For example, a DO loop preheader
2523   /// block containing loop initialization code is global.  A loop header
2524   /// block, which is the target of the loop back edge, is local.  Blocks
2525   /// belong to a region.  Any block within a nested region must be replaced
2526   /// with a block belonging to that region.  Branches may not cross region
2527   /// boundaries.
2528   void createEmptyBlocks(
2529       std::list<Fortran::lower::pft::Evaluation> &evaluationList) {
2530     mlir::Region *region = &builder->getRegion();
2531     for (Fortran::lower::pft::Evaluation &eval : evaluationList) {
2532       if (eval.isNewBlock)
2533         eval.block = builder->createBlock(region);
2534       if (eval.isConstruct() || eval.isDirective()) {
2535         if (eval.lowerAsUnstructured()) {
2536           createEmptyBlocks(eval.getNestedEvaluations());
2537         } else if (eval.hasNestedEvaluations()) {
2538           // A structured construct that is a target starts a new block.
2539           Fortran::lower::pft::Evaluation &constructStmt =
2540               eval.getFirstNestedEvaluation();
2541           if (constructStmt.isNewBlock)
2542             constructStmt.block = builder->createBlock(region);
2543         }
2544       }
2545     }
2546   }
2547 
2548   /// Return the predicate: "current block does not have a terminator branch".
2549   bool blockIsUnterminated() {
2550     mlir::Block *currentBlock = builder->getBlock();
2551     return currentBlock->empty() ||
2552            !currentBlock->back().hasTrait<mlir::OpTrait::IsTerminator>();
2553   }
2554 
2555   /// Unconditionally switch code insertion to a new block.
2556   void startBlock(mlir::Block *newBlock) {
2557     assert(newBlock && "missing block");
2558     // Default termination for the current block is a fallthrough branch to
2559     // the new block.
2560     if (blockIsUnterminated())
2561       genFIRBranch(newBlock);
2562     // Some blocks may be re/started more than once, and might not be empty.
2563     // If the new block already has (only) a terminator, set the insertion
2564     // point to the start of the block.  Otherwise set it to the end.
2565     builder->setInsertionPointToStart(newBlock);
2566     if (blockIsUnterminated())
2567       builder->setInsertionPointToEnd(newBlock);
2568   }
2569 
2570   /// Conditionally switch code insertion to a new block.
2571   void maybeStartBlock(mlir::Block *newBlock) {
2572     if (newBlock)
2573       startBlock(newBlock);
2574   }
2575 
2576   /// Emit return and cleanup after the function has been translated.
2577   void endNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) {
2578     setCurrentPosition(Fortran::lower::pft::stmtSourceLoc(funit.endStmt));
2579     if (funit.isMainProgram())
2580       genExitRoutine();
2581     else
2582       genFIRProcedureExit(funit, funit.getSubprogramSymbol());
2583     funit.finalBlock = nullptr;
2584     LLVM_DEBUG(llvm::dbgs() << "*** Lowering result:\n\n"
2585                             << *builder->getFunction() << '\n');
2586     // FIXME: Simplification should happen in a normal pass, not here.
2587     mlir::IRRewriter rewriter(*builder);
2588     (void)mlir::simplifyRegions(rewriter,
2589                                 {builder->getRegion()}); // remove dead code
2590     delete builder;
2591     builder = nullptr;
2592     hostAssocTuple = mlir::Value{};
2593     localSymbols.clear();
2594   }
2595 
2596   /// Helper to generate GlobalOps when the builder is not positioned in any
2597   /// region block. This is required because the FirOpBuilder assumes it is
2598   /// always positioned inside a region block when creating globals, the easiest
2599   /// way comply is to create a dummy function and to throw it afterwards.
2600   void createGlobalOutsideOfFunctionLowering(
2601       const std::function<void()> &createGlobals) {
2602     // FIXME: get rid of the bogus function context and instantiate the
2603     // globals directly into the module.
2604     mlir::MLIRContext *context = &getMLIRContext();
2605     mlir::func::FuncOp func = fir::FirOpBuilder::createFunction(
2606         mlir::UnknownLoc::get(context), getModuleOp(),
2607         fir::NameUniquer::doGenerated("Sham"),
2608         mlir::FunctionType::get(context, llvm::None, llvm::None));
2609     func.addEntryBlock();
2610     builder = new fir::FirOpBuilder(func, bridge.getKindMap());
2611     createGlobals();
2612     if (mlir::Region *region = func.getCallableRegion())
2613       region->dropAllReferences();
2614     func.erase();
2615     delete builder;
2616     builder = nullptr;
2617     localSymbols.clear();
2618   }
2619   /// Instantiate the data from a BLOCK DATA unit.
2620   void lowerBlockData(Fortran::lower::pft::BlockDataUnit &bdunit) {
2621     createGlobalOutsideOfFunctionLowering([&]() {
2622       Fortran::lower::AggregateStoreMap fakeMap;
2623       for (const auto &[_, sym] : bdunit.symTab) {
2624         if (sym->has<Fortran::semantics::ObjectEntityDetails>()) {
2625           Fortran::lower::pft::Variable var(*sym, true);
2626           instantiateVar(var, fakeMap);
2627         }
2628       }
2629     });
2630   }
2631 
2632   /// Create fir::Global for all the common blocks that appear in the program.
2633   void
2634   lowerCommonBlocks(const Fortran::semantics::CommonBlockList &commonBlocks) {
2635     createGlobalOutsideOfFunctionLowering(
2636         [&]() { Fortran::lower::defineCommonBlocks(*this, commonBlocks); });
2637   }
2638 
2639   /// Lower a procedure (nest).
2640   void lowerFunc(Fortran::lower::pft::FunctionLikeUnit &funit) {
2641     if (!funit.isMainProgram()) {
2642       const Fortran::semantics::Symbol &procSymbol =
2643           funit.getSubprogramSymbol();
2644       if (procSymbol.owner().IsSubmodule()) {
2645         TODO(toLocation(), "support submodules");
2646         return;
2647       }
2648     }
2649     setCurrentPosition(funit.getStartingSourceLoc());
2650     for (int entryIndex = 0, last = funit.entryPointList.size();
2651          entryIndex < last; ++entryIndex) {
2652       funit.setActiveEntry(entryIndex);
2653       startNewFunction(funit); // the entry point for lowering this procedure
2654       for (Fortran::lower::pft::Evaluation &eval : funit.evaluationList)
2655         genFIR(eval);
2656       endNewFunction(funit);
2657     }
2658     funit.setActiveEntry(0);
2659     for (Fortran::lower::pft::FunctionLikeUnit &f : funit.nestedFunctions)
2660       lowerFunc(f); // internal procedure
2661   }
2662 
2663   /// Lower module variable definitions to fir::globalOp and OpenMP/OpenACC
2664   /// declarative construct.
2665   void lowerModuleDeclScope(Fortran::lower::pft::ModuleLikeUnit &mod) {
2666     setCurrentPosition(mod.getStartingSourceLoc());
2667     createGlobalOutsideOfFunctionLowering([&]() {
2668       for (const Fortran::lower::pft::Variable &var :
2669            mod.getOrderedSymbolTable()) {
2670         // Only define the variables owned by this module.
2671         const Fortran::semantics::Scope *owningScope = var.getOwningScope();
2672         if (!owningScope || mod.getScope() == *owningScope)
2673           Fortran::lower::defineModuleVariable(*this, var);
2674       }
2675       for (auto &eval : mod.evaluationList)
2676         genFIR(eval);
2677     });
2678   }
2679 
2680   /// Lower functions contained in a module.
2681   void lowerMod(Fortran::lower::pft::ModuleLikeUnit &mod) {
2682     for (Fortran::lower::pft::FunctionLikeUnit &f : mod.nestedFunctions)
2683       lowerFunc(f);
2684   }
2685 
2686   void setCurrentPosition(const Fortran::parser::CharBlock &position) {
2687     if (position != Fortran::parser::CharBlock{})
2688       currentPosition = position;
2689   }
2690 
2691   /// Set current position at the location of \p parseTreeNode. Note that the
2692   /// position is updated automatically when visiting statements, but not when
2693   /// entering higher level nodes like constructs or procedures. This helper is
2694   /// intended to cover the latter cases.
2695   template <typename A>
2696   void setCurrentPositionAt(const A &parseTreeNode) {
2697     setCurrentPosition(Fortran::parser::FindSourceLocation(parseTreeNode));
2698   }
2699 
2700   //===--------------------------------------------------------------------===//
2701   // Utility methods
2702   //===--------------------------------------------------------------------===//
2703 
2704   /// Convert a parser CharBlock to a Location
2705   mlir::Location toLocation(const Fortran::parser::CharBlock &cb) {
2706     return genLocation(cb);
2707   }
2708 
2709   mlir::Location toLocation() { return toLocation(currentPosition); }
2710   void setCurrentEval(Fortran::lower::pft::Evaluation &eval) {
2711     evalPtr = &eval;
2712   }
2713   Fortran::lower::pft::Evaluation &getEval() {
2714     assert(evalPtr);
2715     return *evalPtr;
2716   }
2717 
2718   std::optional<Fortran::evaluate::Shape>
2719   getShape(const Fortran::lower::SomeExpr &expr) {
2720     return Fortran::evaluate::GetShape(foldingContext, expr);
2721   }
2722 
2723   //===--------------------------------------------------------------------===//
2724   // Analysis on a nested explicit iteration space.
2725   //===--------------------------------------------------------------------===//
2726 
2727   void analyzeExplicitSpace(const Fortran::parser::ConcurrentHeader &header) {
2728     explicitIterSpace.pushLevel();
2729     for (const Fortran::parser::ConcurrentControl &ctrl :
2730          std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) {
2731       const Fortran::semantics::Symbol *ctrlVar =
2732           std::get<Fortran::parser::Name>(ctrl.t).symbol;
2733       explicitIterSpace.addSymbol(ctrlVar);
2734     }
2735     if (const auto &mask =
2736             std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>(
2737                 header.t);
2738         mask.has_value())
2739       analyzeExplicitSpace(*Fortran::semantics::GetExpr(*mask));
2740   }
2741   template <bool LHS = false, typename A>
2742   void analyzeExplicitSpace(const Fortran::evaluate::Expr<A> &e) {
2743     explicitIterSpace.exprBase(&e, LHS);
2744   }
2745   void analyzeExplicitSpace(const Fortran::evaluate::Assignment *assign) {
2746     auto analyzeAssign = [&](const Fortran::lower::SomeExpr &lhs,
2747                              const Fortran::lower::SomeExpr &rhs) {
2748       analyzeExplicitSpace</*LHS=*/true>(lhs);
2749       analyzeExplicitSpace(rhs);
2750     };
2751     std::visit(
2752         Fortran::common::visitors{
2753             [&](const Fortran::evaluate::ProcedureRef &procRef) {
2754               // Ensure the procRef expressions are the one being visited.
2755               assert(procRef.arguments().size() == 2);
2756               const Fortran::lower::SomeExpr *lhs =
2757                   procRef.arguments()[0].value().UnwrapExpr();
2758               const Fortran::lower::SomeExpr *rhs =
2759                   procRef.arguments()[1].value().UnwrapExpr();
2760               assert(lhs && rhs &&
2761                      "user defined assignment arguments must be expressions");
2762               analyzeAssign(*lhs, *rhs);
2763             },
2764             [&](const auto &) { analyzeAssign(assign->lhs, assign->rhs); }},
2765         assign->u);
2766     explicitIterSpace.endAssign();
2767   }
2768   void analyzeExplicitSpace(const Fortran::parser::ForallAssignmentStmt &stmt) {
2769     std::visit([&](const auto &s) { analyzeExplicitSpace(s); }, stmt.u);
2770   }
2771   void analyzeExplicitSpace(const Fortran::parser::AssignmentStmt &s) {
2772     analyzeExplicitSpace(s.typedAssignment->v.operator->());
2773   }
2774   void analyzeExplicitSpace(const Fortran::parser::PointerAssignmentStmt &s) {
2775     analyzeExplicitSpace(s.typedAssignment->v.operator->());
2776   }
2777   void analyzeExplicitSpace(const Fortran::parser::WhereConstruct &c) {
2778     analyzeExplicitSpace(
2779         std::get<
2780             Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>(
2781             c.t)
2782             .statement);
2783     for (const Fortran::parser::WhereBodyConstruct &body :
2784          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t))
2785       analyzeExplicitSpace(body);
2786     for (const Fortran::parser::WhereConstruct::MaskedElsewhere &e :
2787          std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>(
2788              c.t))
2789       analyzeExplicitSpace(e);
2790     if (const auto &e =
2791             std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>(
2792                 c.t);
2793         e.has_value())
2794       analyzeExplicitSpace(e.operator->());
2795   }
2796   void analyzeExplicitSpace(const Fortran::parser::WhereConstructStmt &ws) {
2797     const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr(
2798         std::get<Fortran::parser::LogicalExpr>(ws.t));
2799     addMaskVariable(exp);
2800     analyzeExplicitSpace(*exp);
2801   }
2802   void analyzeExplicitSpace(
2803       const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) {
2804     analyzeExplicitSpace(
2805         std::get<
2806             Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>(
2807             ew.t)
2808             .statement);
2809     for (const Fortran::parser::WhereBodyConstruct &e :
2810          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t))
2811       analyzeExplicitSpace(e);
2812   }
2813   void analyzeExplicitSpace(const Fortran::parser::WhereBodyConstruct &body) {
2814     std::visit(Fortran::common::visitors{
2815                    [&](const Fortran::common::Indirection<
2816                        Fortran::parser::WhereConstruct> &wc) {
2817                      analyzeExplicitSpace(wc.value());
2818                    },
2819                    [&](const auto &s) { analyzeExplicitSpace(s.statement); }},
2820                body.u);
2821   }
2822   void analyzeExplicitSpace(const Fortran::parser::MaskedElsewhereStmt &stmt) {
2823     const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr(
2824         std::get<Fortran::parser::LogicalExpr>(stmt.t));
2825     addMaskVariable(exp);
2826     analyzeExplicitSpace(*exp);
2827   }
2828   void
2829   analyzeExplicitSpace(const Fortran::parser::WhereConstruct::Elsewhere *ew) {
2830     for (const Fortran::parser::WhereBodyConstruct &e :
2831          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew->t))
2832       analyzeExplicitSpace(e);
2833   }
2834   void analyzeExplicitSpace(const Fortran::parser::WhereStmt &stmt) {
2835     const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr(
2836         std::get<Fortran::parser::LogicalExpr>(stmt.t));
2837     addMaskVariable(exp);
2838     analyzeExplicitSpace(*exp);
2839     const std::optional<Fortran::evaluate::Assignment> &assign =
2840         std::get<Fortran::parser::AssignmentStmt>(stmt.t).typedAssignment->v;
2841     assert(assign.has_value() && "WHERE has no statement");
2842     analyzeExplicitSpace(assign.operator->());
2843   }
2844   void analyzeExplicitSpace(const Fortran::parser::ForallStmt &forall) {
2845     analyzeExplicitSpace(
2846         std::get<
2847             Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
2848             forall.t)
2849             .value());
2850     analyzeExplicitSpace(std::get<Fortran::parser::UnlabeledStatement<
2851                              Fortran::parser::ForallAssignmentStmt>>(forall.t)
2852                              .statement);
2853     analyzeExplicitSpacePop();
2854   }
2855   void
2856   analyzeExplicitSpace(const Fortran::parser::ForallConstructStmt &forall) {
2857     analyzeExplicitSpace(
2858         std::get<
2859             Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
2860             forall.t)
2861             .value());
2862   }
2863   void analyzeExplicitSpace(const Fortran::parser::ForallConstruct &forall) {
2864     analyzeExplicitSpace(
2865         std::get<
2866             Fortran::parser::Statement<Fortran::parser::ForallConstructStmt>>(
2867             forall.t)
2868             .statement);
2869     for (const Fortran::parser::ForallBodyConstruct &s :
2870          std::get<std::list<Fortran::parser::ForallBodyConstruct>>(forall.t)) {
2871       std::visit(Fortran::common::visitors{
2872                      [&](const Fortran::common::Indirection<
2873                          Fortran::parser::ForallConstruct> &b) {
2874                        analyzeExplicitSpace(b.value());
2875                      },
2876                      [&](const Fortran::parser::WhereConstruct &w) {
2877                        analyzeExplicitSpace(w);
2878                      },
2879                      [&](const auto &b) { analyzeExplicitSpace(b.statement); }},
2880                  s.u);
2881     }
2882     analyzeExplicitSpacePop();
2883   }
2884 
2885   void analyzeExplicitSpacePop() { explicitIterSpace.popLevel(); }
2886 
2887   void addMaskVariable(Fortran::lower::FrontEndExpr exp) {
2888     // Note: use i8 to store bool values. This avoids round-down behavior found
2889     // with sequences of i1. That is, an array of i1 will be truncated in size
2890     // and be too small. For example, a buffer of type fir.array<7xi1> will have
2891     // 0 size.
2892     mlir::Type i64Ty = builder->getIntegerType(64);
2893     mlir::TupleType ty = fir::factory::getRaggedArrayHeaderType(*builder);
2894     mlir::Type buffTy = ty.getType(1);
2895     mlir::Type shTy = ty.getType(2);
2896     mlir::Location loc = toLocation();
2897     mlir::Value hdr = builder->createTemporary(loc, ty);
2898     // FIXME: Is there a way to create a `zeroinitializer` in LLVM-IR dialect?
2899     // For now, explicitly set lazy ragged header to all zeros.
2900     // auto nilTup = builder->createNullConstant(loc, ty);
2901     // builder->create<fir::StoreOp>(loc, nilTup, hdr);
2902     mlir::Type i32Ty = builder->getIntegerType(32);
2903     mlir::Value zero = builder->createIntegerConstant(loc, i32Ty, 0);
2904     mlir::Value zero64 = builder->createIntegerConstant(loc, i64Ty, 0);
2905     mlir::Value flags = builder->create<fir::CoordinateOp>(
2906         loc, builder->getRefType(i64Ty), hdr, zero);
2907     builder->create<fir::StoreOp>(loc, zero64, flags);
2908     mlir::Value one = builder->createIntegerConstant(loc, i32Ty, 1);
2909     mlir::Value nullPtr1 = builder->createNullConstant(loc, buffTy);
2910     mlir::Value var = builder->create<fir::CoordinateOp>(
2911         loc, builder->getRefType(buffTy), hdr, one);
2912     builder->create<fir::StoreOp>(loc, nullPtr1, var);
2913     mlir::Value two = builder->createIntegerConstant(loc, i32Ty, 2);
2914     mlir::Value nullPtr2 = builder->createNullConstant(loc, shTy);
2915     mlir::Value shape = builder->create<fir::CoordinateOp>(
2916         loc, builder->getRefType(shTy), hdr, two);
2917     builder->create<fir::StoreOp>(loc, nullPtr2, shape);
2918     implicitIterSpace.addMaskVariable(exp, var, shape, hdr);
2919     explicitIterSpace.outermostContext().attachCleanup(
2920         [builder = this->builder, hdr, loc]() {
2921           fir::runtime::genRaggedArrayDeallocate(loc, *builder, hdr);
2922         });
2923   }
2924 
2925   void createRuntimeTypeInfoGlobals() {}
2926 
2927   //===--------------------------------------------------------------------===//
2928 
2929   Fortran::lower::LoweringBridge &bridge;
2930   Fortran::evaluate::FoldingContext foldingContext;
2931   fir::FirOpBuilder *builder = nullptr;
2932   Fortran::lower::pft::Evaluation *evalPtr = nullptr;
2933   Fortran::lower::SymMap localSymbols;
2934   Fortran::parser::CharBlock currentPosition;
2935   RuntimeTypeInfoConverter runtimeTypeInfoConverter;
2936 
2937   /// WHERE statement/construct mask expression stack.
2938   Fortran::lower::ImplicitIterSpace implicitIterSpace;
2939 
2940   /// FORALL context
2941   Fortran::lower::ExplicitIterSpace explicitIterSpace;
2942 
2943   /// Tuple of host assoicated variables.
2944   mlir::Value hostAssocTuple;
2945 };
2946 
2947 } // namespace
2948 
2949 Fortran::evaluate::FoldingContext
2950 Fortran::lower::LoweringBridge::createFoldingContext() const {
2951   return {getDefaultKinds(), getIntrinsicTable()};
2952 }
2953 
2954 void Fortran::lower::LoweringBridge::lower(
2955     const Fortran::parser::Program &prg,
2956     const Fortran::semantics::SemanticsContext &semanticsContext) {
2957   std::unique_ptr<Fortran::lower::pft::Program> pft =
2958       Fortran::lower::createPFT(prg, semanticsContext);
2959   if (dumpBeforeFir)
2960     Fortran::lower::dumpPFT(llvm::errs(), *pft);
2961   FirConverter converter{*this};
2962   converter.run(*pft);
2963 }
2964 
2965 void Fortran::lower::LoweringBridge::parseSourceFile(llvm::SourceMgr &srcMgr) {
2966   mlir::OwningOpRef<mlir::ModuleOp> owningRef =
2967       mlir::parseSourceFile<mlir::ModuleOp>(srcMgr, &context);
2968   module.reset(new mlir::ModuleOp(owningRef.get().getOperation()));
2969   owningRef.release();
2970 }
2971 
2972 Fortran::lower::LoweringBridge::LoweringBridge(
2973     mlir::MLIRContext &context,
2974     const Fortran::common::IntrinsicTypeDefaultKinds &defaultKinds,
2975     const Fortran::evaluate::IntrinsicProcTable &intrinsics,
2976     const Fortran::parser::AllCookedSources &cooked, llvm::StringRef triple,
2977     fir::KindMapping &kindMap)
2978     : defaultKinds{defaultKinds}, intrinsics{intrinsics}, cooked{&cooked},
2979       context{context}, kindMap{kindMap} {
2980   // Register the diagnostic handler.
2981   context.getDiagEngine().registerHandler([](mlir::Diagnostic &diag) {
2982     llvm::raw_ostream &os = llvm::errs();
2983     switch (diag.getSeverity()) {
2984     case mlir::DiagnosticSeverity::Error:
2985       os << "error: ";
2986       break;
2987     case mlir::DiagnosticSeverity::Remark:
2988       os << "info: ";
2989       break;
2990     case mlir::DiagnosticSeverity::Warning:
2991       os << "warning: ";
2992       break;
2993     default:
2994       break;
2995     }
2996     if (!diag.getLocation().isa<mlir::UnknownLoc>())
2997       os << diag.getLocation() << ": ";
2998     os << diag << '\n';
2999     os.flush();
3000     return mlir::success();
3001   });
3002 
3003   // Create the module and attach the attributes.
3004   module = std::make_unique<mlir::ModuleOp>(
3005       mlir::ModuleOp::create(mlir::UnknownLoc::get(&context)));
3006   assert(module.get() && "module was not created");
3007   fir::setTargetTriple(*module.get(), triple);
3008   fir::setKindMapping(*module.get(), kindMap);
3009 }
3010