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