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, "internal error when processing 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) && !lp.getRegionIterArgs().empty())
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     bool skipFinalization = false;
1753     for (const auto &attr : llvm::enumerate(attrList)) {
1754       if (attr.value().isa<mlir::UnitAttr>()) {
1755         if (attrList.size() == 1)
1756           stmtCtx.finalize();
1757         genFIRBranch(*caseBlock++);
1758         break;
1759       }
1760       auto genCond = [&](mlir::Value rhs,
1761                          mlir::arith::CmpIPredicate pred) -> mlir::Value {
1762         if (!isCharSelector)
1763           return builder->create<mlir::arith::CmpIOp>(loc, pred, selector, rhs);
1764         fir::factory::CharacterExprHelper charHelper{*builder, loc};
1765         std::pair<mlir::Value, mlir::Value> lhsVal =
1766             charHelper.createUnboxChar(selector);
1767         mlir::Value &lhsAddr = lhsVal.first;
1768         mlir::Value &lhsLen = lhsVal.second;
1769         std::pair<mlir::Value, mlir::Value> rhsVal =
1770             charHelper.createUnboxChar(rhs);
1771         mlir::Value &rhsAddr = rhsVal.first;
1772         mlir::Value &rhsLen = rhsVal.second;
1773         mlir::Value result = fir::runtime::genCharCompare(
1774             *builder, loc, pred, lhsAddr, lhsLen, rhsAddr, rhsLen);
1775         if (stmtCtx.workListIsEmpty() || skipFinalization)
1776           return result;
1777         if (attr.index() == attrList.size() - 2) {
1778           stmtCtx.finalize();
1779           return result;
1780         }
1781         fir::IfOp ifOp = builder->create<fir::IfOp>(loc, result,
1782                                                     /*withElseRegion=*/false);
1783         builder->setInsertionPointToStart(&ifOp.getThenRegion().front());
1784         stmtCtx.finalizeAndKeep();
1785         builder->setInsertionPointAfter(ifOp);
1786         return result;
1787       };
1788       mlir::Block *newBlock = insertBlock(*caseBlock);
1789       if (attr.value().isa<fir::ClosedIntervalAttr>()) {
1790         mlir::Block *newBlock2 = insertBlock(*caseBlock);
1791         skipFinalization = true;
1792         mlir::Value cond =
1793             genCond(*caseValue++, mlir::arith::CmpIPredicate::sge);
1794         genFIRConditionalBranch(cond, newBlock, newBlock2);
1795         builder->setInsertionPointToEnd(newBlock);
1796         skipFinalization = false;
1797         mlir::Value cond2 =
1798             genCond(*caseValue++, mlir::arith::CmpIPredicate::sle);
1799         genFIRConditionalBranch(cond2, *caseBlock++, newBlock2);
1800         builder->setInsertionPointToEnd(newBlock2);
1801         continue;
1802       }
1803       mlir::arith::CmpIPredicate pred;
1804       if (attr.value().isa<fir::PointIntervalAttr>()) {
1805         pred = mlir::arith::CmpIPredicate::eq;
1806       } else if (attr.value().isa<fir::LowerBoundAttr>()) {
1807         pred = mlir::arith::CmpIPredicate::sge;
1808       } else {
1809         assert(attr.value().isa<fir::UpperBoundAttr>() &&
1810                "unexpected predicate");
1811         pred = mlir::arith::CmpIPredicate::sle;
1812       }
1813       mlir::Value cond = genCond(*caseValue++, pred);
1814       genFIRConditionalBranch(cond, *caseBlock++, newBlock);
1815       builder->setInsertionPointToEnd(newBlock);
1816     }
1817     assert(caseValue == valueList.end() && caseBlock == blockList.end() &&
1818            "select case list mismatch");
1819     assert(stmtCtx.workListIsEmpty() && "statement context must be empty");
1820   }
1821 
1822   fir::ExtendedValue
1823   genAssociateSelector(const Fortran::lower::SomeExpr &selector,
1824                        Fortran::lower::StatementContext &stmtCtx) {
1825     return Fortran::lower::isArraySectionWithoutVectorSubscript(selector)
1826                ? Fortran::lower::createSomeArrayBox(*this, selector,
1827                                                     localSymbols, stmtCtx)
1828                : genExprAddr(selector, stmtCtx);
1829   }
1830 
1831   void genFIR(const Fortran::parser::AssociateConstruct &) {
1832     Fortran::lower::StatementContext stmtCtx;
1833     Fortran::lower::pft::Evaluation &eval = getEval();
1834     for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) {
1835       if (auto *stmt = e.getIf<Fortran::parser::AssociateStmt>()) {
1836         if (eval.lowerAsUnstructured())
1837           maybeStartBlock(e.block);
1838         localSymbols.pushScope();
1839         for (const Fortran::parser::Association &assoc :
1840              std::get<std::list<Fortran::parser::Association>>(stmt->t)) {
1841           Fortran::semantics::Symbol &sym =
1842               *std::get<Fortran::parser::Name>(assoc.t).symbol;
1843           const Fortran::lower::SomeExpr &selector =
1844               *sym.get<Fortran::semantics::AssocEntityDetails>().expr();
1845           localSymbols.addSymbol(sym, genAssociateSelector(selector, stmtCtx));
1846         }
1847       } else if (e.getIf<Fortran::parser::EndAssociateStmt>()) {
1848         if (eval.lowerAsUnstructured())
1849           maybeStartBlock(e.block);
1850         stmtCtx.finalize();
1851         localSymbols.popScope();
1852       } else {
1853         genFIR(e);
1854       }
1855     }
1856   }
1857 
1858   void genFIR(const Fortran::parser::BlockConstruct &blockConstruct) {
1859     setCurrentPositionAt(blockConstruct);
1860     TODO(toLocation(), "BlockConstruct implementation");
1861   }
1862   void genFIR(const Fortran::parser::BlockStmt &) {
1863     TODO(toLocation(), "BlockStmt implementation");
1864   }
1865   void genFIR(const Fortran::parser::EndBlockStmt &) {
1866     TODO(toLocation(), "EndBlockStmt implementation");
1867   }
1868 
1869   void genFIR(const Fortran::parser::ChangeTeamConstruct &construct) {
1870     TODO(toLocation(), "ChangeTeamConstruct implementation");
1871   }
1872   void genFIR(const Fortran::parser::ChangeTeamStmt &stmt) {
1873     TODO(toLocation(), "ChangeTeamStmt implementation");
1874   }
1875   void genFIR(const Fortran::parser::EndChangeTeamStmt &stmt) {
1876     TODO(toLocation(), "EndChangeTeamStmt implementation");
1877   }
1878 
1879   void genFIR(const Fortran::parser::CriticalConstruct &criticalConstruct) {
1880     setCurrentPositionAt(criticalConstruct);
1881     TODO(toLocation(), "CriticalConstruct implementation");
1882   }
1883   void genFIR(const Fortran::parser::CriticalStmt &) {
1884     TODO(toLocation(), "CriticalStmt implementation");
1885   }
1886   void genFIR(const Fortran::parser::EndCriticalStmt &) {
1887     TODO(toLocation(), "EndCriticalStmt implementation");
1888   }
1889 
1890   void genFIR(const Fortran::parser::SelectRankConstruct &selectRankConstruct) {
1891     setCurrentPositionAt(selectRankConstruct);
1892     TODO(toLocation(), "SelectRankConstruct implementation");
1893   }
1894   void genFIR(const Fortran::parser::SelectRankStmt &) {
1895     TODO(toLocation(), "SelectRankStmt implementation");
1896   }
1897   void genFIR(const Fortran::parser::SelectRankCaseStmt &) {
1898     TODO(toLocation(), "SelectRankCaseStmt implementation");
1899   }
1900 
1901   void genFIR(const Fortran::parser::SelectTypeConstruct &selectTypeConstruct) {
1902     setCurrentPositionAt(selectTypeConstruct);
1903     TODO(toLocation(), "SelectTypeConstruct implementation");
1904   }
1905   void genFIR(const Fortran::parser::SelectTypeStmt &) {
1906     TODO(toLocation(), "SelectTypeStmt implementation");
1907   }
1908   void genFIR(const Fortran::parser::TypeGuardStmt &) {
1909     TODO(toLocation(), "TypeGuardStmt implementation");
1910   }
1911 
1912   //===--------------------------------------------------------------------===//
1913   // IO statements (see io.h)
1914   //===--------------------------------------------------------------------===//
1915 
1916   void genFIR(const Fortran::parser::BackspaceStmt &stmt) {
1917     mlir::Value iostat = genBackspaceStatement(*this, stmt);
1918     genIoConditionBranches(getEval(), stmt.v, iostat);
1919   }
1920   void genFIR(const Fortran::parser::CloseStmt &stmt) {
1921     mlir::Value iostat = genCloseStatement(*this, stmt);
1922     genIoConditionBranches(getEval(), stmt.v, iostat);
1923   }
1924   void genFIR(const Fortran::parser::EndfileStmt &stmt) {
1925     mlir::Value iostat = genEndfileStatement(*this, stmt);
1926     genIoConditionBranches(getEval(), stmt.v, iostat);
1927   }
1928   void genFIR(const Fortran::parser::FlushStmt &stmt) {
1929     mlir::Value iostat = genFlushStatement(*this, stmt);
1930     genIoConditionBranches(getEval(), stmt.v, iostat);
1931   }
1932   void genFIR(const Fortran::parser::InquireStmt &stmt) {
1933     mlir::Value iostat = genInquireStatement(*this, stmt);
1934     if (const auto *specs =
1935             std::get_if<std::list<Fortran::parser::InquireSpec>>(&stmt.u))
1936       genIoConditionBranches(getEval(), *specs, iostat);
1937   }
1938   void genFIR(const Fortran::parser::OpenStmt &stmt) {
1939     mlir::Value iostat = genOpenStatement(*this, stmt);
1940     genIoConditionBranches(getEval(), stmt.v, iostat);
1941   }
1942   void genFIR(const Fortran::parser::PrintStmt &stmt) {
1943     genPrintStatement(*this, stmt);
1944   }
1945   void genFIR(const Fortran::parser::ReadStmt &stmt) {
1946     mlir::Value iostat = genReadStatement(*this, stmt);
1947     genIoConditionBranches(getEval(), stmt.controls, iostat);
1948   }
1949   void genFIR(const Fortran::parser::RewindStmt &stmt) {
1950     mlir::Value iostat = genRewindStatement(*this, stmt);
1951     genIoConditionBranches(getEval(), stmt.v, iostat);
1952   }
1953   void genFIR(const Fortran::parser::WaitStmt &stmt) {
1954     mlir::Value iostat = genWaitStatement(*this, stmt);
1955     genIoConditionBranches(getEval(), stmt.v, iostat);
1956   }
1957   void genFIR(const Fortran::parser::WriteStmt &stmt) {
1958     mlir::Value iostat = genWriteStatement(*this, stmt);
1959     genIoConditionBranches(getEval(), stmt.controls, iostat);
1960   }
1961 
1962   template <typename A>
1963   void genIoConditionBranches(Fortran::lower::pft::Evaluation &eval,
1964                               const A &specList, mlir::Value iostat) {
1965     if (!iostat)
1966       return;
1967 
1968     mlir::Block *endBlock = nullptr;
1969     mlir::Block *eorBlock = nullptr;
1970     mlir::Block *errBlock = nullptr;
1971     for (const auto &spec : specList) {
1972       std::visit(Fortran::common::visitors{
1973                      [&](const Fortran::parser::EndLabel &label) {
1974                        endBlock = blockOfLabel(eval, label.v);
1975                      },
1976                      [&](const Fortran::parser::EorLabel &label) {
1977                        eorBlock = blockOfLabel(eval, label.v);
1978                      },
1979                      [&](const Fortran::parser::ErrLabel &label) {
1980                        errBlock = blockOfLabel(eval, label.v);
1981                      },
1982                      [](const auto &) {}},
1983                  spec.u);
1984     }
1985     if (!endBlock && !eorBlock && !errBlock)
1986       return;
1987 
1988     mlir::Location loc = toLocation();
1989     mlir::Type indexType = builder->getIndexType();
1990     mlir::Value selector = builder->createConvert(loc, indexType, iostat);
1991     llvm::SmallVector<int64_t> indexList;
1992     llvm::SmallVector<mlir::Block *> blockList;
1993     if (eorBlock) {
1994       indexList.push_back(Fortran::runtime::io::IostatEor);
1995       blockList.push_back(eorBlock);
1996     }
1997     if (endBlock) {
1998       indexList.push_back(Fortran::runtime::io::IostatEnd);
1999       blockList.push_back(endBlock);
2000     }
2001     if (errBlock) {
2002       indexList.push_back(0);
2003       blockList.push_back(eval.nonNopSuccessor().block);
2004       // ERR label statement is the default successor.
2005       blockList.push_back(errBlock);
2006     } else {
2007       // Fallthrough successor statement is the default successor.
2008       blockList.push_back(eval.nonNopSuccessor().block);
2009     }
2010     builder->create<fir::SelectOp>(loc, selector, indexList, blockList);
2011   }
2012 
2013   //===--------------------------------------------------------------------===//
2014   // Memory allocation and deallocation
2015   //===--------------------------------------------------------------------===//
2016 
2017   void genFIR(const Fortran::parser::AllocateStmt &stmt) {
2018     Fortran::lower::genAllocateStmt(*this, stmt, toLocation());
2019   }
2020 
2021   void genFIR(const Fortran::parser::DeallocateStmt &stmt) {
2022     Fortran::lower::genDeallocateStmt(*this, stmt, toLocation());
2023   }
2024 
2025   /// Nullify pointer object list
2026   ///
2027   /// For each pointer object, reset the pointer to a disassociated status.
2028   /// We do this by setting each pointer to null.
2029   void genFIR(const Fortran::parser::NullifyStmt &stmt) {
2030     mlir::Location loc = toLocation();
2031     for (auto &pointerObject : stmt.v) {
2032       const Fortran::lower::SomeExpr *expr =
2033           Fortran::semantics::GetExpr(pointerObject);
2034       assert(expr);
2035       fir::MutableBoxValue box = genExprMutableBox(loc, *expr);
2036       fir::factory::disassociateMutableBox(*builder, loc, box);
2037     }
2038   }
2039 
2040   //===--------------------------------------------------------------------===//
2041 
2042   void genFIR(const Fortran::parser::EventPostStmt &stmt) {
2043     genEventPostStatement(*this, stmt);
2044   }
2045 
2046   void genFIR(const Fortran::parser::EventWaitStmt &stmt) {
2047     genEventWaitStatement(*this, stmt);
2048   }
2049 
2050   void genFIR(const Fortran::parser::FormTeamStmt &stmt) {
2051     genFormTeamStatement(*this, getEval(), stmt);
2052   }
2053 
2054   void genFIR(const Fortran::parser::LockStmt &stmt) {
2055     genLockStatement(*this, stmt);
2056   }
2057 
2058   fir::ExtendedValue
2059   genInitializerExprValue(const Fortran::lower::SomeExpr &expr,
2060                           Fortran::lower::StatementContext &stmtCtx) {
2061     return Fortran::lower::createSomeInitializerExpression(
2062         toLocation(), *this, expr, localSymbols, stmtCtx);
2063   }
2064 
2065   /// Return true if the current context is a conditionalized and implied
2066   /// iteration space.
2067   bool implicitIterationSpace() { return !implicitIterSpace.empty(); }
2068 
2069   /// Return true if context is currently an explicit iteration space. A scalar
2070   /// assignment expression may be contextually within a user-defined iteration
2071   /// space, transforming it into an array expression.
2072   bool explicitIterationSpace() { return explicitIterSpace.isActive(); }
2073 
2074   /// Generate an array assignment.
2075   /// This is an assignment expression with rank > 0. The assignment may or may
2076   /// not be in a WHERE and/or FORALL context.
2077   /// In a FORALL context, the assignment may be a pointer assignment and the \p
2078   /// lbounds and \p ubounds parameters should only be used in such a pointer
2079   /// assignment case. (If both are None then the array assignment cannot be a
2080   /// pointer assignment.)
2081   void genArrayAssignment(
2082       const Fortran::evaluate::Assignment &assign,
2083       Fortran::lower::StatementContext &stmtCtx,
2084       llvm::Optional<llvm::SmallVector<mlir::Value>> lbounds = llvm::None,
2085       llvm::Optional<llvm::SmallVector<mlir::Value>> ubounds = llvm::None) {
2086     if (Fortran::lower::isWholeAllocatable(assign.lhs)) {
2087       // Assignment to allocatables may require the lhs to be
2088       // deallocated/reallocated. See Fortran 2018 10.2.1.3 p3
2089       Fortran::lower::createAllocatableArrayAssignment(
2090           *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace,
2091           localSymbols, stmtCtx);
2092       return;
2093     }
2094 
2095     if (lbounds) {
2096       // Array of POINTER entities, with elemental assignment.
2097       if (!Fortran::lower::isWholePointer(assign.lhs))
2098         fir::emitFatalError(toLocation(), "pointer assignment to non-pointer");
2099 
2100       Fortran::lower::createArrayOfPointerAssignment(
2101           *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace,
2102           *lbounds, ubounds, localSymbols, stmtCtx);
2103       return;
2104     }
2105 
2106     if (!implicitIterationSpace() && !explicitIterationSpace()) {
2107       // No masks and the iteration space is implied by the array, so create a
2108       // simple array assignment.
2109       Fortran::lower::createSomeArrayAssignment(*this, assign.lhs, assign.rhs,
2110                                                 localSymbols, stmtCtx);
2111       return;
2112     }
2113 
2114     // If there is an explicit iteration space, generate an array assignment
2115     // with a user-specified iteration space and possibly with masks. These
2116     // assignments may *appear* to be scalar expressions, but the scalar
2117     // expression is evaluated at all points in the user-defined space much like
2118     // an ordinary array assignment. More specifically, the semantics inside the
2119     // FORALL much more closely resembles that of WHERE than a scalar
2120     // assignment.
2121     // Otherwise, generate a masked array assignment. The iteration space is
2122     // implied by the lhs array expression.
2123     Fortran::lower::createAnyMaskedArrayAssignment(
2124         *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace,
2125         localSymbols,
2126         explicitIterationSpace() ? explicitIterSpace.stmtContext()
2127                                  : implicitIterSpace.stmtContext());
2128   }
2129 
2130 #if !defined(NDEBUG)
2131   static bool isFuncResultDesignator(const Fortran::lower::SomeExpr &expr) {
2132     const Fortran::semantics::Symbol *sym =
2133         Fortran::evaluate::GetFirstSymbol(expr);
2134     return sym && sym->IsFuncResult();
2135   }
2136 #endif
2137 
2138   inline fir::MutableBoxValue
2139   genExprMutableBox(mlir::Location loc,
2140                     const Fortran::lower::SomeExpr &expr) override final {
2141     return Fortran::lower::createMutableBox(loc, *this, expr, localSymbols);
2142   }
2143 
2144   /// Shared for both assignments and pointer assignments.
2145   void genAssignment(const Fortran::evaluate::Assignment &assign) {
2146     Fortran::lower::StatementContext stmtCtx;
2147     mlir::Location loc = toLocation();
2148     if (explicitIterationSpace()) {
2149       Fortran::lower::createArrayLoads(*this, explicitIterSpace, localSymbols);
2150       explicitIterSpace.genLoopNest();
2151     }
2152     std::visit(
2153         Fortran::common::visitors{
2154             // [1] Plain old assignment.
2155             [&](const Fortran::evaluate::Assignment::Intrinsic &) {
2156               const Fortran::semantics::Symbol *sym =
2157                   Fortran::evaluate::GetLastSymbol(assign.lhs);
2158 
2159               if (!sym)
2160                 TODO(loc, "assignment to pointer result of function reference");
2161 
2162               std::optional<Fortran::evaluate::DynamicType> lhsType =
2163                   assign.lhs.GetType();
2164               assert(lhsType && "lhs cannot be typeless");
2165               // Assignment to polymorphic allocatables may require changing the
2166               // variable dynamic type (See Fortran 2018 10.2.1.3 p3).
2167               if (lhsType->IsPolymorphic() &&
2168                   Fortran::lower::isWholeAllocatable(assign.lhs))
2169                 TODO(loc, "assignment to polymorphic allocatable");
2170 
2171               // Note: No ad-hoc handling for pointers is required here. The
2172               // target will be assigned as per 2018 10.2.1.3 p2. genExprAddr
2173               // on a pointer returns the target address and not the address of
2174               // the pointer variable.
2175 
2176               if (assign.lhs.Rank() > 0 || explicitIterationSpace()) {
2177                 // Array assignment
2178                 // See Fortran 2018 10.2.1.3 p5, p6, and p7
2179                 genArrayAssignment(assign, stmtCtx);
2180                 return;
2181               }
2182 
2183               // Scalar assignment
2184               const bool isNumericScalar =
2185                   isNumericScalarCategory(lhsType->category());
2186               fir::ExtendedValue rhs = isNumericScalar
2187                                            ? genExprValue(assign.rhs, stmtCtx)
2188                                            : genExprAddr(assign.rhs, stmtCtx);
2189               const bool lhsIsWholeAllocatable =
2190                   Fortran::lower::isWholeAllocatable(assign.lhs);
2191               llvm::Optional<fir::factory::MutableBoxReallocation> lhsRealloc;
2192               llvm::Optional<fir::MutableBoxValue> lhsMutableBox;
2193               auto lhs = [&]() -> fir::ExtendedValue {
2194                 if (lhsIsWholeAllocatable) {
2195                   lhsMutableBox = genExprMutableBox(loc, assign.lhs);
2196                   llvm::SmallVector<mlir::Value> lengthParams;
2197                   if (const fir::CharBoxValue *charBox = rhs.getCharBox())
2198                     lengthParams.push_back(charBox->getLen());
2199                   else if (fir::isDerivedWithLenParameters(rhs))
2200                     TODO(loc, "assignment to derived type allocatable with "
2201                               "LEN parameters");
2202                   lhsRealloc = fir::factory::genReallocIfNeeded(
2203                       *builder, loc, *lhsMutableBox,
2204                       /*shape=*/llvm::None, lengthParams);
2205                   return lhsRealloc->newValue;
2206                 }
2207                 return genExprAddr(assign.lhs, stmtCtx);
2208               }();
2209 
2210               if (isNumericScalar) {
2211                 // Fortran 2018 10.2.1.3 p8 and p9
2212                 // Conversions should have been inserted by semantic analysis,
2213                 // but they can be incorrect between the rhs and lhs. Correct
2214                 // that here.
2215                 mlir::Value addr = fir::getBase(lhs);
2216                 mlir::Value val = fir::getBase(rhs);
2217                 // A function with multiple entry points returning different
2218                 // types tags all result variables with one of the largest
2219                 // types to allow them to share the same storage.  Assignment
2220                 // to a result variable of one of the other types requires
2221                 // conversion to the actual type.
2222                 mlir::Type toTy = genType(assign.lhs);
2223                 mlir::Value cast =
2224                     builder->convertWithSemantics(loc, toTy, val);
2225                 if (fir::dyn_cast_ptrEleTy(addr.getType()) != toTy) {
2226                   assert(isFuncResultDesignator(assign.lhs) && "type mismatch");
2227                   addr = builder->createConvert(
2228                       toLocation(), builder->getRefType(toTy), addr);
2229                 }
2230                 builder->create<fir::StoreOp>(loc, cast, addr);
2231               } else if (isCharacterCategory(lhsType->category())) {
2232                 // Fortran 2018 10.2.1.3 p10 and p11
2233                 fir::factory::CharacterExprHelper{*builder, loc}.createAssign(
2234                     lhs, rhs);
2235               } else if (isDerivedCategory(lhsType->category())) {
2236                 // Fortran 2018 10.2.1.3 p13 and p14
2237                 // Recursively gen an assignment on each element pair.
2238                 fir::factory::genRecordAssignment(*builder, loc, lhs, rhs);
2239               } else {
2240                 llvm_unreachable("unknown category");
2241               }
2242               if (lhsIsWholeAllocatable)
2243                 fir::factory::finalizeRealloc(
2244                     *builder, loc, lhsMutableBox.getValue(),
2245                     /*lbounds=*/llvm::None, /*takeLboundsIfRealloc=*/false,
2246                     lhsRealloc.getValue());
2247             },
2248 
2249             // [2] User defined assignment. If the context is a scalar
2250             // expression then call the procedure.
2251             [&](const Fortran::evaluate::ProcedureRef &procRef) {
2252               Fortran::lower::StatementContext &ctx =
2253                   explicitIterationSpace() ? explicitIterSpace.stmtContext()
2254                                            : stmtCtx;
2255               Fortran::lower::createSubroutineCall(
2256                   *this, procRef, explicitIterSpace, implicitIterSpace,
2257                   localSymbols, ctx, /*isUserDefAssignment=*/true);
2258             },
2259 
2260             // [3] Pointer assignment with possibly empty bounds-spec. R1035: a
2261             // bounds-spec is a lower bound value.
2262             [&](const Fortran::evaluate::Assignment::BoundsSpec &lbExprs) {
2263               if (Fortran::evaluate::IsProcedure(assign.rhs))
2264                 TODO(loc, "procedure pointer assignment");
2265               std::optional<Fortran::evaluate::DynamicType> lhsType =
2266                   assign.lhs.GetType();
2267               std::optional<Fortran::evaluate::DynamicType> rhsType =
2268                   assign.rhs.GetType();
2269               // Polymorphic lhs/rhs may need more care. See F2018 10.2.2.3.
2270               if ((lhsType && lhsType->IsPolymorphic()) ||
2271                   (rhsType && rhsType->IsPolymorphic()))
2272                 TODO(loc, "pointer assignment involving polymorphic entity");
2273 
2274               llvm::SmallVector<mlir::Value> lbounds;
2275               for (const Fortran::evaluate::ExtentExpr &lbExpr : lbExprs)
2276                 lbounds.push_back(
2277                     fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx)));
2278               if (explicitIterationSpace()) {
2279                 // Pointer assignment in FORALL context. Copy the rhs box value
2280                 // into the lhs box variable.
2281                 genArrayAssignment(assign, stmtCtx, lbounds);
2282                 return;
2283               }
2284               fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs);
2285               Fortran::lower::associateMutableBox(*this, loc, lhs, assign.rhs,
2286                                                   lbounds, stmtCtx);
2287             },
2288 
2289             // [4] Pointer assignment with bounds-remapping. R1036: a
2290             // bounds-remapping is a pair, lower bound and upper bound.
2291             [&](const Fortran::evaluate::Assignment::BoundsRemapping
2292                     &boundExprs) {
2293               std::optional<Fortran::evaluate::DynamicType> lhsType =
2294                   assign.lhs.GetType();
2295               std::optional<Fortran::evaluate::DynamicType> rhsType =
2296                   assign.rhs.GetType();
2297               // Polymorphic lhs/rhs may need more care. See F2018 10.2.2.3.
2298               if ((lhsType && lhsType->IsPolymorphic()) ||
2299                   (rhsType && rhsType->IsPolymorphic()))
2300                 TODO(loc, "pointer assignment involving polymorphic entity");
2301 
2302               llvm::SmallVector<mlir::Value> lbounds;
2303               llvm::SmallVector<mlir::Value> ubounds;
2304               for (const std::pair<Fortran::evaluate::ExtentExpr,
2305                                    Fortran::evaluate::ExtentExpr> &pair :
2306                    boundExprs) {
2307                 const Fortran::evaluate::ExtentExpr &lbExpr = pair.first;
2308                 const Fortran::evaluate::ExtentExpr &ubExpr = pair.second;
2309                 lbounds.push_back(
2310                     fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx)));
2311                 ubounds.push_back(
2312                     fir::getBase(genExprValue(toEvExpr(ubExpr), stmtCtx)));
2313               }
2314               if (explicitIterationSpace()) {
2315                 // Pointer assignment in FORALL context. Copy the rhs box value
2316                 // into the lhs box variable.
2317                 genArrayAssignment(assign, stmtCtx, lbounds, ubounds);
2318                 return;
2319               }
2320               fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs);
2321               if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
2322                       assign.rhs)) {
2323                 fir::factory::disassociateMutableBox(*builder, loc, lhs);
2324                 return;
2325               }
2326               // Do not generate a temp in case rhs is an array section.
2327               fir::ExtendedValue rhs =
2328                   Fortran::lower::isArraySectionWithoutVectorSubscript(
2329                       assign.rhs)
2330                       ? Fortran::lower::createSomeArrayBox(
2331                             *this, assign.rhs, localSymbols, stmtCtx)
2332                       : genExprAddr(assign.rhs, stmtCtx);
2333               fir::factory::associateMutableBoxWithRemap(*builder, loc, lhs,
2334                                                          rhs, lbounds, ubounds);
2335               if (explicitIterationSpace()) {
2336                 mlir::ValueRange inners = explicitIterSpace.getInnerArgs();
2337                 if (!inners.empty())
2338                   builder->create<fir::ResultOp>(loc, inners);
2339               }
2340             },
2341         },
2342         assign.u);
2343     if (explicitIterationSpace())
2344       Fortran::lower::createArrayMergeStores(*this, explicitIterSpace);
2345   }
2346 
2347   void genFIR(const Fortran::parser::WhereConstruct &c) {
2348     implicitIterSpace.growStack();
2349     genNestedStatement(
2350         std::get<
2351             Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>(
2352             c.t));
2353     for (const auto &body :
2354          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t))
2355       genFIR(body);
2356     for (const auto &e :
2357          std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>(
2358              c.t))
2359       genFIR(e);
2360     if (const auto &e =
2361             std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>(
2362                 c.t);
2363         e.has_value())
2364       genFIR(*e);
2365     genNestedStatement(
2366         std::get<Fortran::parser::Statement<Fortran::parser::EndWhereStmt>>(
2367             c.t));
2368   }
2369   void genFIR(const Fortran::parser::WhereBodyConstruct &body) {
2370     std::visit(
2371         Fortran::common::visitors{
2372             [&](const Fortran::parser::Statement<
2373                 Fortran::parser::AssignmentStmt> &stmt) {
2374               genNestedStatement(stmt);
2375             },
2376             [&](const Fortran::parser::Statement<Fortran::parser::WhereStmt>
2377                     &stmt) { genNestedStatement(stmt); },
2378             [&](const Fortran::common::Indirection<
2379                 Fortran::parser::WhereConstruct> &c) { genFIR(c.value()); },
2380         },
2381         body.u);
2382   }
2383   void genFIR(const Fortran::parser::WhereConstructStmt &stmt) {
2384     implicitIterSpace.append(Fortran::semantics::GetExpr(
2385         std::get<Fortran::parser::LogicalExpr>(stmt.t)));
2386   }
2387   void genFIR(const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) {
2388     genNestedStatement(
2389         std::get<
2390             Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>(
2391             ew.t));
2392     for (const auto &body :
2393          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t))
2394       genFIR(body);
2395   }
2396   void genFIR(const Fortran::parser::MaskedElsewhereStmt &stmt) {
2397     implicitIterSpace.append(Fortran::semantics::GetExpr(
2398         std::get<Fortran::parser::LogicalExpr>(stmt.t)));
2399   }
2400   void genFIR(const Fortran::parser::WhereConstruct::Elsewhere &ew) {
2401     genNestedStatement(
2402         std::get<Fortran::parser::Statement<Fortran::parser::ElsewhereStmt>>(
2403             ew.t));
2404     for (const auto &body :
2405          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t))
2406       genFIR(body);
2407   }
2408   void genFIR(const Fortran::parser::ElsewhereStmt &stmt) {
2409     implicitIterSpace.append(nullptr);
2410   }
2411   void genFIR(const Fortran::parser::EndWhereStmt &) {
2412     implicitIterSpace.shrinkStack();
2413   }
2414 
2415   void genFIR(const Fortran::parser::WhereStmt &stmt) {
2416     Fortran::lower::StatementContext stmtCtx;
2417     const auto &assign = std::get<Fortran::parser::AssignmentStmt>(stmt.t);
2418     implicitIterSpace.growStack();
2419     implicitIterSpace.append(Fortran::semantics::GetExpr(
2420         std::get<Fortran::parser::LogicalExpr>(stmt.t)));
2421     genAssignment(*assign.typedAssignment->v);
2422     implicitIterSpace.shrinkStack();
2423   }
2424 
2425   void genFIR(const Fortran::parser::PointerAssignmentStmt &stmt) {
2426     genAssignment(*stmt.typedAssignment->v);
2427   }
2428 
2429   void genFIR(const Fortran::parser::AssignmentStmt &stmt) {
2430     genAssignment(*stmt.typedAssignment->v);
2431   }
2432 
2433   void genFIR(const Fortran::parser::SyncAllStmt &stmt) {
2434     genSyncAllStatement(*this, stmt);
2435   }
2436 
2437   void genFIR(const Fortran::parser::SyncImagesStmt &stmt) {
2438     genSyncImagesStatement(*this, stmt);
2439   }
2440 
2441   void genFIR(const Fortran::parser::SyncMemoryStmt &stmt) {
2442     genSyncMemoryStatement(*this, stmt);
2443   }
2444 
2445   void genFIR(const Fortran::parser::SyncTeamStmt &stmt) {
2446     genSyncTeamStatement(*this, stmt);
2447   }
2448 
2449   void genFIR(const Fortran::parser::UnlockStmt &stmt) {
2450     genUnlockStatement(*this, stmt);
2451   }
2452 
2453   void genFIR(const Fortran::parser::AssignStmt &stmt) {
2454     const Fortran::semantics::Symbol &symbol =
2455         *std::get<Fortran::parser::Name>(stmt.t).symbol;
2456     mlir::Location loc = toLocation();
2457     mlir::Value labelValue = builder->createIntegerConstant(
2458         loc, genType(symbol), std::get<Fortran::parser::Label>(stmt.t));
2459     builder->create<fir::StoreOp>(loc, labelValue, getSymbolAddress(symbol));
2460   }
2461 
2462   void genFIR(const Fortran::parser::FormatStmt &) {
2463     // do nothing.
2464 
2465     // FORMAT statements have no semantics. They may be lowered if used by a
2466     // data transfer statement.
2467   }
2468 
2469   void genFIR(const Fortran::parser::PauseStmt &stmt) {
2470     genPauseStatement(*this, stmt);
2471   }
2472 
2473   // call FAIL IMAGE in runtime
2474   void genFIR(const Fortran::parser::FailImageStmt &stmt) {
2475     genFailImageStatement(*this);
2476   }
2477 
2478   // call STOP, ERROR STOP in runtime
2479   void genFIR(const Fortran::parser::StopStmt &stmt) {
2480     genStopStatement(*this, stmt);
2481   }
2482 
2483   void genFIR(const Fortran::parser::ReturnStmt &stmt) {
2484     Fortran::lower::pft::FunctionLikeUnit *funit =
2485         getEval().getOwningProcedure();
2486     assert(funit && "not inside main program, function or subroutine");
2487     if (funit->isMainProgram()) {
2488       genExitRoutine();
2489       return;
2490     }
2491     mlir::Location loc = toLocation();
2492     if (stmt.v) {
2493       // Alternate return statement - If this is a subroutine where some
2494       // alternate entries have alternate returns, but the active entry point
2495       // does not, ignore the alternate return value.  Otherwise, assign it
2496       // to the compiler-generated result variable.
2497       const Fortran::semantics::Symbol &symbol = funit->getSubprogramSymbol();
2498       if (Fortran::semantics::HasAlternateReturns(symbol)) {
2499         Fortran::lower::StatementContext stmtCtx;
2500         const Fortran::lower::SomeExpr *expr =
2501             Fortran::semantics::GetExpr(*stmt.v);
2502         assert(expr && "missing alternate return expression");
2503         mlir::Value altReturnIndex = builder->createConvert(
2504             loc, builder->getIndexType(), createFIRExpr(loc, expr, stmtCtx));
2505         builder->create<fir::StoreOp>(loc, altReturnIndex,
2506                                       getAltReturnResult(symbol));
2507       }
2508     }
2509     // Branch to the last block of the SUBROUTINE, which has the actual return.
2510     if (!funit->finalBlock) {
2511       mlir::OpBuilder::InsertPoint insPt = builder->saveInsertionPoint();
2512       funit->finalBlock = builder->createBlock(&builder->getRegion());
2513       builder->restoreInsertionPoint(insPt);
2514     }
2515     builder->create<mlir::cf::BranchOp>(loc, funit->finalBlock);
2516   }
2517 
2518   void genFIR(const Fortran::parser::CycleStmt &) {
2519     genFIRBranch(getEval().controlSuccessor->block);
2520   }
2521   void genFIR(const Fortran::parser::ExitStmt &) {
2522     genFIRBranch(getEval().controlSuccessor->block);
2523   }
2524   void genFIR(const Fortran::parser::GotoStmt &) {
2525     genFIRBranch(getEval().controlSuccessor->block);
2526   }
2527 
2528   // Nop statements - No code, or code is generated at the construct level.
2529   void genFIR(const Fortran::parser::AssociateStmt &) {}       // nop
2530   void genFIR(const Fortran::parser::CaseStmt &) {}            // nop
2531   void genFIR(const Fortran::parser::ContinueStmt &) {}        // nop
2532   void genFIR(const Fortran::parser::ElseIfStmt &) {}          // nop
2533   void genFIR(const Fortran::parser::ElseStmt &) {}            // nop
2534   void genFIR(const Fortran::parser::EndAssociateStmt &) {}    // nop
2535   void genFIR(const Fortran::parser::EndDoStmt &) {}           // nop
2536   void genFIR(const Fortran::parser::EndFunctionStmt &) {}     // nop
2537   void genFIR(const Fortran::parser::EndIfStmt &) {}           // nop
2538   void genFIR(const Fortran::parser::EndMpSubprogramStmt &) {} // nop
2539   void genFIR(const Fortran::parser::EndSelectStmt &) {}       // nop
2540   void genFIR(const Fortran::parser::EndSubroutineStmt &) {}   // nop
2541   void genFIR(const Fortran::parser::EntryStmt &) {}           // nop
2542   void genFIR(const Fortran::parser::IfStmt &) {}              // nop
2543   void genFIR(const Fortran::parser::IfThenStmt &) {}          // nop
2544   void genFIR(const Fortran::parser::NonLabelDoStmt &) {}      // nop
2545   void genFIR(const Fortran::parser::OmpEndLoopDirective &) {} // nop
2546 
2547   void genFIR(const Fortran::parser::NamelistStmt &) {
2548     TODO(toLocation(), "NamelistStmt lowering");
2549   }
2550 
2551   /// Generate FIR for the Evaluation `eval`.
2552   void genFIR(Fortran::lower::pft::Evaluation &eval,
2553               bool unstructuredContext = true) {
2554     if (unstructuredContext) {
2555       // When transitioning from unstructured to structured code,
2556       // the structured code could be a target that starts a new block.
2557       maybeStartBlock(eval.isConstruct() && eval.lowerAsStructured()
2558                           ? eval.getFirstNestedEvaluation().block
2559                           : eval.block);
2560     }
2561 
2562     setCurrentEval(eval);
2563     setCurrentPosition(eval.position);
2564     eval.visit([&](const auto &stmt) { genFIR(stmt); });
2565 
2566     if (unstructuredContext && blockIsUnterminated()) {
2567       // Exit from an unstructured IF or SELECT construct block.
2568       Fortran::lower::pft::Evaluation *successor{};
2569       if (eval.isActionStmt())
2570         successor = eval.controlSuccessor;
2571       else if (eval.isConstruct() &&
2572                eval.getLastNestedEvaluation()
2573                    .lexicalSuccessor->isIntermediateConstructStmt())
2574         successor = eval.constructExit;
2575       if (successor && successor->block)
2576         genFIRBranch(successor->block);
2577     }
2578   }
2579 
2580   /// Map mlir function block arguments to the corresponding Fortran dummy
2581   /// variables. When the result is passed as a hidden argument, the Fortran
2582   /// result is also mapped. The symbol map is used to hold this mapping.
2583   void mapDummiesAndResults(Fortran::lower::pft::FunctionLikeUnit &funit,
2584                             const Fortran::lower::CalleeInterface &callee) {
2585     assert(builder && "require a builder object at this point");
2586     using PassBy = Fortran::lower::CalleeInterface::PassEntityBy;
2587     auto mapPassedEntity = [&](const auto arg) {
2588       if (arg.passBy == PassBy::AddressAndLength) {
2589         // TODO: now that fir call has some attributes regarding character
2590         // return, PassBy::AddressAndLength should be retired.
2591         mlir::Location loc = toLocation();
2592         fir::factory::CharacterExprHelper charHelp{*builder, loc};
2593         mlir::Value box =
2594             charHelp.createEmboxChar(arg.firArgument, arg.firLength);
2595         addSymbol(arg.entity->get(), box);
2596       } else {
2597         if (arg.entity.has_value()) {
2598           addSymbol(arg.entity->get(), arg.firArgument);
2599         } else {
2600           assert(funit.parentHasHostAssoc());
2601           funit.parentHostAssoc().internalProcedureBindings(*this,
2602                                                             localSymbols);
2603         }
2604       }
2605     };
2606     for (const Fortran::lower::CalleeInterface::PassedEntity &arg :
2607          callee.getPassedArguments())
2608       mapPassedEntity(arg);
2609     if (std::optional<Fortran::lower::CalleeInterface::PassedEntity>
2610             passedResult = callee.getPassedResult()) {
2611       mapPassedEntity(*passedResult);
2612       // FIXME: need to make sure things are OK here. addSymbol may not be OK
2613       if (funit.primaryResult &&
2614           passedResult->entity->get() != *funit.primaryResult)
2615         addSymbol(*funit.primaryResult,
2616                   getSymbolAddress(passedResult->entity->get()));
2617     }
2618   }
2619 
2620   /// Instantiate variable \p var and add it to the symbol map.
2621   /// See ConvertVariable.cpp.
2622   void instantiateVar(const Fortran::lower::pft::Variable &var,
2623                       Fortran::lower::AggregateStoreMap &storeMap) {
2624     Fortran::lower::instantiateVariable(*this, var, localSymbols, storeMap);
2625     if (var.hasSymbol() &&
2626         var.getSymbol().test(
2627             Fortran::semantics::Symbol::Flag::OmpThreadprivate))
2628       Fortran::lower::genThreadprivateOp(*this, var);
2629   }
2630 
2631   /// Prepare to translate a new function
2632   void startNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) {
2633     assert(!builder && "expected nullptr");
2634     Fortran::lower::CalleeInterface callee(funit, *this);
2635     mlir::func::FuncOp func = callee.addEntryBlockAndMapArguments();
2636     builder = new fir::FirOpBuilder(func, bridge.getKindMap());
2637     assert(builder && "FirOpBuilder did not instantiate");
2638     builder->setInsertionPointToStart(&func.front());
2639     func.setVisibility(mlir::SymbolTable::Visibility::Public);
2640 
2641     mapDummiesAndResults(funit, callee);
2642 
2643     // Note: not storing Variable references because getOrderedSymbolTable
2644     // below returns a temporary.
2645     llvm::SmallVector<Fortran::lower::pft::Variable> deferredFuncResultList;
2646 
2647     // Backup actual argument for entry character results
2648     // with different lengths. It needs to be added to the non
2649     // primary results symbol before mapSymbolAttributes is called.
2650     Fortran::lower::SymbolBox resultArg;
2651     if (std::optional<Fortran::lower::CalleeInterface::PassedEntity>
2652             passedResult = callee.getPassedResult())
2653       resultArg = lookupSymbol(passedResult->entity->get());
2654 
2655     Fortran::lower::AggregateStoreMap storeMap;
2656     // The front-end is currently not adding module variables referenced
2657     // in a module procedure as host associated. As a result we need to
2658     // instantiate all module variables here if this is a module procedure.
2659     // It is likely that the front-end behavior should change here.
2660     // This also applies to internal procedures inside module procedures.
2661     if (auto *module = Fortran::lower::pft::getAncestor<
2662             Fortran::lower::pft::ModuleLikeUnit>(funit))
2663       for (const Fortran::lower::pft::Variable &var :
2664            module->getOrderedSymbolTable())
2665         instantiateVar(var, storeMap);
2666 
2667     mlir::Value primaryFuncResultStorage;
2668     for (const Fortran::lower::pft::Variable &var :
2669          funit.getOrderedSymbolTable()) {
2670       // Always instantiate aggregate storage blocks.
2671       if (var.isAggregateStore()) {
2672         instantiateVar(var, storeMap);
2673         continue;
2674       }
2675       const Fortran::semantics::Symbol &sym = var.getSymbol();
2676       if (funit.parentHasHostAssoc()) {
2677         // Never instantitate host associated variables, as they are already
2678         // instantiated from an argument tuple. Instead, just bind the symbol to
2679         // the reference to the host variable, which must be in the map.
2680         const Fortran::semantics::Symbol &ultimate = sym.GetUltimate();
2681         if (funit.parentHostAssoc().isAssociated(ultimate)) {
2682           Fortran::lower::SymbolBox hostBox =
2683               localSymbols.lookupSymbol(ultimate);
2684           assert(hostBox && "host association is not in map");
2685           localSymbols.addSymbol(sym, hostBox.toExtendedValue());
2686           continue;
2687         }
2688       }
2689       if (!sym.IsFuncResult() || !funit.primaryResult) {
2690         instantiateVar(var, storeMap);
2691       } else if (&sym == funit.primaryResult) {
2692         instantiateVar(var, storeMap);
2693         primaryFuncResultStorage = getSymbolAddress(sym);
2694       } else {
2695         deferredFuncResultList.push_back(var);
2696       }
2697     }
2698 
2699     // TODO: should use same mechanism as equivalence?
2700     // One blocking point is character entry returns that need special handling
2701     // since they are not locally allocated but come as argument. CHARACTER(*)
2702     // is not something that fits well with equivalence lowering.
2703     for (const Fortran::lower::pft::Variable &altResult :
2704          deferredFuncResultList) {
2705       if (std::optional<Fortran::lower::CalleeInterface::PassedEntity>
2706               passedResult = callee.getPassedResult())
2707         addSymbol(altResult.getSymbol(), resultArg.getAddr());
2708       Fortran::lower::StatementContext stmtCtx;
2709       Fortran::lower::mapSymbolAttributes(*this, altResult, localSymbols,
2710                                           stmtCtx, primaryFuncResultStorage);
2711     }
2712 
2713     // If this is a host procedure with host associations, then create the tuple
2714     // of pointers for passing to the internal procedures.
2715     if (!funit.getHostAssoc().empty())
2716       funit.getHostAssoc().hostProcedureBindings(*this, localSymbols);
2717 
2718     // Create most function blocks in advance.
2719     createEmptyBlocks(funit.evaluationList);
2720 
2721     // Reinstate entry block as the current insertion point.
2722     builder->setInsertionPointToEnd(&func.front());
2723 
2724     if (callee.hasAlternateReturns()) {
2725       // Create a local temp to hold the alternate return index.
2726       // Give it an integer index type and the subroutine name (for dumps).
2727       // Attach it to the subroutine symbol in the localSymbols map.
2728       // Initialize it to zero, the "fallthrough" alternate return value.
2729       const Fortran::semantics::Symbol &symbol = funit.getSubprogramSymbol();
2730       mlir::Location loc = toLocation();
2731       mlir::Type idxTy = builder->getIndexType();
2732       mlir::Value altResult =
2733           builder->createTemporary(loc, idxTy, toStringRef(symbol.name()));
2734       addSymbol(symbol, altResult);
2735       mlir::Value zero = builder->createIntegerConstant(loc, idxTy, 0);
2736       builder->create<fir::StoreOp>(loc, zero, altResult);
2737     }
2738 
2739     if (Fortran::lower::pft::Evaluation *alternateEntryEval =
2740             funit.getEntryEval())
2741       genFIRBranch(alternateEntryEval->lexicalSuccessor->block);
2742   }
2743 
2744   /// Create global blocks for the current function.  This eliminates the
2745   /// distinction between forward and backward targets when generating
2746   /// branches.  A block is "global" if it can be the target of a GOTO or
2747   /// other source code branch.  A block that can only be targeted by a
2748   /// compiler generated branch is "local".  For example, a DO loop preheader
2749   /// block containing loop initialization code is global.  A loop header
2750   /// block, which is the target of the loop back edge, is local.  Blocks
2751   /// belong to a region.  Any block within a nested region must be replaced
2752   /// with a block belonging to that region.  Branches may not cross region
2753   /// boundaries.
2754   void createEmptyBlocks(
2755       std::list<Fortran::lower::pft::Evaluation> &evaluationList) {
2756     mlir::Region *region = &builder->getRegion();
2757     for (Fortran::lower::pft::Evaluation &eval : evaluationList) {
2758       if (eval.isNewBlock)
2759         eval.block = builder->createBlock(region);
2760       if (eval.isConstruct() || eval.isDirective()) {
2761         if (eval.lowerAsUnstructured()) {
2762           createEmptyBlocks(eval.getNestedEvaluations());
2763         } else if (eval.hasNestedEvaluations()) {
2764           // A structured construct that is a target starts a new block.
2765           Fortran::lower::pft::Evaluation &constructStmt =
2766               eval.getFirstNestedEvaluation();
2767           if (constructStmt.isNewBlock)
2768             constructStmt.block = builder->createBlock(region);
2769         }
2770       }
2771     }
2772   }
2773 
2774   /// Return the predicate: "current block does not have a terminator branch".
2775   bool blockIsUnterminated() {
2776     mlir::Block *currentBlock = builder->getBlock();
2777     return currentBlock->empty() ||
2778            !currentBlock->back().hasTrait<mlir::OpTrait::IsTerminator>();
2779   }
2780 
2781   /// Unconditionally switch code insertion to a new block.
2782   void startBlock(mlir::Block *newBlock) {
2783     assert(newBlock && "missing block");
2784     // Default termination for the current block is a fallthrough branch to
2785     // the new block.
2786     if (blockIsUnterminated())
2787       genFIRBranch(newBlock);
2788     // Some blocks may be re/started more than once, and might not be empty.
2789     // If the new block already has (only) a terminator, set the insertion
2790     // point to the start of the block.  Otherwise set it to the end.
2791     builder->setInsertionPointToStart(newBlock);
2792     if (blockIsUnterminated())
2793       builder->setInsertionPointToEnd(newBlock);
2794   }
2795 
2796   /// Conditionally switch code insertion to a new block.
2797   void maybeStartBlock(mlir::Block *newBlock) {
2798     if (newBlock)
2799       startBlock(newBlock);
2800   }
2801 
2802   /// Emit return and cleanup after the function has been translated.
2803   void endNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) {
2804     setCurrentPosition(Fortran::lower::pft::stmtSourceLoc(funit.endStmt));
2805     if (funit.isMainProgram())
2806       genExitRoutine();
2807     else
2808       genFIRProcedureExit(funit, funit.getSubprogramSymbol());
2809     funit.finalBlock = nullptr;
2810     LLVM_DEBUG(llvm::dbgs() << "*** Lowering result:\n\n"
2811                             << *builder->getFunction() << '\n');
2812     // FIXME: Simplification should happen in a normal pass, not here.
2813     mlir::IRRewriter rewriter(*builder);
2814     (void)mlir::simplifyRegions(rewriter,
2815                                 {builder->getRegion()}); // remove dead code
2816     delete builder;
2817     builder = nullptr;
2818     hostAssocTuple = mlir::Value{};
2819     localSymbols.clear();
2820   }
2821 
2822   /// Helper to generate GlobalOps when the builder is not positioned in any
2823   /// region block. This is required because the FirOpBuilder assumes it is
2824   /// always positioned inside a region block when creating globals, the easiest
2825   /// way comply is to create a dummy function and to throw it afterwards.
2826   void createGlobalOutsideOfFunctionLowering(
2827       const std::function<void()> &createGlobals) {
2828     // FIXME: get rid of the bogus function context and instantiate the
2829     // globals directly into the module.
2830     mlir::MLIRContext *context = &getMLIRContext();
2831     mlir::func::FuncOp func = fir::FirOpBuilder::createFunction(
2832         mlir::UnknownLoc::get(context), getModuleOp(),
2833         fir::NameUniquer::doGenerated("Sham"),
2834         mlir::FunctionType::get(context, llvm::None, llvm::None));
2835     func.addEntryBlock();
2836     builder = new fir::FirOpBuilder(func, bridge.getKindMap());
2837     createGlobals();
2838     if (mlir::Region *region = func.getCallableRegion())
2839       region->dropAllReferences();
2840     func.erase();
2841     delete builder;
2842     builder = nullptr;
2843     localSymbols.clear();
2844   }
2845   /// Instantiate the data from a BLOCK DATA unit.
2846   void lowerBlockData(Fortran::lower::pft::BlockDataUnit &bdunit) {
2847     createGlobalOutsideOfFunctionLowering([&]() {
2848       Fortran::lower::AggregateStoreMap fakeMap;
2849       for (const auto &[_, sym] : bdunit.symTab) {
2850         if (sym->has<Fortran::semantics::ObjectEntityDetails>()) {
2851           Fortran::lower::pft::Variable var(*sym, true);
2852           instantiateVar(var, fakeMap);
2853         }
2854       }
2855     });
2856   }
2857 
2858   /// Create fir::Global for all the common blocks that appear in the program.
2859   void
2860   lowerCommonBlocks(const Fortran::semantics::CommonBlockList &commonBlocks) {
2861     createGlobalOutsideOfFunctionLowering(
2862         [&]() { Fortran::lower::defineCommonBlocks(*this, commonBlocks); });
2863   }
2864 
2865   /// Lower a procedure (nest).
2866   void lowerFunc(Fortran::lower::pft::FunctionLikeUnit &funit) {
2867     if (!funit.isMainProgram()) {
2868       const Fortran::semantics::Symbol &procSymbol =
2869           funit.getSubprogramSymbol();
2870       if (procSymbol.owner().IsSubmodule())
2871         TODO(toLocation(), "support for submodules");
2872       if (Fortran::semantics::IsSeparateModuleProcedureInterface(&procSymbol))
2873         TODO(toLocation(), "separate module procedure");
2874     }
2875     setCurrentPosition(funit.getStartingSourceLoc());
2876     for (int entryIndex = 0, last = funit.entryPointList.size();
2877          entryIndex < last; ++entryIndex) {
2878       funit.setActiveEntry(entryIndex);
2879       startNewFunction(funit); // the entry point for lowering this procedure
2880       for (Fortran::lower::pft::Evaluation &eval : funit.evaluationList)
2881         genFIR(eval);
2882       endNewFunction(funit);
2883     }
2884     funit.setActiveEntry(0);
2885     for (Fortran::lower::pft::FunctionLikeUnit &f : funit.nestedFunctions)
2886       lowerFunc(f); // internal procedure
2887   }
2888 
2889   /// Lower module variable definitions to fir::globalOp and OpenMP/OpenACC
2890   /// declarative construct.
2891   void lowerModuleDeclScope(Fortran::lower::pft::ModuleLikeUnit &mod) {
2892     setCurrentPosition(mod.getStartingSourceLoc());
2893     createGlobalOutsideOfFunctionLowering([&]() {
2894       for (const Fortran::lower::pft::Variable &var :
2895            mod.getOrderedSymbolTable()) {
2896         // Only define the variables owned by this module.
2897         const Fortran::semantics::Scope *owningScope = var.getOwningScope();
2898         if (!owningScope || mod.getScope() == *owningScope)
2899           Fortran::lower::defineModuleVariable(*this, var);
2900       }
2901       for (auto &eval : mod.evaluationList)
2902         genFIR(eval);
2903     });
2904   }
2905 
2906   /// Lower functions contained in a module.
2907   void lowerMod(Fortran::lower::pft::ModuleLikeUnit &mod) {
2908     for (Fortran::lower::pft::FunctionLikeUnit &f : mod.nestedFunctions)
2909       lowerFunc(f);
2910   }
2911 
2912   void setCurrentPosition(const Fortran::parser::CharBlock &position) {
2913     if (position != Fortran::parser::CharBlock{})
2914       currentPosition = position;
2915   }
2916 
2917   /// Set current position at the location of \p parseTreeNode. Note that the
2918   /// position is updated automatically when visiting statements, but not when
2919   /// entering higher level nodes like constructs or procedures. This helper is
2920   /// intended to cover the latter cases.
2921   template <typename A>
2922   void setCurrentPositionAt(const A &parseTreeNode) {
2923     setCurrentPosition(Fortran::parser::FindSourceLocation(parseTreeNode));
2924   }
2925 
2926   //===--------------------------------------------------------------------===//
2927   // Utility methods
2928   //===--------------------------------------------------------------------===//
2929 
2930   /// Convert a parser CharBlock to a Location
2931   mlir::Location toLocation(const Fortran::parser::CharBlock &cb) {
2932     return genLocation(cb);
2933   }
2934 
2935   mlir::Location toLocation() { return toLocation(currentPosition); }
2936   void setCurrentEval(Fortran::lower::pft::Evaluation &eval) {
2937     evalPtr = &eval;
2938   }
2939   Fortran::lower::pft::Evaluation &getEval() {
2940     assert(evalPtr);
2941     return *evalPtr;
2942   }
2943 
2944   std::optional<Fortran::evaluate::Shape>
2945   getShape(const Fortran::lower::SomeExpr &expr) {
2946     return Fortran::evaluate::GetShape(foldingContext, expr);
2947   }
2948 
2949   //===--------------------------------------------------------------------===//
2950   // Analysis on a nested explicit iteration space.
2951   //===--------------------------------------------------------------------===//
2952 
2953   void analyzeExplicitSpace(const Fortran::parser::ConcurrentHeader &header) {
2954     explicitIterSpace.pushLevel();
2955     for (const Fortran::parser::ConcurrentControl &ctrl :
2956          std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) {
2957       const Fortran::semantics::Symbol *ctrlVar =
2958           std::get<Fortran::parser::Name>(ctrl.t).symbol;
2959       explicitIterSpace.addSymbol(ctrlVar);
2960     }
2961     if (const auto &mask =
2962             std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>(
2963                 header.t);
2964         mask.has_value())
2965       analyzeExplicitSpace(*Fortran::semantics::GetExpr(*mask));
2966   }
2967   template <bool LHS = false, typename A>
2968   void analyzeExplicitSpace(const Fortran::evaluate::Expr<A> &e) {
2969     explicitIterSpace.exprBase(&e, LHS);
2970   }
2971   void analyzeExplicitSpace(const Fortran::evaluate::Assignment *assign) {
2972     auto analyzeAssign = [&](const Fortran::lower::SomeExpr &lhs,
2973                              const Fortran::lower::SomeExpr &rhs) {
2974       analyzeExplicitSpace</*LHS=*/true>(lhs);
2975       analyzeExplicitSpace(rhs);
2976     };
2977     std::visit(
2978         Fortran::common::visitors{
2979             [&](const Fortran::evaluate::ProcedureRef &procRef) {
2980               // Ensure the procRef expressions are the one being visited.
2981               assert(procRef.arguments().size() == 2);
2982               const Fortran::lower::SomeExpr *lhs =
2983                   procRef.arguments()[0].value().UnwrapExpr();
2984               const Fortran::lower::SomeExpr *rhs =
2985                   procRef.arguments()[1].value().UnwrapExpr();
2986               assert(lhs && rhs &&
2987                      "user defined assignment arguments must be expressions");
2988               analyzeAssign(*lhs, *rhs);
2989             },
2990             [&](const auto &) { analyzeAssign(assign->lhs, assign->rhs); }},
2991         assign->u);
2992     explicitIterSpace.endAssign();
2993   }
2994   void analyzeExplicitSpace(const Fortran::parser::ForallAssignmentStmt &stmt) {
2995     std::visit([&](const auto &s) { analyzeExplicitSpace(s); }, stmt.u);
2996   }
2997   void analyzeExplicitSpace(const Fortran::parser::AssignmentStmt &s) {
2998     analyzeExplicitSpace(s.typedAssignment->v.operator->());
2999   }
3000   void analyzeExplicitSpace(const Fortran::parser::PointerAssignmentStmt &s) {
3001     analyzeExplicitSpace(s.typedAssignment->v.operator->());
3002   }
3003   void analyzeExplicitSpace(const Fortran::parser::WhereConstruct &c) {
3004     analyzeExplicitSpace(
3005         std::get<
3006             Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>(
3007             c.t)
3008             .statement);
3009     for (const Fortran::parser::WhereBodyConstruct &body :
3010          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t))
3011       analyzeExplicitSpace(body);
3012     for (const Fortran::parser::WhereConstruct::MaskedElsewhere &e :
3013          std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>(
3014              c.t))
3015       analyzeExplicitSpace(e);
3016     if (const auto &e =
3017             std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>(
3018                 c.t);
3019         e.has_value())
3020       analyzeExplicitSpace(e.operator->());
3021   }
3022   void analyzeExplicitSpace(const Fortran::parser::WhereConstructStmt &ws) {
3023     const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr(
3024         std::get<Fortran::parser::LogicalExpr>(ws.t));
3025     addMaskVariable(exp);
3026     analyzeExplicitSpace(*exp);
3027   }
3028   void analyzeExplicitSpace(
3029       const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) {
3030     analyzeExplicitSpace(
3031         std::get<
3032             Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>(
3033             ew.t)
3034             .statement);
3035     for (const Fortran::parser::WhereBodyConstruct &e :
3036          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t))
3037       analyzeExplicitSpace(e);
3038   }
3039   void analyzeExplicitSpace(const Fortran::parser::WhereBodyConstruct &body) {
3040     std::visit(Fortran::common::visitors{
3041                    [&](const Fortran::common::Indirection<
3042                        Fortran::parser::WhereConstruct> &wc) {
3043                      analyzeExplicitSpace(wc.value());
3044                    },
3045                    [&](const auto &s) { analyzeExplicitSpace(s.statement); }},
3046                body.u);
3047   }
3048   void analyzeExplicitSpace(const Fortran::parser::MaskedElsewhereStmt &stmt) {
3049     const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr(
3050         std::get<Fortran::parser::LogicalExpr>(stmt.t));
3051     addMaskVariable(exp);
3052     analyzeExplicitSpace(*exp);
3053   }
3054   void
3055   analyzeExplicitSpace(const Fortran::parser::WhereConstruct::Elsewhere *ew) {
3056     for (const Fortran::parser::WhereBodyConstruct &e :
3057          std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew->t))
3058       analyzeExplicitSpace(e);
3059   }
3060   void analyzeExplicitSpace(const Fortran::parser::WhereStmt &stmt) {
3061     const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr(
3062         std::get<Fortran::parser::LogicalExpr>(stmt.t));
3063     addMaskVariable(exp);
3064     analyzeExplicitSpace(*exp);
3065     const std::optional<Fortran::evaluate::Assignment> &assign =
3066         std::get<Fortran::parser::AssignmentStmt>(stmt.t).typedAssignment->v;
3067     assert(assign.has_value() && "WHERE has no statement");
3068     analyzeExplicitSpace(assign.operator->());
3069   }
3070   void analyzeExplicitSpace(const Fortran::parser::ForallStmt &forall) {
3071     analyzeExplicitSpace(
3072         std::get<
3073             Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
3074             forall.t)
3075             .value());
3076     analyzeExplicitSpace(std::get<Fortran::parser::UnlabeledStatement<
3077                              Fortran::parser::ForallAssignmentStmt>>(forall.t)
3078                              .statement);
3079     analyzeExplicitSpacePop();
3080   }
3081   void
3082   analyzeExplicitSpace(const Fortran::parser::ForallConstructStmt &forall) {
3083     analyzeExplicitSpace(
3084         std::get<
3085             Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
3086             forall.t)
3087             .value());
3088   }
3089   void analyzeExplicitSpace(const Fortran::parser::ForallConstruct &forall) {
3090     analyzeExplicitSpace(
3091         std::get<
3092             Fortran::parser::Statement<Fortran::parser::ForallConstructStmt>>(
3093             forall.t)
3094             .statement);
3095     for (const Fortran::parser::ForallBodyConstruct &s :
3096          std::get<std::list<Fortran::parser::ForallBodyConstruct>>(forall.t)) {
3097       std::visit(Fortran::common::visitors{
3098                      [&](const Fortran::common::Indirection<
3099                          Fortran::parser::ForallConstruct> &b) {
3100                        analyzeExplicitSpace(b.value());
3101                      },
3102                      [&](const Fortran::parser::WhereConstruct &w) {
3103                        analyzeExplicitSpace(w);
3104                      },
3105                      [&](const auto &b) { analyzeExplicitSpace(b.statement); }},
3106                  s.u);
3107     }
3108     analyzeExplicitSpacePop();
3109   }
3110 
3111   void analyzeExplicitSpacePop() { explicitIterSpace.popLevel(); }
3112 
3113   void addMaskVariable(Fortran::lower::FrontEndExpr exp) {
3114     // Note: use i8 to store bool values. This avoids round-down behavior found
3115     // with sequences of i1. That is, an array of i1 will be truncated in size
3116     // and be too small. For example, a buffer of type fir.array<7xi1> will have
3117     // 0 size.
3118     mlir::Type i64Ty = builder->getIntegerType(64);
3119     mlir::TupleType ty = fir::factory::getRaggedArrayHeaderType(*builder);
3120     mlir::Type buffTy = ty.getType(1);
3121     mlir::Type shTy = ty.getType(2);
3122     mlir::Location loc = toLocation();
3123     mlir::Value hdr = builder->createTemporary(loc, ty);
3124     // FIXME: Is there a way to create a `zeroinitializer` in LLVM-IR dialect?
3125     // For now, explicitly set lazy ragged header to all zeros.
3126     // auto nilTup = builder->createNullConstant(loc, ty);
3127     // builder->create<fir::StoreOp>(loc, nilTup, hdr);
3128     mlir::Type i32Ty = builder->getIntegerType(32);
3129     mlir::Value zero = builder->createIntegerConstant(loc, i32Ty, 0);
3130     mlir::Value zero64 = builder->createIntegerConstant(loc, i64Ty, 0);
3131     mlir::Value flags = builder->create<fir::CoordinateOp>(
3132         loc, builder->getRefType(i64Ty), hdr, zero);
3133     builder->create<fir::StoreOp>(loc, zero64, flags);
3134     mlir::Value one = builder->createIntegerConstant(loc, i32Ty, 1);
3135     mlir::Value nullPtr1 = builder->createNullConstant(loc, buffTy);
3136     mlir::Value var = builder->create<fir::CoordinateOp>(
3137         loc, builder->getRefType(buffTy), hdr, one);
3138     builder->create<fir::StoreOp>(loc, nullPtr1, var);
3139     mlir::Value two = builder->createIntegerConstant(loc, i32Ty, 2);
3140     mlir::Value nullPtr2 = builder->createNullConstant(loc, shTy);
3141     mlir::Value shape = builder->create<fir::CoordinateOp>(
3142         loc, builder->getRefType(shTy), hdr, two);
3143     builder->create<fir::StoreOp>(loc, nullPtr2, shape);
3144     implicitIterSpace.addMaskVariable(exp, var, shape, hdr);
3145     explicitIterSpace.outermostContext().attachCleanup(
3146         [builder = this->builder, hdr, loc]() {
3147           fir::runtime::genRaggedArrayDeallocate(loc, *builder, hdr);
3148         });
3149   }
3150 
3151   void createRuntimeTypeInfoGlobals() {}
3152 
3153   //===--------------------------------------------------------------------===//
3154 
3155   Fortran::lower::LoweringBridge &bridge;
3156   Fortran::evaluate::FoldingContext foldingContext;
3157   fir::FirOpBuilder *builder = nullptr;
3158   Fortran::lower::pft::Evaluation *evalPtr = nullptr;
3159   Fortran::lower::SymMap localSymbols;
3160   Fortran::parser::CharBlock currentPosition;
3161   RuntimeTypeInfoConverter runtimeTypeInfoConverter;
3162 
3163   /// WHERE statement/construct mask expression stack.
3164   Fortran::lower::ImplicitIterSpace implicitIterSpace;
3165 
3166   /// FORALL context
3167   Fortran::lower::ExplicitIterSpace explicitIterSpace;
3168 
3169   /// Tuple of host assoicated variables.
3170   mlir::Value hostAssocTuple;
3171 };
3172 
3173 } // namespace
3174 
3175 Fortran::evaluate::FoldingContext
3176 Fortran::lower::LoweringBridge::createFoldingContext() const {
3177   return {getDefaultKinds(), getIntrinsicTable()};
3178 }
3179 
3180 void Fortran::lower::LoweringBridge::lower(
3181     const Fortran::parser::Program &prg,
3182     const Fortran::semantics::SemanticsContext &semanticsContext) {
3183   std::unique_ptr<Fortran::lower::pft::Program> pft =
3184       Fortran::lower::createPFT(prg, semanticsContext);
3185   if (dumpBeforeFir)
3186     Fortran::lower::dumpPFT(llvm::errs(), *pft);
3187   FirConverter converter{*this};
3188   converter.run(*pft);
3189 }
3190 
3191 void Fortran::lower::LoweringBridge::parseSourceFile(llvm::SourceMgr &srcMgr) {
3192   mlir::OwningOpRef<mlir::ModuleOp> owningRef =
3193       mlir::parseSourceFile<mlir::ModuleOp>(srcMgr, &context);
3194   module.reset(new mlir::ModuleOp(owningRef.get().getOperation()));
3195   owningRef.release();
3196 }
3197 
3198 Fortran::lower::LoweringBridge::LoweringBridge(
3199     mlir::MLIRContext &context,
3200     const Fortran::common::IntrinsicTypeDefaultKinds &defaultKinds,
3201     const Fortran::evaluate::IntrinsicProcTable &intrinsics,
3202     const Fortran::parser::AllCookedSources &cooked, llvm::StringRef triple,
3203     fir::KindMapping &kindMap)
3204     : defaultKinds{defaultKinds}, intrinsics{intrinsics}, cooked{&cooked},
3205       context{context}, kindMap{kindMap} {
3206   // Register the diagnostic handler.
3207   context.getDiagEngine().registerHandler([](mlir::Diagnostic &diag) {
3208     llvm::raw_ostream &os = llvm::errs();
3209     switch (diag.getSeverity()) {
3210     case mlir::DiagnosticSeverity::Error:
3211       os << "error: ";
3212       break;
3213     case mlir::DiagnosticSeverity::Remark:
3214       os << "info: ";
3215       break;
3216     case mlir::DiagnosticSeverity::Warning:
3217       os << "warning: ";
3218       break;
3219     default:
3220       break;
3221     }
3222     if (!diag.getLocation().isa<mlir::UnknownLoc>())
3223       os << diag.getLocation() << ": ";
3224     os << diag << '\n';
3225     os.flush();
3226     return mlir::success();
3227   });
3228 
3229   // Create the module and attach the attributes.
3230   module = std::make_unique<mlir::ModuleOp>(
3231       mlir::ModuleOp::create(mlir::UnknownLoc::get(&context)));
3232   assert(module.get() && "module was not created");
3233   fir::setTargetTriple(*module.get(), triple);
3234   fir::setKindMapping(*module.get(), kindMap);
3235 }
3236