Debian Codegraph @

flang/lib/Lower/Bridge.cpp

raw
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/ConvertCall.h"
18 #include "flang/Lower/ConvertExpr.h"
19 #include "flang/Lower/ConvertExprToHLFIR.h"
20 #include "flang/Lower/ConvertType.h"
21 #include "flang/Lower/ConvertVariable.h"
22 #include "flang/Lower/HostAssociations.h"
23 #include "flang/Lower/IO.h"
24 #include "flang/Lower/IterationSpace.h"
25 #include "flang/Lower/Mangler.h"
26 #include "flang/Lower/OpenACC.h"
27 #include "flang/Lower/OpenMP.h"
28 #include "flang/Lower/PFTBuilder.h"
29 #include "flang/Lower/Runtime.h"
30 #include "flang/Lower/StatementContext.h"
31 #include "flang/Lower/Support/Utils.h"
32 #include "flang/Optimizer/Builder/BoxValue.h"
33 #include "flang/Optimizer/Builder/Character.h"
34 #include "flang/Optimizer/Builder/FIRBuilder.h"
35 #include "flang/Optimizer/Builder/Runtime/Assign.h"
36 #include "flang/Optimizer/Builder/Runtime/Character.h"
37 #include "flang/Optimizer/Builder/Runtime/Derived.h"
38 #include "flang/Optimizer/Builder/Runtime/EnvironmentDefaults.h"
39 #include "flang/Optimizer/Builder/Runtime/Main.h"
40 #include "flang/Optimizer/Builder/Runtime/Ragged.h"
41 #include "flang/Optimizer/Builder/Runtime/Stop.h"
42 #include "flang/Optimizer/Builder/Todo.h"
43 #include "flang/Optimizer/Dialect/CUF/Attributes/CUFAttr.h"
44 #include "flang/Optimizer/Dialect/CUF/CUFOps.h"
45 #include "flang/Optimizer/Dialect/FIRAttr.h"
46 #include "flang/Optimizer/Dialect/FIRDialect.h"
47 #include "flang/Optimizer/Dialect/FIROps.h"
48 #include "flang/Optimizer/Dialect/Support/FIRContext.h"
49 #include "flang/Optimizer/HLFIR/HLFIROps.h"
50 #include "flang/Optimizer/Support/DataLayout.h"
51 #include "flang/Optimizer/Support/FatalError.h"
52 #include "flang/Optimizer/Support/InternalNames.h"
53 #include "flang/Optimizer/Transforms/Passes.h"
54 #include "flang/Parser/parse-tree.h"
55 #include "flang/Runtime/iostat.h"
56 #include "flang/Semantics/runtime-type-info.h"
57 #include "flang/Semantics/symbol.h"
58 #include "flang/Semantics/tools.h"
59 #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
60 #include "mlir/IR/Matchers.h"
61 #include "mlir/IR/PatternMatch.h"
62 #include "mlir/Parser/Parser.h"
63 #include "mlir/Transforms/RegionUtils.h"
64 #include "llvm/ADT/SmallVector.h"
65 #include "llvm/ADT/StringSet.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/FileSystem.h"
70 #include "llvm/Support/Path.h"
71 #include "llvm/Target/TargetMachine.h"
72 #include <optional>
73
74 #define DEBUG_TYPE "flang-lower-bridge"
75
76 static llvm::cl::opt<bool> dumpBeforeFir(
77 "fdebug-dump-pre-fir", llvm::cl::init(false),
78 llvm::cl::desc("dump the Pre-FIR tree prior to FIR generation"));
79
80 static llvm::cl::opt<bool> forceLoopToExecuteOnce(
81 "always-execute-loop-body", llvm::cl::init(false),
82 llvm::cl::desc("force the body of a loop to execute at least once"));
83
84 namespace {
85 /// Information for generating a structured or unstructured increment loop.
86 struct IncrementLoopInfo {
87 template <typename T>
88 explicit IncrementLoopInfo(Fortran::semantics::Symbol &sym, const T &lower,
89 const T &upper, const std::optional<T> &step,
90 bool isUnordered = false)
91 : loopVariableSym{&sym}, lowerExpr{Fortran::semantics::GetExpr(lower)},
92 upperExpr{Fortran::semantics::GetExpr(upper)},
93 stepExpr{Fortran::semantics::GetExpr(step)}, isUnordered{isUnordered} {}
94
95 IncrementLoopInfo(IncrementLoopInfo &&) = default;
96 IncrementLoopInfo &operator=(IncrementLoopInfo &&x) = default;
97
98 bool isStructured() const { return !headerBlock; }
99
100 mlir::Type getLoopVariableType() const {
101 assert(loopVariable && "must be set");
102 return fir::unwrapRefType(loopVariable.getType());
103 }
104
105 bool hasLocalitySpecs() const {
106 return !localSymList.empty() || !localInitSymList.empty() ||
107 !reduceSymList.empty() || !sharedSymList.empty();
108 }
109
110 // Data members common to both structured and unstructured loops.
111 const Fortran::semantics::Symbol *loopVariableSym;
112 const Fortran::lower::SomeExpr *lowerExpr;
113 const Fortran::lower::SomeExpr *upperExpr;
114 const Fortran::lower::SomeExpr *stepExpr;
115 const Fortran::lower::SomeExpr *maskExpr = nullptr;
116 bool isUnordered; // do concurrent, forall
117 llvm::SmallVector<const Fortran::semantics::Symbol *> localSymList;
118 llvm::SmallVector<const Fortran::semantics::Symbol *> localInitSymList;
119 llvm::SmallVector<
120 std::pair<fir::ReduceOperationEnum, const Fortran::semantics::Symbol *>>
121 reduceSymList;
122 llvm::SmallVector<const Fortran::semantics::Symbol *> sharedSymList;
123 mlir::Value loopVariable = nullptr;
124
125 // Data members for structured loops.
126 fir::DoLoopOp doLoop = nullptr;
127
128 // Data members for unstructured loops.
129 bool hasRealControl = false;
130 mlir::Value tripVariable = nullptr;
131 mlir::Value stepVariable = nullptr;
132 mlir::Block *headerBlock = nullptr; // loop entry and test block
133 mlir::Block *maskBlock = nullptr; // concurrent loop mask block
134 mlir::Block *bodyBlock = nullptr; // first loop body block
135 mlir::Block *exitBlock = nullptr; // loop exit target block
136 };
137
138 /// Information to support stack management, object deallocation, and
139 /// object finalization at early and normal construct exits.
140 struct ConstructContext {
141 explicit ConstructContext(Fortran::lower::pft::Evaluation &eval,
142 Fortran::lower::StatementContext &stmtCtx)
143 : eval{eval}, stmtCtx{stmtCtx} {}
144
145 Fortran::lower::pft::Evaluation &eval; // construct eval
146 Fortran::lower::StatementContext &stmtCtx; // construct exit code
147 std::optional<hlfir::Entity> selector; // construct selector, if any.
148 bool pushedScope = false; // was a scoped pushed for this construct?
149 };
150
151 /// Helper to gather the lower bounds of array components with non deferred
152 /// shape when they are not all ones. Return an empty array attribute otherwise.
153 static mlir::DenseI64ArrayAttr
154 gatherComponentNonDefaultLowerBounds(mlir::Location loc,
155 mlir::MLIRContext *mlirContext,
156 const Fortran::semantics::Symbol &sym) {
157 if (Fortran::semantics::IsAllocatableOrObjectPointer(&sym))
158 return {};
159 mlir::DenseI64ArrayAttr lbs_attr;
160 if (const auto *objDetails =
161 sym.detailsIf<Fortran::semantics::ObjectEntityDetails>()) {
162 llvm::SmallVector<std::int64_t> lbs;
163 bool hasNonDefaultLbs = false;
164 for (const Fortran::semantics::ShapeSpec &bounds : objDetails->shape())
165 if (auto lb = bounds.lbound().GetExplicit()) {
166 if (auto constant = Fortran::evaluate::ToInt64(*lb)) {
167 hasNonDefaultLbs |= (*constant != 1);
168 lbs.push_back(*constant);
169 } else {
170 TODO(loc, "generate fir.dt_component for length parametrized derived "
171 "types");
172 }
173 }
174 if (hasNonDefaultLbs) {
175 assert(static_cast<int>(lbs.size()) == sym.Rank() &&
176 "expected component bounds to be constant or deferred");
177 lbs_attr = mlir::DenseI64ArrayAttr::get(mlirContext, lbs);
178 }
179 }
180 return lbs_attr;
181 }
182
183 // Helper class to generate name of fir.global containing component explicit
184 // default value for objects, and initial procedure target for procedure pointer
185 // components.
186 static mlir::FlatSymbolRefAttr gatherComponentInit(
187 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
188 const Fortran::semantics::Symbol &sym, fir::RecordType derivedType) {
189 mlir::MLIRContext *mlirContext = &converter.getMLIRContext();
190 // Return procedure target mangled name for procedure pointer components.
191 if (const auto *procPtr =
192 sym.detailsIf<Fortran::semantics::ProcEntityDetails>()) {
193 if (std::optional<const Fortran::semantics::Symbol *> maybeInitSym =
194 procPtr->init()) {
195 // So far, do not make distinction between p => NULL() and p without init,
196 // f18 always initialize pointers to NULL anyway.
197 if (!*maybeInitSym)
198 return {};
199 return mlir::FlatSymbolRefAttr::get(mlirContext,
200 converter.mangleName(**maybeInitSym));
201 }
202 }
203
204 const auto *objDetails =
205 sym.detailsIf<Fortran::semantics::ObjectEntityDetails>();
206 if (!objDetails || !objDetails->init().has_value())
207 return {};
208 // Object component initial value. Semantic package component object default
209 // value into compiler generated symbols that are lowered as read-only
210 // fir.global. Get the name of this global.
211 std::string name = fir::NameUniquer::getComponentInitName(
212 derivedType.getName(), toStringRef(sym.name()));
213 return mlir::FlatSymbolRefAttr::get(mlirContext, name);
214 }
215
216 /// Helper class to generate the runtime type info global data and the
217 /// fir.type_info operations that contain the dipatch tables (if any).
218 /// The type info global data is required to describe the derived type to the
219 /// runtime so that it can operate over it.
220 /// It must be ensured these operations will be generated for every derived type
221 /// lowered in the current translated unit. However, these operations
222 /// cannot be generated before FuncOp have been created for functions since the
223 /// initializers may take their address (e.g for type bound procedures). This
224 /// class allows registering all the required type info while it is not
225 /// possible to create GlobalOp/TypeInfoOp, and to generate this data afte
226 /// function lowering.
227 class TypeInfoConverter {
228 /// Store the location and symbols of derived type info to be generated.
229 /// The location of the derived type instantiation is also stored because
230 /// runtime type descriptor symbols are compiler generated and cannot be
231 /// mapped to user code on their own.
232 struct TypeInfo {
233 Fortran::semantics::SymbolRef symbol;
234 const Fortran::semantics::DerivedTypeSpec &typeSpec;
235 fir::RecordType type;
236 mlir::Location loc;
237 };
238
239 public:
240 void registerTypeInfo(Fortran::lower::AbstractConverter &converter,
241 mlir::Location loc,
242 Fortran::semantics::SymbolRef typeInfoSym,
243 const Fortran::semantics::DerivedTypeSpec &typeSpec,
244 fir::RecordType type) {
245 if (seen.contains(typeInfoSym))
246 return;
247 seen.insert(typeInfoSym);
248 currentTypeInfoStack->emplace_back(
249 TypeInfo{typeInfoSym, typeSpec, type, loc});
250 return;
251 }
252
253 void createTypeInfo(Fortran::lower::AbstractConverter &converter) {
254 while (!registeredTypeInfoA.empty()) {
255 currentTypeInfoStack = &registeredTypeInfoB;
256 for (const TypeInfo &info : registeredTypeInfoA)
257 createTypeInfoOpAndGlobal(converter, info);
258 registeredTypeInfoA.clear();
259 currentTypeInfoStack = &registeredTypeInfoA;
260 for (const TypeInfo &info : registeredTypeInfoB)
261 createTypeInfoOpAndGlobal(converter, info);
262 registeredTypeInfoB.clear();
263 }
264 }
265
266 private:
267 void createTypeInfoOpAndGlobal(Fortran::lower::AbstractConverter &converter,
268 const TypeInfo &info) {
269 Fortran::lower::createRuntimeTypeInfoGlobal(converter, info.symbol.get());
270 createTypeInfoOp(converter, info);
271 }
272
273 void createTypeInfoOp(Fortran::lower::AbstractConverter &converter,
274 const TypeInfo &info) {
275 fir::RecordType parentType{};
276 if (const Fortran::semantics::DerivedTypeSpec *parent =
277 Fortran::evaluate::GetParentTypeSpec(info.typeSpec))
278 parentType = mlir::cast<fir::RecordType>(converter.genType(*parent));
279
280 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
281 fir::TypeInfoOp dt;
282 mlir::OpBuilder::InsertPoint insertPointIfCreated;
283 std::tie(dt, insertPointIfCreated) =
284 builder.createTypeInfoOp(info.loc, info.type, parentType);
285 if (!insertPointIfCreated.isSet())
286 return; // fir.type_info was already built in a previous call.
287
288 // Set init, destroy, and nofinal attributes.
289 if (!info.typeSpec.HasDefaultInitialization(/*ignoreAllocatable=*/false,
290 /*ignorePointer=*/false))
291 dt->setAttr(dt.getNoInitAttrName(), builder.getUnitAttr());
292 if (!info.typeSpec.HasDestruction())
293 dt->setAttr(dt.getNoDestroyAttrName(), builder.getUnitAttr());
294 if (!Fortran::semantics::MayRequireFinalization(info.typeSpec))
295 dt->setAttr(dt.getNoFinalAttrName(), builder.getUnitAttr());
296
297 const Fortran::semantics::Scope &derivedScope =
298 DEREF(info.typeSpec.GetScope());
299
300 // Fill binding table region if the derived type has bindings.
301 Fortran::semantics::SymbolVector bindings =
302 Fortran::semantics::CollectBindings(derivedScope);
303 if (!bindings.empty()) {
304 builder.createBlock(&dt.getDispatchTable());
305 for (const Fortran::semantics::SymbolRef &binding : bindings) {
306 const auto &details =
307 binding.get().get<Fortran::semantics::ProcBindingDetails>();
308 std::string tbpName = binding.get().name().ToString();
309 if (details.numPrivatesNotOverridden() > 0)
310 tbpName += "."s + std::to_string(details.numPrivatesNotOverridden());
311 std::string bindingName = converter.mangleName(details.symbol());
312 builder.create<fir::DTEntryOp>(
313 info.loc, mlir::StringAttr::get(builder.getContext(), tbpName),
314 mlir::SymbolRefAttr::get(builder.getContext(), bindingName));
315 }
316 builder.create<fir::FirEndOp>(info.loc);
317 }
318 // Gather info about components that is not reflected in fir.type and may be
319 // needed later: component initial values and array component non default
320 // lower bounds.
321 mlir::Block *componentInfo = nullptr;
322 for (const auto &componentName :
323 info.typeSpec.typeSymbol()
324 .get<Fortran::semantics::DerivedTypeDetails>()
325 .componentNames()) {
326 auto scopeIter = derivedScope.find(componentName);
327 assert(scopeIter != derivedScope.cend() &&
328 "failed to find derived type component symbol");
329 const Fortran::semantics::Symbol &component = scopeIter->second.get();
330 mlir::FlatSymbolRefAttr init_val =
331 gatherComponentInit(info.loc, converter, component, info.type);
332 mlir::DenseI64ArrayAttr lbs = gatherComponentNonDefaultLowerBounds(
333 info.loc, builder.getContext(), component);
334 if (init_val || lbs) {
335 if (!componentInfo)
336 componentInfo = builder.createBlock(&dt.getComponentInfo());
337 auto compName = mlir::StringAttr::get(builder.getContext(),
338 toStringRef(component.name()));
339 builder.create<fir::DTComponentOp>(info.loc, compName, lbs, init_val);
340 }
341 }
342 if (componentInfo)
343 builder.create<fir::FirEndOp>(info.loc);
344 builder.restoreInsertionPoint(insertPointIfCreated);
345 }
346
347 /// Store the front-end data that will be required to generate the type info
348 /// for the derived types that have been converted to fir.type<>. There are
349 /// two stacks since the type info may visit new types, so the new types must
350 /// be added to a new stack.
351 llvm::SmallVector<TypeInfo> registeredTypeInfoA;
352 llvm::SmallVector<TypeInfo> registeredTypeInfoB;
353 llvm::SmallVector<TypeInfo> *currentTypeInfoStack = &registeredTypeInfoA;
354 /// Track symbols symbols processed during and after the registration
355 /// to avoid infinite loops between type conversions and global variable
356 /// creation.
357 llvm::SmallSetVector<Fortran::semantics::SymbolRef, 32> seen;
358 };
359
360 using IncrementLoopNestInfo = llvm::SmallVector<IncrementLoopInfo, 8>;
361 } // namespace
362
363 //===----------------------------------------------------------------------===//
364 // FirConverter
365 //===----------------------------------------------------------------------===//
366
367 namespace {
368
369 /// Traverse the pre-FIR tree (PFT) to generate the FIR dialect of MLIR.
370 class FirConverter : public Fortran::lower::AbstractConverter {
371 public:
372 explicit FirConverter(Fortran::lower::LoweringBridge &bridge)
373 : Fortran::lower::AbstractConverter(bridge.getLoweringOptions()),
374 bridge{bridge}, foldingContext{bridge.createFoldingContext()},
375 mlirSymbolTable{bridge.getModule()} {}
376 virtual ~FirConverter() = default;
377
378 /// Convert the PFT to FIR.
379 void run(Fortran::lower::pft::Program &pft) {
380 // Preliminary translation pass.
381
382 // Lower common blocks, taking into account initialization and the largest
383 // size of all instances of each common block. This is done before lowering
384 // since the global definition may differ from any one local definition.
385 lowerCommonBlocks(pft.getCommonBlocks());
386
387 // - Declare all functions that have definitions so that definition
388 // signatures prevail over call site signatures.
389 // - Define module variables and OpenMP/OpenACC declarative constructs so
390 // they are available before lowering any function that may use them.
391 bool hasMainProgram = false;
392 const Fortran::semantics::Symbol *globalOmpRequiresSymbol = nullptr;
393 for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) {
394 Fortran::common::visit(
395 Fortran::common::visitors{
396 [&](Fortran::lower::pft::FunctionLikeUnit &f) {
397 if (f.isMainProgram())
398 hasMainProgram = true;
399 declareFunction(f);
400 if (!globalOmpRequiresSymbol)
401 globalOmpRequiresSymbol = f.getScope().symbol();
402 },
403 [&](Fortran::lower::pft::ModuleLikeUnit &m) {
404 lowerModuleDeclScope(m);
405 for (Fortran::lower::pft::ContainedUnit &unit :
406 m.containedUnitList)
407 if (auto *f =
408 std::get_if<Fortran::lower::pft::FunctionLikeUnit>(
409 &unit))
410 declareFunction(*f);
411 },
412 [&](Fortran::lower::pft::BlockDataUnit &b) {
413 if (!globalOmpRequiresSymbol)
414 globalOmpRequiresSymbol = b.symTab.symbol();
415 },
416 [&](Fortran::lower::pft::CompilerDirectiveUnit &d) {},
417 [&](Fortran::lower::pft::OpenACCDirectiveUnit &d) {},
418 },
419 u);
420 }
421
422 // Create definitions of intrinsic module constants.
423 createGlobalOutsideOfFunctionLowering(
424 [&]() { createIntrinsicModuleDefinitions(pft); });
425
426 // Primary translation pass.
427 for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) {
428 Fortran::common::visit(
429 Fortran::common::visitors{
430 [&](Fortran::lower::pft::FunctionLikeUnit &f) { lowerFunc(f); },
431 [&](Fortran::lower::pft::ModuleLikeUnit &m) { lowerMod(m); },
432 [&](Fortran::lower::pft::BlockDataUnit &b) {},
433 [&](Fortran::lower::pft::CompilerDirectiveUnit &d) {},
434 [&](Fortran::lower::pft::OpenACCDirectiveUnit &d) {
435 builder = new fir::FirOpBuilder(
436 bridge.getModule(), bridge.getKindMap(), &mlirSymbolTable);
437 Fortran::lower::genOpenACCRoutineConstruct(
438 *this, bridge.getSemanticsContext(), bridge.getModule(),
439 d.routine, accRoutineInfos);
440 builder = nullptr;
441 },
442 },
443 u);
444 }
445
446 // Once all the code has been translated, create global runtime type info
447 // data structures for the derived types that have been processed, as well
448 // as fir.type_info operations for the dispatch tables.
449 createGlobalOutsideOfFunctionLowering(
450 [&]() { typeInfoConverter.createTypeInfo(*this); });
451
452 // Generate the `main` entry point if necessary
453 if (hasMainProgram)
454 createGlobalOutsideOfFunctionLowering([&]() {
455 fir::runtime::genMain(*builder, toLocation(),
456 bridge.getEnvironmentDefaults());
457 });
458
459 finalizeOpenACCLowering();
460 finalizeOpenMPLowering(globalOmpRequiresSymbol);
461 }
462
463 /// Declare a function.
464 void declareFunction(Fortran::lower::pft::FunctionLikeUnit &funit) {
465 setCurrentPosition(funit.getStartingSourceLoc());
466 for (int entryIndex = 0, last = funit.entryPointList.size();
467 entryIndex < last; ++entryIndex) {
468 funit.setActiveEntry(entryIndex);
469 // Calling CalleeInterface ctor will build a declaration
470 // mlir::func::FuncOp with no other side effects.
471 // TODO: when doing some compiler profiling on real apps, it may be worth
472 // to check it's better to save the CalleeInterface instead of recomputing
473 // it later when lowering the body. CalleeInterface ctor should be linear
474 // with the number of arguments, so it is not awful to do it that way for
475 // now, but the linear coefficient might be non negligible. Until
476 // measured, stick to the solution that impacts the code less.
477 Fortran::lower::CalleeInterface{funit, *this};
478 }
479 funit.setActiveEntry(0);
480
481 // Compute the set of host associated entities from the nested functions.
482 llvm::SetVector<const Fortran::semantics::Symbol *> escapeHost;
483 for (Fortran::lower::pft::ContainedUnit &unit : funit.containedUnitList)
484 if (auto *f = std::get_if<Fortran::lower::pft::FunctionLikeUnit>(&unit))
485 collectHostAssociatedVariables(*f, escapeHost);
486 funit.setHostAssociatedSymbols(escapeHost);
487
488 // Declare internal procedures
489 for (Fortran::lower::pft::ContainedUnit &unit : funit.containedUnitList)
490 if (auto *f = std::get_if<Fortran::lower::pft::FunctionLikeUnit>(&unit))
491 declareFunction(*f);
492 }
493
494 /// Get the scope that is defining or using \p sym. The returned scope is not
495 /// the ultimate scope, since this helper does not traverse use association.
496 /// This allows capturing module variables that are referenced in an internal
497 /// procedure but whose use statement is inside the host program.
498 const Fortran::semantics::Scope &
499 getSymbolHostScope(const Fortran::semantics::Symbol &sym) {
500 const Fortran::semantics::Symbol *hostSymbol = &sym;
501 while (const auto *details =
502 hostSymbol->detailsIf<Fortran::semantics::HostAssocDetails>())
503 hostSymbol = &details->symbol();
504 return hostSymbol->owner();
505 }
506
507 /// Collects the canonical list of all host associated symbols. These bindings
508 /// must be aggregated into a tuple which can then be added to each of the
509 /// internal procedure declarations and passed at each call site.
510 void collectHostAssociatedVariables(
511 Fortran::lower::pft::FunctionLikeUnit &funit,
512 llvm::SetVector<const Fortran::semantics::Symbol *> &escapees) {
513 const Fortran::semantics::Scope *internalScope =
514 funit.getSubprogramSymbol().scope();
515 assert(internalScope && "internal procedures symbol must create a scope");
516 auto addToListIfEscapee = [&](const Fortran::semantics::Symbol &sym) {
517 const Fortran::semantics::Symbol &ultimate = sym.GetUltimate();
518 const auto *namelistDetails =
519 ultimate.detailsIf<Fortran::semantics::NamelistDetails>();
520 if (ultimate.has<Fortran::semantics::ObjectEntityDetails>() ||
521 Fortran::semantics::IsProcedurePointer(ultimate) ||
522 Fortran::semantics::IsDummy(sym) || namelistDetails) {
523 const Fortran::semantics::Scope &symbolScope = getSymbolHostScope(sym);
524 if (symbolScope.kind() ==
525 Fortran::semantics::Scope::Kind::MainProgram ||
526 symbolScope.kind() == Fortran::semantics::Scope::Kind::Subprogram)
527 if (symbolScope != *internalScope &&
528 symbolScope.Contains(*internalScope)) {
529 if (namelistDetails) {
530 // So far, namelist symbols are processed on the fly in IO and
531 // the related namelist data structure is not added to the symbol
532 // map, so it cannot be passed to the internal procedures.
533 // Instead, all the symbols of the host namelist used in the
534 // internal procedure must be considered as host associated so
535 // that IO lowering can find them when needed.
536 for (const auto &namelistObject : namelistDetails->objects())
537 escapees.insert(&*namelistObject);
538 } else {
539 escapees.insert(&ultimate);
540 }
541 }
542 }
543 };
544 Fortran::lower::pft::visitAllSymbols(funit, addToListIfEscapee);
545 }
546
547 //===--------------------------------------------------------------------===//
548 // AbstractConverter overrides
549 //===--------------------------------------------------------------------===//
550
551 mlir::Value getSymbolAddress(Fortran::lower::SymbolRef sym) override final {
552 return lookupSymbol(sym).getAddr();
553 }
554
555 fir::ExtendedValue
556 symBoxToExtendedValue(const Fortran::lower::SymbolBox &symBox) {
557 return symBox.match(
558 [](const Fortran::lower::SymbolBox::Intrinsic &box)
559 -> fir::ExtendedValue { return box.getAddr(); },
560 [](const Fortran::lower::SymbolBox::None &) -> fir::ExtendedValue {
561 llvm::report_fatal_error("symbol not mapped");
562 },
563 [&](const fir::FortranVariableOpInterface &x) -> fir::ExtendedValue {
564 return hlfir::translateToExtendedValue(getCurrentLocation(),
565 getFirOpBuilder(), x);
566 },
567 [](const auto &box) -> fir::ExtendedValue { return box; });
568 }
569
570 fir::ExtendedValue
571 getSymbolExtendedValue(const Fortran::semantics::Symbol &sym,
572 Fortran::lower::SymMap *symMap) override final {
573 Fortran::lower::SymbolBox sb = lookupSymbol(sym, symMap);
574 if (!sb) {
575 LLVM_DEBUG(llvm::dbgs() << "unknown symbol: " << sym << "\nmap: "
576 << (symMap ? *symMap : localSymbols) << '\n');
577 fir::emitFatalError(getCurrentLocation(),
578 "symbol is not mapped to any IR value");
579 }
580 return symBoxToExtendedValue(sb);
581 }
582
583 mlir::Value impliedDoBinding(llvm::StringRef name) override final {
584 mlir::Value val = localSymbols.lookupImpliedDo(name);
585 if (!val)
586 fir::emitFatalError(toLocation(), "ac-do-variable has no binding");
587 return val;
588 }
589
590 void copySymbolBinding(Fortran::lower::SymbolRef src,
591 Fortran::lower::SymbolRef target) override final {
592 localSymbols.copySymbolBinding(src, target);
593 }
594
595 /// Add the symbol binding to the inner-most level of the symbol map and
596 /// return true if it is not already present. Otherwise, return false.
597 bool bindIfNewSymbol(Fortran::lower::SymbolRef sym,
598 const fir::ExtendedValue &exval) {
599 if (shallowLookupSymbol(sym))
600 return false;
601 bindSymbol(sym, exval);
602 return true;
603 }
604
605 void bindSymbol(Fortran::lower::SymbolRef sym,
606 const fir::ExtendedValue &exval) override final {
607 addSymbol(sym, exval, /*forced=*/true);
608 }
609
610 void
611 overrideExprValues(const Fortran::lower::ExprToValueMap *map) override final {
612 exprValueOverrides = map;
613 }
614
615 const Fortran::lower::ExprToValueMap *getExprOverrides() override final {
616 return exprValueOverrides;
617 }
618
619 bool lookupLabelSet(Fortran::lower::SymbolRef sym,
620 Fortran::lower::pft::LabelSet &labelSet) override final {
621 Fortran::lower::pft::FunctionLikeUnit &owningProc =
622 *getEval().getOwningProcedure();
623 auto iter = owningProc.assignSymbolLabelMap.find(sym);
624 if (iter == owningProc.assignSymbolLabelMap.end())
625 return false;
626 labelSet = iter->second;
627 return true;
628 }
629
630 Fortran::lower::pft::Evaluation *
631 lookupLabel(Fortran::lower::pft::Label label) override final {
632 Fortran::lower::pft::FunctionLikeUnit &owningProc =
633 *getEval().getOwningProcedure();
634 return owningProc.labelEvaluationMap.lookup(label);
635 }
636
637 fir::ExtendedValue
638 genExprAddr(const Fortran::lower::SomeExpr &expr,
639 Fortran::lower::StatementContext &context,
640 mlir::Location *locPtr = nullptr) override final {
641 mlir::Location loc = locPtr ? *locPtr : toLocation();
642 if (lowerToHighLevelFIR())
643 return Fortran::lower::convertExprToAddress(loc, *this, expr,
644 localSymbols, context);
645 return Fortran::lower::createSomeExtendedAddress(loc, *this, expr,
646 localSymbols, context);
647 }
648
649 fir::ExtendedValue
650 genExprValue(const Fortran::lower::SomeExpr &expr,
651 Fortran::lower::StatementContext &context,
652 mlir::Location *locPtr = nullptr) override final {
653 mlir::Location loc = locPtr ? *locPtr : toLocation();
654 if (lowerToHighLevelFIR())
655 return Fortran::lower::convertExprToValue(loc, *this, expr, localSymbols,
656 context);
657 return Fortran::lower::createSomeExtendedExpression(loc, *this, expr,
658 localSymbols, context);
659 }
660
661 fir::ExtendedValue
662 genExprBox(mlir::Location loc, const Fortran::lower::SomeExpr &expr,
663 Fortran::lower::StatementContext &stmtCtx) override final {
664 if (lowerToHighLevelFIR())
665 return Fortran::lower::convertExprToBox(loc, *this, expr, localSymbols,
666 stmtCtx);
667 return Fortran::lower::createBoxValue(loc, *this, expr, localSymbols,
668 stmtCtx);
669 }
670
671 Fortran::evaluate::FoldingContext &getFoldingContext() override final {
672 return foldingContext;
673 }
674
675 mlir::Type genType(const Fortran::lower::SomeExpr &expr) override final {
676 return Fortran::lower::translateSomeExprToFIRType(*this, expr);
677 }
678 mlir::Type genType(const Fortran::lower::pft::Variable &var) override final {
679 return Fortran::lower::translateVariableToFIRType(*this, var);
680 }
681 mlir::Type genType(Fortran::lower::SymbolRef sym) override final {
682 return Fortran::lower::translateSymbolToFIRType(*this, sym);
683 }
684 mlir::Type
685 genType(Fortran::common::TypeCategory tc, int kind,
686 llvm::ArrayRef<std::int64_t> lenParameters) override final {
687 return Fortran::lower::getFIRType(&getMLIRContext(), tc, kind,
688 lenParameters);
689 }
690 mlir::Type
691 genType(const Fortran::semantics::DerivedTypeSpec &tySpec) override final {
692 return Fortran::lower::translateDerivedTypeToFIRType(*this, tySpec);
693 }
694 mlir::Type genType(Fortran::common::TypeCategory tc) override final {
695 return Fortran::lower::getFIRType(
696 &getMLIRContext(), tc, bridge.getDefaultKinds().GetDefaultKind(tc),
697 std::nullopt);
698 }
699
700 Fortran::lower::TypeConstructionStack &
701 getTypeConstructionStack() override final {
702 return typeConstructionStack;
703 }
704
705 bool
706 isPresentShallowLookup(const Fortran::semantics::Symbol &sym) override final {
707 return bool(shallowLookupSymbol(sym));
708 }
709
710 bool createHostAssociateVarClone(
711 const Fortran::semantics::Symbol &sym) override final {
712 mlir::Location loc = genLocation(sym.name());
713 mlir::Type symType = genType(sym);
714 const auto *details = sym.detailsIf<Fortran::semantics::HostAssocDetails>();
715 assert(details && "No host-association found");
716 const Fortran::semantics::Symbol &hsym = details->symbol();
717 mlir::Type hSymType = genType(hsym.GetUltimate());
718 Fortran::lower::SymbolBox hsb =
719 lookupSymbol(hsym, /*symMap=*/nullptr, /*forceHlfirBase=*/true);
720
721 auto allocate = [&](llvm::ArrayRef<mlir::Value> shape,
722 llvm::ArrayRef<mlir::Value> typeParams) -> mlir::Value {
723 mlir::Value allocVal = builder->allocateLocal(
724 loc,
725 Fortran::semantics::IsAllocatableOrObjectPointer(&hsym.GetUltimate())
726 ? hSymType
727 : symType,
728 mangleName(sym), toStringRef(sym.GetUltimate().name()),
729 /*pinned=*/true, shape, typeParams,
730 sym.GetUltimate().attrs().test(Fortran::semantics::Attr::TARGET));
731 return allocVal;
732 };
733
734 fir::ExtendedValue hexv = symBoxToExtendedValue(hsb);
735 fir::ExtendedValue exv = hexv.match(
736 [&](const fir::BoxValue &box) -> fir::ExtendedValue {
737 const Fortran::semantics::DeclTypeSpec *type = sym.GetType();
738 if (type && type->IsPolymorphic())
739 TODO(loc, "create polymorphic host associated copy");
740 // Create a contiguous temp with the same shape and length as
741 // the original variable described by a fir.box.
742 llvm::SmallVector<mlir::Value> extents =
743 fir::factory::getExtents(loc, *builder, hexv);
744 if (box.isDerivedWithLenParameters())
745 TODO(loc, "get length parameters from derived type BoxValue");
746 if (box.isCharacter()) {
747 mlir::Value len = fir::factory::readCharLen(*builder, loc, box);
748 mlir::Value temp = allocate(extents, {len});
749 return fir::CharArrayBoxValue{temp, len, extents};
750 }
751 return fir::ArrayBoxValue{allocate(extents, {}), extents};
752 },
753 [&](const fir::MutableBoxValue &box) -> fir::ExtendedValue {
754 // Allocate storage for a pointer/allocatble descriptor.
755 // No shape/lengths to be passed to the alloca.
756 return fir::MutableBoxValue(allocate({}, {}), {}, {});
757 },
758 [&](const auto &) -> fir::ExtendedValue {
759 mlir::Value temp =
760 allocate(fir::factory::getExtents(loc, *builder, hexv),
761 fir::factory::getTypeParams(loc, *builder, hexv));
762 return fir::substBase(hexv, temp);
763 });
764
765 // Initialise cloned allocatable
766 hexv.match(
767 [&](const fir::MutableBoxValue &box) -> void {
768 // Do not process pointers
769 if (Fortran::semantics::IsPointer(sym.GetUltimate())) {
770 return;
771 }
772 // Allocate storage for a pointer/allocatble descriptor.
773 // No shape/lengths to be passed to the alloca.
774 const auto new_box = exv.getBoxOf<fir::MutableBoxValue>();
775
776 // allocate if allocated
777 mlir::Value isAllocated =
778 fir::factory::genIsAllocatedOrAssociatedTest(*builder, loc, box);
779 auto if_builder = builder->genIfThenElse(loc, isAllocated);
780 if_builder.genThen([&]() {
781 std::string name = mangleName(sym) + ".alloc";
782 fir::ExtendedValue read = fir::factory::genMutableBoxRead(
783 *builder, loc, box, /*mayBePolymorphic=*/false);
784 if (auto read_arr_box = read.getBoxOf<fir::ArrayBoxValue>()) {
785 fir::factory::genInlinedAllocation(
786 *builder, loc, *new_box, read_arr_box->getLBounds(),
787 read_arr_box->getExtents(),
788 /*lenParams=*/std::nullopt, name,
789 /*mustBeHeap=*/true);
790 } else if (auto read_char_arr_box =
791 read.getBoxOf<fir::CharArrayBoxValue>()) {
792 fir::factory::genInlinedAllocation(
793 *builder, loc, *new_box, read_char_arr_box->getLBounds(),
794 read_char_arr_box->getExtents(), read_char_arr_box->getLen(),
795 name,
796 /*mustBeHeap=*/true);
797 } else if (auto read_char_box =
798 read.getBoxOf<fir::CharBoxValue>()) {
799 fir::factory::genInlinedAllocation(*builder, loc, *new_box,
800 /*lbounds=*/std::nullopt,
801 /*extents=*/std::nullopt,
802 read_char_box->getLen(), name,
803 /*mustBeHeap=*/true);
804 } else {
805 fir::factory::genInlinedAllocation(
806 *builder, loc, *new_box, box.getMutableProperties().lbounds,
807 box.getMutableProperties().extents,
808 box.nonDeferredLenParams(), name,
809 /*mustBeHeap=*/true);
810 }
811 });
812 if_builder.genElse([&]() {
813 // nullify box
814 auto empty = fir::factory::createUnallocatedBox(
815 *builder, loc, new_box->getBoxTy(),
816 new_box->nonDeferredLenParams(), {});
817 builder->create<fir::StoreOp>(loc, empty, new_box->getAddr());
818 });
819 if_builder.end();
820 },
821 [&](const auto &) -> void {
822 // Do nothing
823 });
824
825 return bindIfNewSymbol(sym, exv);
826 }
827
828 void createHostAssociateVarCloneDealloc(
829 const Fortran::semantics::Symbol &sym) override final {
830 mlir::Location loc = genLocation(sym.name());
831 Fortran::lower::SymbolBox hsb =
832 lookupSymbol(sym, /*symMap=*/nullptr, /*forceHlfirBase=*/true);
833
834 fir::ExtendedValue hexv = symBoxToExtendedValue(hsb);
835 hexv.match(
836 [&](const fir::MutableBoxValue &new_box) -> void {
837 // Do not process pointers
838 if (Fortran::semantics::IsPointer(sym.GetUltimate())) {
839 return;
840 }
841 // deallocate allocated in createHostAssociateVarClone value
842 Fortran::lower::genDeallocateIfAllocated(*this, new_box, loc);
843 },
844 [&](const auto &) -> void {
845 // Do nothing
846 });
847 }
848
849 void copyVar(mlir::Location loc, mlir::Value dst, mlir::Value src,
850 fir::FortranVariableFlagsEnum attrs) override final {
851 bool isAllocatable =
852 bitEnumContainsAny(attrs, fir::FortranVariableFlagsEnum::allocatable);
853 bool isPointer =
854 bitEnumContainsAny(attrs, fir::FortranVariableFlagsEnum::pointer);
855
856 copyVarHLFIR(loc, Fortran::lower::SymbolBox::Intrinsic{dst},
857 Fortran::lower::SymbolBox::Intrinsic{src}, isAllocatable,
858 isPointer);
859 }
860
861 void copyHostAssociateVar(
862 const Fortran::semantics::Symbol &sym,
863 mlir::OpBuilder::InsertPoint *copyAssignIP = nullptr) override final {
864 // 1) Fetch the original copy of the variable.
865 assert(sym.has<Fortran::semantics::HostAssocDetails>() &&
866 "No host-association found");
867 const Fortran::semantics::Symbol &hsym = sym.GetUltimate();
868 Fortran::lower::SymbolBox hsb = lookupOneLevelUpSymbol(hsym);
869 assert(hsb && "Host symbol box not found");
870
871 // 2) Fetch the copied one that will mask the original.
872 Fortran::lower::SymbolBox sb = shallowLookupSymbol(sym);
873 assert(sb && "Host-associated symbol box not found");
874 assert(hsb.getAddr() != sb.getAddr() &&
875 "Host and associated symbol boxes are the same");
876
877 // 3) Perform the assignment.
878 mlir::OpBuilder::InsertPoint insPt = builder->saveInsertionPoint();
879 if (copyAssignIP && copyAssignIP->isSet())
880 builder->restoreInsertionPoint(*copyAssignIP);
881 else
882 builder->setInsertionPointAfter(sb.getAddr().getDefiningOp());
883
884 Fortran::lower::SymbolBox *lhs_sb, *rhs_sb;
885 if (copyAssignIP && copyAssignIP->isSet() &&
886 sym.test(Fortran::semantics::Symbol::Flag::OmpLastPrivate)) {
887 // lastprivate case
888 lhs_sb = &hsb;
889 rhs_sb = &sb;
890 } else {
891 lhs_sb = &sb;
892 rhs_sb = &hsb;
893 }
894
895 copyVar(sym, *lhs_sb, *rhs_sb);
896
897 if (copyAssignIP && copyAssignIP->isSet() &&
898 sym.test(Fortran::semantics::Symbol::Flag::OmpLastPrivate)) {
899 builder->restoreInsertionPoint(insPt);
900 }
901 }
902
903 void genEval(Fortran::lower::pft::Evaluation &eval,
904 bool unstructuredContext) override final {
905 genFIR(eval, unstructuredContext);
906 }
907
908 //===--------------------------------------------------------------------===//
909 // Utility methods
910 //===--------------------------------------------------------------------===//
911
912 void collectSymbolSet(
913 Fortran::lower::pft::Evaluation &eval,
914 llvm::SetVector<const Fortran::semantics::Symbol *> &symbolSet,
915 Fortran::semantics::Symbol::Flag flag, bool collectSymbols,
916 bool checkHostAssociatedSymbols) override final {
917 auto addToList = [&](const Fortran::semantics::Symbol &sym) {
918 std::function<void(const Fortran::semantics::Symbol &, bool)>
919 insertSymbols = [&](const Fortran::semantics::Symbol &oriSymbol,
920 bool collectSymbol) {
921 if (collectSymbol && oriSymbol.test(flag))
922 symbolSet.insert(&oriSymbol);
923 else if (checkHostAssociatedSymbols)
924 if (const auto *details{
925 oriSymbol
926 .detailsIf<Fortran::semantics::HostAssocDetails>()})
927 insertSymbols(details->symbol(), true);
928 };
929 insertSymbols(sym, collectSymbols);
930 };
931 Fortran::lower::pft::visitAllSymbols(eval, addToList);
932 }
933
934 mlir::Location getCurrentLocation() override final { return toLocation(); }
935
936 /// Generate a dummy location.
937 mlir::Location genUnknownLocation() override final {
938 // Note: builder may not be instantiated yet
939 return mlir::UnknownLoc::get(&getMLIRContext());
940 }
941
942 /// Generate a `Location` from the `CharBlock`.
943 mlir::Location
944 genLocation(const Fortran::parser::CharBlock &block) override final {
945 if (const Fortran::parser::AllCookedSources *cooked =
946 bridge.getCookedSource()) {
947 if (std::optional<Fortran::parser::ProvenanceRange> provenance =
948 cooked->GetProvenanceRange(block)) {
949 if (std::optional<Fortran::parser::SourcePosition> filePos =
950 cooked->allSources().GetSourcePosition(provenance->start())) {
951 llvm::SmallString<256> filePath(*filePos->path);
952 llvm::sys::fs::make_absolute(filePath);
953 llvm::sys::path::remove_dots(filePath);
954 return mlir::FileLineColLoc::get(&getMLIRContext(), filePath.str(),
955 filePos->line, filePos->column);
956 }
957 }
958 }
959 return genUnknownLocation();
960 }
961
962 const Fortran::semantics::Scope &getCurrentScope() override final {
963 return bridge.getSemanticsContext().FindScope(currentPosition);
964 }
965
966 fir::FirOpBuilder &getFirOpBuilder() override final { return *builder; }
967
968 mlir::ModuleOp &getModuleOp() override final { return bridge.getModule(); }
969
970 mlir::MLIRContext &getMLIRContext() override final {
971 return bridge.getMLIRContext();
972 }
973 std::string
974 mangleName(const Fortran::semantics::Symbol &symbol) override final {
975 return Fortran::lower::mangle::mangleName(
976 symbol, scopeBlockIdMap, /*keepExternalInScope=*/false,
977 getLoweringOptions().getUnderscoring());
978 }
979 std::string mangleName(
980 const Fortran::semantics::DerivedTypeSpec &derivedType) override final {
981 return Fortran::lower::mangle::mangleName(derivedType, scopeBlockIdMap);
982 }
983 std::string mangleName(std::string &name) override final {
984 return Fortran::lower::mangle::mangleName(name, getCurrentScope(),
985 scopeBlockIdMap);
986 }
987 std::string getRecordTypeFieldName(
988 const Fortran::semantics::Symbol &component) override final {
989 return Fortran::lower::mangle::getRecordTypeFieldName(component,
990 scopeBlockIdMap);
991 }
992 const fir::KindMapping &getKindMap() override final {
993 return bridge.getKindMap();
994 }
995
996 /// Return the current function context, which may be a nested BLOCK context
997 /// or a full subprogram context.
998 Fortran::lower::StatementContext &getFctCtx() override final {
999 if (!activeConstructStack.empty() &&
1000 activeConstructStack.back().eval.isA<Fortran::parser::BlockConstruct>())
1001 return activeConstructStack.back().stmtCtx;
1002 return bridge.fctCtx();
1003 }
1004
1005 mlir::Value hostAssocTupleValue() override final { return hostAssocTuple; }
1006
1007 /// Record a binding for the ssa-value of the tuple for this function.
1008 void bindHostAssocTuple(mlir::Value val) override final {
1009 assert(!hostAssocTuple && val);
1010 hostAssocTuple = val;
1011 }
1012
1013 mlir::Value dummyArgsScopeValue() const override final {
1014 return dummyArgsScope;
1015 }
1016
1017 bool isRegisteredDummySymbol(
1018 Fortran::semantics::SymbolRef symRef) const override final {
1019 auto *sym = &*symRef;
1020 return registeredDummySymbols.contains(sym);
1021 }
1022
1023 void registerTypeInfo(mlir::Location loc,
1024 Fortran::lower::SymbolRef typeInfoSym,
1025 const Fortran::semantics::DerivedTypeSpec &typeSpec,
1026 fir::RecordType type) override final {
1027 typeInfoConverter.registerTypeInfo(*this, loc, typeInfoSym, typeSpec, type);
1028 }
1029
1030 llvm::StringRef
1031 getUniqueLitName(mlir::Location loc,
1032 std::unique_ptr<Fortran::lower::SomeExpr> expr,
1033 mlir::Type eleTy) override final {
1034 std::string namePrefix =
1035 getConstantExprManglePrefix(loc, *expr.get(), eleTy);
1036 auto [it, inserted] = literalNamesMap.try_emplace(
1037 expr.get(), namePrefix + std::to_string(uniqueLitId));
1038 const auto &name = it->second;
1039 if (inserted) {
1040 // Keep ownership of the expr key.
1041 literalExprsStorage.push_back(std::move(expr));
1042
1043 // If we've just added a new name, we have to make sure
1044 // there is no global object with the same name in the module.
1045 fir::GlobalOp global = builder->getNamedGlobal(name);
1046 if (global)
1047 fir::emitFatalError(loc, llvm::Twine("global object with name '") +
1048 llvm::Twine(name) +
1049 llvm::Twine("' already exists"));
1050 ++uniqueLitId;
1051 return name;
1052 }
1053
1054 // The name already exists. Verify that the prefix is the same.
1055 if (!llvm::StringRef(name).starts_with(namePrefix))
1056 fir::emitFatalError(loc, llvm::Twine("conflicting prefixes: '") +
1057 llvm::Twine(name) +
1058 llvm::Twine("' does not start with '") +
1059 llvm::Twine(namePrefix) + llvm::Twine("'"));
1060
1061 return name;
1062 }
1063
1064 private:
1065 FirConverter() = delete;
1066 FirConverter(const FirConverter &) = delete;
1067 FirConverter &operator=(const FirConverter &) = delete;
1068
1069 //===--------------------------------------------------------------------===//
1070 // Helper member functions
1071 //===--------------------------------------------------------------------===//
1072
1073 mlir::Value createFIRExpr(mlir::Location loc,
1074 const Fortran::lower::SomeExpr *expr,
1075 Fortran::lower::StatementContext &stmtCtx) {
1076 return fir::getBase(genExprValue(*expr, stmtCtx, &loc));
1077 }
1078
1079 /// Find the symbol in the local map or return null.
1080 Fortran::lower::SymbolBox
1081 lookupSymbol(const Fortran::semantics::Symbol &sym,
1082 Fortran::lower::SymMap *symMap = nullptr,
1083 bool forceHlfirBase = false) {
1084 symMap = symMap ? symMap : &localSymbols;
1085 if (lowerToHighLevelFIR()) {
1086 if (std::optional<fir::FortranVariableOpInterface> var =
1087 symMap->lookupVariableDefinition(sym)) {
1088 auto exv = hlfir::translateToExtendedValue(toLocation(), *builder, *var,
1089 forceHlfirBase);
1090 return exv.match(
1091 [](mlir::Value x) -> Fortran::lower::SymbolBox {
1092 return Fortran::lower::SymbolBox::Intrinsic{x};
1093 },
1094 [](auto x) -> Fortran::lower::SymbolBox { return x; });
1095 }
1096
1097 // Entry character result represented as an argument pair
1098 // needs to be represented in the symbol table even before
1099 // we can create DeclareOp for it. The temporary mapping
1100 // is EmboxCharOp that conveys the address and length information.
1101 // After mapSymbolAttributes is done, the mapping is replaced
1102 // with the new DeclareOp, and the following table lookups
1103 // do not reach here.
1104 if (sym.IsFuncResult())
1105 if (const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType())
1106 if (declTy->category() ==
1107 Fortran::semantics::DeclTypeSpec::Category::Character)
1108 return symMap->lookupSymbol(sym);
1109
1110 // Procedure dummies are not mapped with an hlfir.declare because
1111 // they are not "variable" (cannot be assigned to), and it would
1112 // make hlfir.declare more complex than it needs to to allow this.
1113 // Do a regular lookup.
1114 if (Fortran::semantics::IsProcedure(sym))
1115 return symMap->lookupSymbol(sym);
1116
1117 // Commonblock names are not variables, but in some lowerings (like
1118 // OpenMP) it is useful to maintain the address of the commonblock in an
1119 // MLIR value and query it. hlfir.declare need not be created for these.
1120 if (sym.detailsIf<Fortran::semantics::CommonBlockDetails>())
1121 return symMap->lookupSymbol(sym);
1122
1123 // For symbols to be privatized in OMP, the symbol is mapped to an
1124 // instance of `SymbolBox::Intrinsic` (i.e. a direct mapping to an MLIR
1125 // SSA value). This MLIR SSA value is the block argument to the
1126 // `omp.private`'s `alloc` block. If this is the case, we return this
1127 // `SymbolBox::Intrinsic` value.
1128 if (Fortran::lower::SymbolBox v = symMap->lookupSymbol(sym))
1129 return v;
1130
1131 return {};
1132 }
1133 if (Fortran::lower::SymbolBox v = symMap->lookupSymbol(sym))
1134 return v;
1135 return {};
1136 }
1137
1138 /// Find the symbol in the inner-most level of the local map or return null.
1139 Fortran::lower::SymbolBox
1140 shallowLookupSymbol(const Fortran::semantics::Symbol &sym) {
1141 if (Fortran::lower::SymbolBox v = localSymbols.shallowLookupSymbol(sym))
1142 return v;
1143 return {};
1144 }
1145
1146 /// Find the symbol in one level up of symbol map such as for host-association
1147 /// in OpenMP code or return null.
1148 Fortran::lower::SymbolBox
1149 lookupOneLevelUpSymbol(const Fortran::semantics::Symbol &sym) override {
1150 if (Fortran::lower::SymbolBox v = localSymbols.lookupOneLevelUpSymbol(sym))
1151 return v;
1152 return {};
1153 }
1154
1155 mlir::SymbolTable *getMLIRSymbolTable() override { return &mlirSymbolTable; }
1156
1157 /// Add the symbol to the local map and return `true`. If the symbol is
1158 /// already in the map and \p forced is `false`, the map is not updated.
1159 /// Instead the value `false` is returned.
1160 bool addSymbol(const Fortran::semantics::SymbolRef sym,
1161 fir::ExtendedValue val, bool forced = false) {
1162 if (!forced && lookupSymbol(sym))
1163 return false;
1164 if (lowerToHighLevelFIR()) {
1165 Fortran::lower::genDeclareSymbol(*this, localSymbols, sym, val,
1166 fir::FortranVariableFlagsEnum::None,
1167 forced);
1168 } else {
1169 localSymbols.addSymbol(sym, val, forced);
1170 }
1171 return true;
1172 }
1173
1174 void copyVar(const Fortran::semantics::Symbol &sym,
1175 const Fortran::lower::SymbolBox &lhs_sb,
1176 const Fortran::lower::SymbolBox &rhs_sb) {
1177 mlir::Location loc = genLocation(sym.name());
1178 if (lowerToHighLevelFIR())
1179 copyVarHLFIR(loc, lhs_sb, rhs_sb);
1180 else
1181 copyVarFIR(loc, sym, lhs_sb, rhs_sb);
1182 }
1183
1184 void copyVarHLFIR(mlir::Location loc, Fortran::lower::SymbolBox dst,
1185 Fortran::lower::SymbolBox src) {
1186 assert(lowerToHighLevelFIR());
1187
1188 bool isBoxAllocatable = dst.match(
1189 [](const fir::MutableBoxValue &box) { return box.isAllocatable(); },
1190 [](const fir::FortranVariableOpInterface &box) {
1191 return fir::FortranVariableOpInterface(box).isAllocatable();
1192 },
1193 [](const auto &box) { return false; });
1194
1195 bool isBoxPointer = dst.match(
1196 [](const fir::MutableBoxValue &box) { return box.isPointer(); },
1197 [](const fir::FortranVariableOpInterface &box) {
1198 return fir::FortranVariableOpInterface(box).isPointer();
1199 },
1200 [](const auto &box) { return false; });
1201
1202 copyVarHLFIR(loc, dst, src, isBoxAllocatable, isBoxPointer);
1203 }
1204
1205 void copyVarHLFIR(mlir::Location loc, Fortran::lower::SymbolBox dst,
1206 Fortran::lower::SymbolBox src, bool isAllocatable,
1207 bool isPointer) {
1208 assert(lowerToHighLevelFIR());
1209 hlfir::Entity lhs{dst.getAddr()};
1210 hlfir::Entity rhs{src.getAddr()};
1211 // Temporary_lhs is set to true in hlfir.assign below to avoid user
1212 // assignment to be used and finalization to be called on the LHS.
1213 // This may or may not be correct but mimics the current behaviour
1214 // without HLFIR.
1215 auto copyData = [&](hlfir::Entity l, hlfir::Entity r) {
1216 // Dereference RHS and load it if trivial scalar.
1217 r = hlfir::loadTrivialScalar(loc, *builder, r);
1218 builder->create<hlfir::AssignOp>(
1219 loc, r, l,
1220 /*isWholeAllocatableAssignment=*/false,
1221 /*keepLhsLengthInAllocatableAssignment=*/false,
1222 /*temporary_lhs=*/true);
1223 };
1224
1225 if (isAllocatable) {
1226 // Deep copy allocatable if it is allocated.
1227 // Note that when allocated, the RHS is already allocated with the LHS
1228 // shape for copy on entry in createHostAssociateVarClone.
1229 // For lastprivate, this assumes that the RHS was not reallocated in
1230 // the OpenMP region.
1231 lhs = hlfir::derefPointersAndAllocatables(loc, *builder, lhs);
1232 mlir::Value addr = hlfir::genVariableRawAddress(loc, *builder, lhs);
1233 mlir::Value isAllocated = builder->genIsNotNullAddr(loc, addr);
1234 builder->genIfThen(loc, isAllocated)
1235 .genThen([&]() {
1236 // Copy the DATA, not the descriptors.
1237 copyData(lhs, rhs);
1238 })
1239 .end();
1240 } else if (isPointer) {
1241 // Set LHS target to the target of RHS (do not copy the RHS
1242 // target data into the LHS target storage).
1243 auto loadVal = builder->create<fir::LoadOp>(loc, rhs);
1244 builder->create<fir::StoreOp>(loc, loadVal, lhs);
1245 } else {
1246 // Non ALLOCATABLE/POINTER variable. Simple DATA copy.
1247 copyData(lhs, rhs);
1248 }
1249 }
1250
1251 void copyVarFIR(mlir::Location loc, const Fortran::semantics::Symbol &sym,
1252 const Fortran::lower::SymbolBox &lhs_sb,
1253 const Fortran::lower::SymbolBox &rhs_sb) {
1254 assert(!lowerToHighLevelFIR());
1255 fir::ExtendedValue lhs = symBoxToExtendedValue(lhs_sb);
1256 fir::ExtendedValue rhs = symBoxToExtendedValue(rhs_sb);
1257 mlir::Type symType = genType(sym);
1258 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(symType)) {
1259 Fortran::lower::StatementContext stmtCtx;
1260 Fortran::lower::createSomeArrayAssignment(*this, lhs, rhs, localSymbols,
1261 stmtCtx);
1262 stmtCtx.finalizeAndReset();
1263 } else if (lhs.getBoxOf<fir::CharBoxValue>()) {
1264 fir::factory::CharacterExprHelper{*builder, loc}.createAssign(lhs, rhs);
1265 } else {
1266 auto loadVal = builder->create<fir::LoadOp>(loc, fir::getBase(rhs));
1267 builder->create<fir::StoreOp>(loc, loadVal, fir::getBase(lhs));
1268 }
1269 }
1270
1271 /// Map a block argument to a result or dummy symbol. This is not the
1272 /// definitive mapping. The specification expression have not been lowered
1273 /// yet. The final mapping will be done using this pre-mapping in
1274 /// Fortran::lower::mapSymbolAttributes.
1275 bool mapBlockArgToDummyOrResult(const Fortran::semantics::SymbolRef sym,
1276 mlir::Value val, bool isResult) {
1277 localSymbols.addSymbol(sym, val);
1278 if (!isResult)
1279 registerDummySymbol(sym);
1280
1281 return true;
1282 }
1283
1284 /// Generate the address of loop variable \p sym.
1285 /// If \p sym is not mapped yet, allocate local storage for it.
1286 mlir::Value genLoopVariableAddress(mlir::Location loc,
1287 const Fortran::semantics::Symbol &sym,
1288 bool isUnordered) {
1289 if (isUnordered || sym.has<Fortran::semantics::HostAssocDetails>() ||
1290 sym.has<Fortran::semantics::UseDetails>()) {
1291 if (!shallowLookupSymbol(sym)) {
1292 // Do concurrent loop variables are not mapped yet since they are local
1293 // to the Do concurrent scope (same for OpenMP loops).
1294 mlir::OpBuilder::InsertPoint insPt = builder->saveInsertionPoint();
1295 builder->setInsertionPointToStart(builder->getAllocaBlock());
1296 mlir::Type tempTy = genType(sym);
1297 mlir::Value temp =
1298 builder->createTemporaryAlloc(loc, tempTy, toStringRef(sym.name()));
1299 bindIfNewSymbol(sym, temp);
1300 builder->restoreInsertionPoint(insPt);
1301 }
1302 }
1303 auto entry = lookupSymbol(sym);
1304 (void)entry;
1305 assert(entry && "loop control variable must already be in map");
1306 Fortran::lower::StatementContext stmtCtx;
1307 return fir::getBase(
1308 genExprAddr(Fortran::evaluate::AsGenericExpr(sym).value(), stmtCtx));
1309 }
1310
1311 static bool isNumericScalarCategory(Fortran::common::TypeCategory cat) {
1312 return cat == Fortran::common::TypeCategory::Integer ||
1313 cat == Fortran::common::TypeCategory::Real ||
1314 cat == Fortran::common::TypeCategory::Complex ||
1315 cat == Fortran::common::TypeCategory::Logical;
1316 }
1317 static bool isLogicalCategory(Fortran::common::TypeCategory cat) {
1318 return cat == Fortran::common::TypeCategory::Logical;
1319 }
1320 static bool isCharacterCategory(Fortran::common::TypeCategory cat) {
1321 return cat == Fortran::common::TypeCategory::Character;
1322 }
1323 static bool isDerivedCategory(Fortran::common::TypeCategory cat) {
1324 return cat == Fortran::common::TypeCategory::Derived;
1325 }
1326
1327 /// Insert a new block before \p block. Leave the insertion point unchanged.
1328 mlir::Block *insertBlock(mlir::Block *block) {
1329 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
1330 mlir::Block *newBlock = builder->createBlock(block);
1331 builder->restoreInsertionPoint(insertPt);
1332 return newBlock;
1333 }
1334
1335 Fortran::lower::pft::Evaluation &evalOfLabel(Fortran::parser::Label label) {
1336 const Fortran::lower::pft::LabelEvalMap &labelEvaluationMap =
1337 getEval().getOwningProcedure()->labelEvaluationMap;
1338 const auto iter = labelEvaluationMap.find(label);
1339 assert(iter != labelEvaluationMap.end() && "label missing from map");
1340 return *iter->second;
1341 }
1342
1343 void genBranch(mlir::Block *targetBlock) {
1344 assert(targetBlock && "missing unconditional target block");
1345 builder->create<mlir::cf::BranchOp>(toLocation(), targetBlock);
1346 }
1347
1348 void genConditionalBranch(mlir::Value cond, mlir::Block *trueTarget,
1349 mlir::Block *falseTarget) {
1350 assert(trueTarget && "missing conditional branch true block");
1351 assert(falseTarget && "missing conditional branch false block");
1352 mlir::Location loc = toLocation();
1353 mlir::Value bcc = builder->createConvert(loc, builder->getI1Type(), cond);
1354 builder->create<mlir::cf::CondBranchOp>(loc, bcc, trueTarget, std::nullopt,
1355 falseTarget, std::nullopt);
1356 }
1357 void genConditionalBranch(mlir::Value cond,
1358 Fortran::lower::pft::Evaluation *trueTarget,
1359 Fortran::lower::pft::Evaluation *falseTarget) {
1360 genConditionalBranch(cond, trueTarget->block, falseTarget->block);
1361 }
1362 void genConditionalBranch(const Fortran::parser::ScalarLogicalExpr &expr,
1363 mlir::Block *trueTarget, mlir::Block *falseTarget) {
1364 Fortran::lower::StatementContext stmtCtx;
1365 mlir::Value cond =
1366 createFIRExpr(toLocation(), Fortran::semantics::GetExpr(expr), stmtCtx);
1367 stmtCtx.finalizeAndReset();
1368 genConditionalBranch(cond, trueTarget, falseTarget);
1369 }
1370 void genConditionalBranch(const Fortran::parser::ScalarLogicalExpr &expr,
1371 Fortran::lower::pft::Evaluation *trueTarget,
1372 Fortran::lower::pft::Evaluation *falseTarget) {
1373 Fortran::lower::StatementContext stmtCtx;
1374 mlir::Value cond =
1375 createFIRExpr(toLocation(), Fortran::semantics::GetExpr(expr), stmtCtx);
1376 stmtCtx.finalizeAndReset();
1377 genConditionalBranch(cond, trueTarget->block, falseTarget->block);
1378 }
1379
1380 /// Return the nearest active ancestor construct of \p eval, or nullptr.
1381 Fortran::lower::pft::Evaluation *
1382 getActiveAncestor(const Fortran::lower::pft::Evaluation &eval) {
1383 Fortran::lower::pft::Evaluation *ancestor = eval.parentConstruct;
1384 for (; ancestor; ancestor = ancestor->parentConstruct)
1385 if (ancestor->activeConstruct)
1386 break;
1387 return ancestor;
1388 }
1389
1390 /// Return the predicate: "a branch to \p targetEval has exit code".
1391 bool hasExitCode(const Fortran::lower::pft::Evaluation &targetEval) {
1392 Fortran::lower::pft::Evaluation *activeAncestor =
1393 getActiveAncestor(targetEval);
1394 for (auto it = activeConstructStack.rbegin(),
1395 rend = activeConstructStack.rend();
1396 it != rend; ++it) {
1397 if (&it->eval == activeAncestor)
1398 break;
1399 if (it->stmtCtx.hasCode())
1400 return true;
1401 }
1402 return false;
1403 }
1404
1405 /// Generate a branch to \p targetEval after generating on-exit code for
1406 /// any enclosing construct scopes that are exited by taking the branch.
1407 void
1408 genConstructExitBranch(const Fortran::lower::pft::Evaluation &targetEval) {
1409 Fortran::lower::pft::Evaluation *activeAncestor =
1410 getActiveAncestor(targetEval);
1411 for (auto it = activeConstructStack.rbegin(),
1412 rend = activeConstructStack.rend();
1413 it != rend; ++it) {
1414 if (&it->eval == activeAncestor)
1415 break;
1416 it->stmtCtx.finalizeAndKeep();
1417 }
1418 genBranch(targetEval.block);
1419 }
1420
1421 /// A construct contains nested evaluations. Some of these evaluations
1422 /// may start a new basic block, others will add code to an existing
1423 /// block.
1424 /// Collect the list of nested evaluations that are last in their block,
1425 /// organize them into two sets:
1426 /// 1. Exiting evaluations: they may need a branch exiting from their
1427 /// parent construct,
1428 /// 2. Fall-through evaluations: they will continue to the following
1429 /// evaluation. They may still need a branch, but they do not exit
1430 /// the construct. They appear in cases where the following evaluation
1431 /// is a target of some branch.
1432 void collectFinalEvaluations(
1433 Fortran::lower::pft::Evaluation &construct,
1434 llvm::SmallVector<Fortran::lower::pft::Evaluation *> &exits,
1435 llvm::SmallVector<Fortran::lower::pft::Evaluation *> &fallThroughs) {
1436 Fortran::lower::pft::EvaluationList &nested =
1437 construct.getNestedEvaluations();
1438 if (nested.empty())
1439 return;
1440
1441 Fortran::lower::pft::Evaluation *exit = construct.constructExit;
1442 Fortran::lower::pft::Evaluation *previous = &nested.front();
1443
1444 for (auto it = ++nested.begin(), end = nested.end(); it != end;
1445 previous = &*it++) {
1446 if (it->block == nullptr)
1447 continue;
1448 // "*it" starts a new block, check what to do with "previous"
1449 if (it->isIntermediateConstructStmt() && previous != exit)
1450 exits.push_back(previous);
1451 else if (previous->lexicalSuccessor && previous->lexicalSuccessor->block)
1452 fallThroughs.push_back(previous);
1453 }
1454 if (previous != exit)
1455 exits.push_back(previous);
1456 }
1457
1458 /// Generate a SelectOp or branch sequence that compares \p selector against
1459 /// values in \p valueList and targets corresponding labels in \p labelList.
1460 /// If no value matches the selector, branch to \p defaultEval.
1461 ///
1462 /// Three cases require special processing.
1463 ///
1464 /// An empty \p valueList indicates an ArithmeticIfStmt context that requires
1465 /// two comparisons against 0 or 0.0. The selector may have either INTEGER
1466 /// or REAL type.
1467 ///
1468 /// A nonpositive \p valuelist value indicates an IO statement context
1469 /// (0 for ERR, -1 for END, -2 for EOR). An ERR branch must be taken for
1470 /// any positive (IOSTAT) value. A missing (zero) label requires a branch
1471 /// to \p defaultEval for that value.
1472 ///
1473 /// A non-null \p errorBlock indicates an AssignedGotoStmt context that
1474 /// must always branch to an explicit target. There is no valid defaultEval
1475 /// in this case. Generate a branch to \p errorBlock for an AssignedGotoStmt
1476 /// that violates this program requirement.
1477 ///
1478 /// If this is not an ArithmeticIfStmt and no targets have exit code,
1479 /// generate a SelectOp. Otherwise, for each target, if it has exit code,
1480 /// branch to a new block, insert exit code, and then branch to the target.
1481 /// Otherwise, branch directly to the target.
1482 void genMultiwayBranch(mlir::Value selector,
1483 llvm::SmallVector<int64_t> valueList,
1484 llvm::SmallVector<Fortran::parser::Label> labelList,
1485 const Fortran::lower::pft::Evaluation &defaultEval,
1486 mlir::Block *errorBlock = nullptr) {
1487 bool inArithmeticIfContext = valueList.empty();
1488 assert(((inArithmeticIfContext && labelList.size() == 2) ||
1489 (valueList.size() && labelList.size() == valueList.size())) &&
1490 "mismatched multiway branch targets");
1491 mlir::Block *defaultBlock = errorBlock ? errorBlock : defaultEval.block;
1492 bool defaultHasExitCode = !errorBlock && hasExitCode(defaultEval);
1493 bool hasAnyExitCode = defaultHasExitCode;
1494 if (!hasAnyExitCode)
1495 for (auto label : labelList)
1496 if (label && hasExitCode(evalOfLabel(label))) {
1497 hasAnyExitCode = true;
1498 break;
1499 }
1500 mlir::Location loc = toLocation();
1501 size_t branchCount = labelList.size();
1502 if (!inArithmeticIfContext && !hasAnyExitCode &&
1503 !getEval().forceAsUnstructured()) { // from -no-structured-fir option
1504 // Generate a SelectOp.
1505 llvm::SmallVector<mlir::Block *> blockList;
1506 for (auto label : labelList) {
1507 mlir::Block *block =
1508 label ? evalOfLabel(label).block : defaultEval.block;
1509 assert(block && "missing multiway branch block");
1510 blockList.push_back(block);
1511 }
1512 blockList.push_back(defaultBlock);
1513 if (valueList[branchCount - 1] == 0) // Swap IO ERR and default blocks.
1514 std::swap(blockList[branchCount - 1], blockList[branchCount]);
1515 builder->create<fir::SelectOp>(loc, selector, valueList, blockList);
1516 return;
1517 }
1518 mlir::Type selectorType = selector.getType();
1519 bool realSelector = mlir::isa<mlir::FloatType>(selectorType);
1520 assert((inArithmeticIfContext || !realSelector) && "invalid selector type");
1521 mlir::Value zero;
1522 if (inArithmeticIfContext)
1523 zero =
1524 realSelector
1525 ? builder->create<mlir::arith::ConstantOp>(
1526 loc, selectorType, builder->getFloatAttr(selectorType, 0.0))
1527 : builder->createIntegerConstant(loc, selectorType, 0);
1528 for (auto label : llvm::enumerate(labelList)) {
1529 mlir::Value cond;
1530 if (realSelector) // inArithmeticIfContext
1531 cond = builder->create<mlir::arith::CmpFOp>(
1532 loc,
1533 label.index() == 0 ? mlir::arith::CmpFPredicate::OLT
1534 : mlir::arith::CmpFPredicate::OGT,
1535 selector, zero);
1536 else if (inArithmeticIfContext) // INTEGER selector
1537 cond = builder->create<mlir::arith::CmpIOp>(
1538 loc,
1539 label.index() == 0 ? mlir::arith::CmpIPredicate::slt
1540 : mlir::arith::CmpIPredicate::sgt,
1541 selector, zero);
1542 else // A value of 0 is an IO ERR branch: invert comparison.
1543 cond = builder->create<mlir::arith::CmpIOp>(
1544 loc,
1545 valueList[label.index()] == 0 ? mlir::arith::CmpIPredicate::ne
1546 : mlir::arith::CmpIPredicate::eq,
1547 selector,
1548 builder->createIntegerConstant(loc, selectorType,
1549 valueList[label.index()]));
1550 // Branch to a new block with exit code and then to the target, or branch
1551 // directly to the target. defaultBlock is the "else" target.
1552 bool lastBranch = label.index() == branchCount - 1;
1553 mlir::Block *nextBlock =
1554 lastBranch && !defaultHasExitCode
1555 ? defaultBlock
1556 : builder->getBlock()->splitBlock(builder->getInsertionPoint());
1557 const Fortran::lower::pft::Evaluation &targetEval =
1558 label.value() ? evalOfLabel(label.value()) : defaultEval;
1559 if (hasExitCode(targetEval)) {
1560 mlir::Block *jumpBlock =
1561 builder->getBlock()->splitBlock(builder->getInsertionPoint());
1562 genConditionalBranch(cond, jumpBlock, nextBlock);
1563 startBlock(jumpBlock);
1564 genConstructExitBranch(targetEval);
1565 } else {
1566 genConditionalBranch(cond, targetEval.block, nextBlock);
1567 }
1568 if (!lastBranch) {
1569 startBlock(nextBlock);
1570 } else if (defaultHasExitCode) {
1571 startBlock(nextBlock);
1572 genConstructExitBranch(defaultEval);
1573 }
1574 }
1575 }
1576
1577 void pushActiveConstruct(Fortran::lower::pft::Evaluation &eval,
1578 Fortran::lower::StatementContext &stmtCtx) {
1579 activeConstructStack.push_back(ConstructContext{eval, stmtCtx});
1580 eval.activeConstruct = true;
1581 }
1582 void popActiveConstruct() {
1583 assert(!activeConstructStack.empty() && "invalid active construct stack");
1584 activeConstructStack.back().eval.activeConstruct = false;
1585 if (activeConstructStack.back().pushedScope)
1586 localSymbols.popScope();
1587 activeConstructStack.pop_back();
1588 }
1589
1590 //===--------------------------------------------------------------------===//
1591 // Termination of symbolically referenced execution units
1592 //===--------------------------------------------------------------------===//
1593
1594 /// END of program
1595 ///
1596 /// Generate the cleanup block before the program exits
1597 void genExitRoutine() {
1598
1599 if (blockIsUnterminated())
1600 builder->create<mlir::func::ReturnOp>(toLocation());
1601 }
1602
1603 /// END of procedure-like constructs
1604 ///
1605 /// Generate the cleanup block before the procedure exits
1606 void genReturnSymbol(const Fortran::semantics::Symbol &functionSymbol) {
1607 const Fortran::semantics::Symbol &resultSym =
1608 functionSymbol.get<Fortran::semantics::SubprogramDetails>().result();
1609 Fortran::lower::SymbolBox resultSymBox = lookupSymbol(resultSym);
1610 mlir::Location loc = toLocation();
1611 if (!resultSymBox) {
1612 mlir::emitError(loc, "internal error when processing function return");
1613 return;
1614 }
1615 mlir::Value resultVal = resultSymBox.match(
1616 [&](const fir::CharBoxValue &x) -> mlir::Value {
1617 if (Fortran::semantics::IsBindCProcedure(functionSymbol))
1618 return builder->create<fir::LoadOp>(loc, x.getBuffer());
1619 return fir::factory::CharacterExprHelper{*builder, loc}
1620 .createEmboxChar(x.getBuffer(), x.getLen());
1621 },
1622 [&](const fir::MutableBoxValue &x) -> mlir::Value {
1623 mlir::Value resultRef = resultSymBox.getAddr();
1624 mlir::Value load = builder->create<fir::LoadOp>(loc, resultRef);
1625 unsigned rank = x.rank();
1626 if (x.isAllocatable() && rank > 0) {
1627 // ALLOCATABLE array result must have default lower bounds.
1628 // At the call site the result box of a function reference
1629 // might be considered having default lower bounds, but
1630 // the runtime box should probably comply with this assumption
1631 // as well. If the result box has proper lbounds in runtime,
1632 // this may improve the debugging experience of Fortran apps.
1633 // We may consider removing this, if the overhead of setting
1634 // default lower bounds is too big.
1635 mlir::Value one =
1636 builder->createIntegerConstant(loc, builder->getIndexType(), 1);
1637 llvm::SmallVector<mlir::Value> lbounds{rank, one};
1638 auto shiftTy = fir::ShiftType::get(builder->getContext(), rank);
1639 mlir::Value shiftOp =
1640 builder->create<fir::ShiftOp>(loc, shiftTy, lbounds);
1641 load = builder->create<fir::ReboxOp>(
1642 loc, load.getType(), load, shiftOp, /*slice=*/mlir::Value{});
1643 }
1644 return load;
1645 },
1646 [&](const auto &) -> mlir::Value {
1647 mlir::Value resultRef = resultSymBox.getAddr();
1648 mlir::Type resultType = genType(resultSym);
1649 mlir::Type resultRefType = builder->getRefType(resultType);
1650 // A function with multiple entry points returning different types
1651 // tags all result variables with one of the largest types to allow
1652 // them to share the same storage. Convert this to the actual type.
1653 if (resultRef.getType() != resultRefType)
1654 resultRef = builder->createConvert(loc, resultRefType, resultRef);
1655 return builder->create<fir::LoadOp>(loc, resultRef);
1656 });
1657 bridge.openAccCtx().finalizeAndPop();
1658 bridge.fctCtx().finalizeAndPop();
1659 builder->create<mlir::func::ReturnOp>(loc, resultVal);
1660 }
1661
1662 /// Get the return value of a call to \p symbol, which is a subroutine entry
1663 /// point that has alternative return specifiers.
1664 const mlir::Value
1665 getAltReturnResult(const Fortran::semantics::Symbol &symbol) {
1666 assert(Fortran::semantics::HasAlternateReturns(symbol) &&
1667 "subroutine does not have alternate returns");
1668 return getSymbolAddress(symbol);
1669 }
1670
1671 void genFIRProcedureExit(Fortran::lower::pft::FunctionLikeUnit &funit,
1672 const Fortran::semantics::Symbol &symbol) {
1673 if (mlir::Block *finalBlock = funit.finalBlock) {
1674 // The current block must end with a terminator.
1675 if (blockIsUnterminated())
1676 builder->create<mlir::cf::BranchOp>(toLocation(), finalBlock);
1677 // Set insertion point to final block.
1678 builder->setInsertionPoint(finalBlock, finalBlock->end());
1679 }
1680 if (Fortran::semantics::IsFunction(symbol)) {
1681 genReturnSymbol(symbol);
1682 } else if (Fortran::semantics::HasAlternateReturns(symbol)) {
1683 mlir::Value retval = builder->create<fir::LoadOp>(
1684 toLocation(), getAltReturnResult(symbol));
1685 bridge.openAccCtx().finalizeAndPop();
1686 bridge.fctCtx().finalizeAndPop();
1687 builder->create<mlir::func::ReturnOp>(toLocation(), retval);
1688 } else {
1689 bridge.openAccCtx().finalizeAndPop();
1690 bridge.fctCtx().finalizeAndPop();
1691 genExitRoutine();
1692 }
1693 }
1694
1695 //
1696 // Statements that have control-flow semantics
1697 //
1698
1699 /// Generate an If[Then]Stmt condition or its negation.
1700 template <typename A>
1701 mlir::Value genIfCondition(const A *stmt, bool negate = false) {
1702 mlir::Location loc = toLocation();
1703 Fortran::lower::StatementContext stmtCtx;
1704 mlir::Value condExpr = createFIRExpr(
1705 loc,
1706 Fortran::semantics::GetExpr(
1707 std::get<Fortran::parser::ScalarLogicalExpr>(stmt->t)),
1708 stmtCtx);
1709 stmtCtx.finalizeAndReset();
1710 mlir::Value cond =
1711 builder->createConvert(loc, builder->getI1Type(), condExpr);
1712 if (negate)
1713 cond = builder->create<mlir::arith::XOrIOp>(
1714 loc, cond, builder->createIntegerConstant(loc, cond.getType(), 1));
1715 return cond;
1716 }
1717
1718 mlir::func::FuncOp getFunc(llvm::StringRef name, mlir::FunctionType ty) {
1719 if (mlir::func::FuncOp func = builder->getNamedFunction(name)) {
1720 assert(func.getFunctionType() == ty);
1721 return func;
1722 }
1723 return builder->createFunction(toLocation(), name, ty);
1724 }
1725
1726 /// Lowering of CALL statement
1727 void genFIR(const Fortran::parser::CallStmt &stmt) {
1728 Fortran::lower::StatementContext stmtCtx;
1729 Fortran::lower::pft::Evaluation &eval = getEval();
1730 setCurrentPosition(stmt.source);
1731 assert(stmt.typedCall && "Call was not analyzed");
1732 mlir::Value res{};
1733 if (lowerToHighLevelFIR()) {
1734 std::optional<mlir::Type> resultType;
1735 if (stmt.typedCall->hasAlternateReturns())
1736 resultType = builder->getIndexType();
1737 auto hlfirRes = Fortran::lower::convertCallToHLFIR(
1738 toLocation(), *this, *stmt.typedCall, resultType, localSymbols,
1739 stmtCtx);
1740 if (hlfirRes)
1741 res = *hlfirRes;
1742 } else {
1743 // Call statement lowering shares code with function call lowering.
1744 res = Fortran::lower::createSubroutineCall(
1745 *this, *stmt.typedCall, explicitIterSpace, implicitIterSpace,
1746 localSymbols, stmtCtx, /*isUserDefAssignment=*/false);
1747 }
1748 stmtCtx.finalizeAndReset();
1749 if (!res)
1750 return; // "Normal" subroutine call.
1751 // Call with alternate return specifiers.
1752 // The call returns an index that selects an alternate return branch target.
1753 llvm::SmallVector<int64_t> indexList;
1754 llvm::SmallVector<Fortran::parser::Label> labelList;
1755 int64_t index = 0;
1756 for (const Fortran::parser::ActualArgSpec &arg :
1757 std::get<std::list<Fortran::parser::ActualArgSpec>>(stmt.call.t)) {
1758 const auto &actual = std::get<Fortran::parser::ActualArg>(arg.t);
1759 if (const auto *altReturn =
1760 std::get_if<Fortran::parser::AltReturnSpec>(&actual.u)) {
1761 indexList.push_back(++index);
1762 labelList.push_back(altReturn->v);
1763 }
1764 }
1765 genMultiwayBranch(res, indexList, labelList, eval.nonNopSuccessor());
1766 }
1767
1768 void genFIR(const Fortran::parser::ComputedGotoStmt &stmt) {
1769 Fortran::lower::StatementContext stmtCtx;
1770 Fortran::lower::pft::Evaluation &eval = getEval();
1771 mlir::Value selectExpr =
1772 createFIRExpr(toLocation(),
1773 Fortran::semantics::GetExpr(
1774 std::get<Fortran::parser::ScalarIntExpr>(stmt.t)),
1775 stmtCtx);
1776 stmtCtx.finalizeAndReset();
1777 llvm::SmallVector<int64_t> indexList;
1778 llvm::SmallVector<Fortran::parser::Label> labelList;
1779 int64_t index = 0;
1780 for (Fortran::parser::Label label :
1781 std::get<std::list<Fortran::parser::Label>>(stmt.t)) {
1782 indexList.push_back(++index);
1783 labelList.push_back(label);
1784 }
1785 genMultiwayBranch(selectExpr, indexList, labelList, eval.nonNopSuccessor());
1786 }
1787
1788 void genFIR(const Fortran::parser::ArithmeticIfStmt &stmt) {
1789 Fortran::lower::StatementContext stmtCtx;
1790 mlir::Value expr = createFIRExpr(
1791 toLocation(),
1792 Fortran::semantics::GetExpr(std::get<Fortran::parser::Expr>(stmt.t)),
1793 stmtCtx);
1794 stmtCtx.finalizeAndReset();
1795 // Raise an exception if REAL expr is a NaN.
1796 if (mlir::isa<mlir::FloatType>(expr.getType()))
1797 expr = builder->create<mlir::arith::AddFOp>(toLocation(), expr, expr);
1798 // An empty valueList indicates to genMultiwayBranch that the branch is
1799 // an ArithmeticIfStmt that has two branches on value 0 or 0.0.
1800 llvm::SmallVector<int64_t> valueList;
1801 llvm::SmallVector<Fortran::parser::Label> labelList;
1802 labelList.push_back(std::get<1>(stmt.t));
1803 labelList.push_back(std::get<3>(stmt.t));
1804 const Fortran::lower::pft::LabelEvalMap &labelEvaluationMap =
1805 getEval().getOwningProcedure()->labelEvaluationMap;
1806 const auto iter = labelEvaluationMap.find(std::get<2>(stmt.t));
1807 assert(iter != labelEvaluationMap.end() && "label missing from map");
1808 genMultiwayBranch(expr, valueList, labelList, *iter->second);
1809 }
1810
1811 void genFIR(const Fortran::parser::AssignedGotoStmt &stmt) {
1812 // See Fortran 90 Clause 8.2.4.
1813 // Relax the requirement that the GOTO variable must have a value in the
1814 // label list when a list is present, and allow a branch to any non-format
1815 // target that has an ASSIGN statement for the variable.
1816 mlir::Location loc = toLocation();
1817 Fortran::lower::pft::Evaluation &eval = getEval();
1818 Fortran::lower::pft::FunctionLikeUnit &owningProc =
1819 *eval.getOwningProcedure();
1820 const Fortran::lower::pft::SymbolLabelMap &symbolLabelMap =
1821 owningProc.assignSymbolLabelMap;
1822 const Fortran::lower::pft::LabelEvalMap &labelEvalMap =
1823 owningProc.labelEvaluationMap;
1824 const Fortran::semantics::Symbol &symbol =
1825 *std::get<Fortran::parser::Name>(stmt.t).symbol;
1826 auto labelSetIter = symbolLabelMap.find(symbol);
1827 llvm::SmallVector<int64_t> valueList;
1828 llvm::SmallVector<Fortran::parser::Label> labelList;
1829 if (labelSetIter != symbolLabelMap.end()) {
1830 for (auto &label : labelSetIter->second) {
1831 const auto evalIter = labelEvalMap.find(label);
1832 assert(evalIter != labelEvalMap.end() && "assigned goto label missing");
1833 if (evalIter->second->block) { // non-format statement
1834 valueList.push_back(label); // label as an integer
1835 labelList.push_back(label);
1836 }
1837 }
1838 }
1839 if (!labelList.empty()) {
1840 auto selectExpr =
1841 builder->create<fir::LoadOp>(loc, getSymbolAddress(symbol));
1842 // Add a default error target in case the goto is nonconforming.
1843 mlir::Block *errorBlock =
1844 builder->getBlock()->splitBlock(builder->getInsertionPoint());
1845 genMultiwayBranch(selectExpr, valueList, labelList,
1846 eval.nonNopSuccessor(), errorBlock);
1847 startBlock(errorBlock);
1848 }
1849 fir::runtime::genReportFatalUserError(
1850 *builder, loc,
1851 "Assigned GOTO variable '" + symbol.name().ToString() +
1852 "' does not have a valid target label value");
1853 builder->create<fir::UnreachableOp>(loc);
1854 }
1855
1856 fir::ReduceOperationEnum
1857 getReduceOperationEnum(const Fortran::parser::ReductionOperator &rOpr) {
1858 switch (rOpr.v) {
1859 case Fortran::parser::ReductionOperator::Operator::Plus:
1860 return fir::ReduceOperationEnum::Add;
1861 case Fortran::parser::ReductionOperator::Operator::Multiply:
1862 return fir::ReduceOperationEnum::Multiply;
1863 case Fortran::parser::ReductionOperator::Operator::And:
1864 return fir::ReduceOperationEnum::AND;
1865 case Fortran::parser::ReductionOperator::Operator::Or:
1866 return fir::ReduceOperationEnum::OR;
1867 case Fortran::parser::ReductionOperator::Operator::Eqv:
1868 return fir::ReduceOperationEnum::EQV;
1869 case Fortran::parser::ReductionOperator::Operator::Neqv:
1870 return fir::ReduceOperationEnum::NEQV;
1871 case Fortran::parser::ReductionOperator::Operator::Max:
1872 return fir::ReduceOperationEnum::MAX;
1873 case Fortran::parser::ReductionOperator::Operator::Min:
1874 return fir::ReduceOperationEnum::MIN;
1875 case Fortran::parser::ReductionOperator::Operator::Iand:
1876 return fir::ReduceOperationEnum::IAND;
1877 case Fortran::parser::ReductionOperator::Operator::Ior:
1878 return fir::ReduceOperationEnum::IOR;
1879 case Fortran::parser::ReductionOperator::Operator::Ieor:
1880 return fir::ReduceOperationEnum::EIOR;
1881 }
1882 llvm_unreachable("illegal reduction operator");
1883 }
1884
1885 /// Collect DO CONCURRENT or FORALL loop control information.
1886 IncrementLoopNestInfo getConcurrentControl(
1887 const Fortran::parser::ConcurrentHeader &header,
1888 const std::list<Fortran::parser::LocalitySpec> &localityList = {}) {
1889 IncrementLoopNestInfo incrementLoopNestInfo;
1890 for (const Fortran::parser::ConcurrentControl &control :
1891 std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t))
1892 incrementLoopNestInfo.emplace_back(
1893 *std::get<0>(control.t).symbol, std::get<1>(control.t),
1894 std::get<2>(control.t), std::get<3>(control.t), /*isUnordered=*/true);
1895 IncrementLoopInfo &info = incrementLoopNestInfo.back();
1896 info.maskExpr = Fortran::semantics::GetExpr(
1897 std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>(header.t));
1898 for (const Fortran::parser::LocalitySpec &x : localityList) {
1899 if (const auto *localList =
1900 std::get_if<Fortran::parser::LocalitySpec::Local>(&x.u))
1901 for (const Fortran::parser::Name &x : localList->v)
1902 info.localSymList.push_back(x.symbol);
1903 if (const auto *localInitList =
1904 std::get_if<Fortran::parser::LocalitySpec::LocalInit>(&x.u))
1905 for (const Fortran::parser::Name &x : localInitList->v)
1906 info.localInitSymList.push_back(x.symbol);
1907 for (IncrementLoopInfo &info : incrementLoopNestInfo) {
1908 if (const auto *reduceList =
1909 std::get_if<Fortran::parser::LocalitySpec::Reduce>(&x.u)) {
1910 fir::ReduceOperationEnum reduce_operation = getReduceOperationEnum(
1911 std::get<Fortran::parser::ReductionOperator>(reduceList->t));
1912 for (const Fortran::parser::Name &x :
1913 std::get<std::list<Fortran::parser::Name>>(reduceList->t)) {
1914 info.reduceSymList.push_back(
1915 std::make_pair(reduce_operation, x.symbol));
1916 }
1917 }
1918 }
1919 if (const auto *sharedList =
1920 std::get_if<Fortran::parser::LocalitySpec::Shared>(&x.u))
1921 for (const Fortran::parser::Name &x : sharedList->v)
1922 info.sharedSymList.push_back(x.symbol);
1923 }
1924 return incrementLoopNestInfo;
1925 }
1926
1927 /// Create DO CONCURRENT construct symbol bindings and generate LOCAL_INIT
1928 /// assignments.
1929 void handleLocalitySpecs(const IncrementLoopInfo &info) {
1930 Fortran::semantics::SemanticsContext &semanticsContext =
1931 bridge.getSemanticsContext();
1932 for (const Fortran::semantics::Symbol *sym : info.localSymList)
1933 createHostAssociateVarClone(*sym);
1934 for (const Fortran::semantics::Symbol *sym : info.localInitSymList) {
1935 createHostAssociateVarClone(*sym);
1936 const auto *hostDetails =
1937 sym->detailsIf<Fortran::semantics::HostAssocDetails>();
1938 assert(hostDetails && "missing locality spec host symbol");
1939 const Fortran::semantics::Symbol *hostSym = &hostDetails->symbol();
1940 Fortran::evaluate::ExpressionAnalyzer ea{semanticsContext};
1941 Fortran::evaluate::Assignment assign{
1942 ea.Designate(Fortran::evaluate::DataRef{*sym}).value(),
1943 ea.Designate(Fortran::evaluate::DataRef{*hostSym}).value()};
1944 if (Fortran::semantics::IsPointer(*sym))
1945 assign.u = Fortran::evaluate::Assignment::BoundsSpec{};
1946 genAssignment(assign);
1947 }
1948 for (const Fortran::semantics::Symbol *sym : info.sharedSymList) {
1949 const auto *hostDetails =
1950 sym->detailsIf<Fortran::semantics::HostAssocDetails>();
1951 copySymbolBinding(hostDetails->symbol(), *sym);
1952 }
1953 }
1954
1955 /// Generate FIR for a DO construct. There are six variants:
1956 /// - unstructured infinite and while loops
1957 /// - structured and unstructured increment loops
1958 /// - structured and unstructured concurrent loops
1959 void genFIR(const Fortran::parser::DoConstruct &doConstruct) {
1960 setCurrentPositionAt(doConstruct);
1961 // Collect loop nest information.
1962 // Generate begin loop code directly for infinite and while loops.
1963 Fortran::lower::pft::Evaluation &eval = getEval();
1964 bool unstructuredContext = eval.lowerAsUnstructured();
1965 Fortran::lower::pft::Evaluation &doStmtEval =
1966 eval.getFirstNestedEvaluation();
1967 auto *doStmt = doStmtEval.getIf<Fortran::parser::NonLabelDoStmt>();
1968 const auto &loopControl =
1969 std::get<std::optional<Fortran::parser::LoopControl>>(doStmt->t);
1970 mlir::Block *preheaderBlock = doStmtEval.block;
1971 mlir::Block *beginBlock =
1972 preheaderBlock ? preheaderBlock : builder->getBlock();
1973 auto createNextBeginBlock = [&]() {
1974 // Step beginBlock through unstructured preheader, header, and mask
1975 // blocks, created in outermost to innermost order.
1976 return beginBlock = beginBlock->splitBlock(beginBlock->end());
1977 };
1978 mlir::Block *headerBlock =
1979 unstructuredContext ? createNextBeginBlock() : nullptr;
1980 mlir::Block *bodyBlock = doStmtEval.lexicalSuccessor->block;
1981 mlir::Block *exitBlock = doStmtEval.parentConstruct->constructExit->block;
1982 IncrementLoopNestInfo incrementLoopNestInfo;
1983 const Fortran::parser::ScalarLogicalExpr *whileCondition = nullptr;
1984 bool infiniteLoop = !loopControl.has_value();
1985 if (infiniteLoop) {
1986 assert(unstructuredContext && "infinite loop must be unstructured");
1987 startBlock(headerBlock);
1988 } else if ((whileCondition =
1989 std::get_if<Fortran::parser::ScalarLogicalExpr>(
1990 &loopControl->u))) {
1991 assert(unstructuredContext && "while loop must be unstructured");
1992 maybeStartBlock(preheaderBlock); // no block or empty block
1993 startBlock(headerBlock);
1994 genConditionalBranch(*whileCondition, bodyBlock, exitBlock);
1995 } else if (const auto *bounds =
1996 std::get_if<Fortran::parser::LoopControl::Bounds>(
1997 &loopControl->u)) {
1998 // Non-concurrent increment loop.
1999 IncrementLoopInfo &info = incrementLoopNestInfo.emplace_back(
2000 *bounds->name.thing.symbol, bounds->lower, bounds->upper,
2001 bounds->step);
2002 if (unstructuredContext) {
2003 maybeStartBlock(preheaderBlock);
2004 info.hasRealControl = info.loopVariableSym->GetType()->IsNumeric(
2005 Fortran::common::TypeCategory::Real);
2006 info.headerBlock = headerBlock;
2007 info.bodyBlock = bodyBlock;
2008 info.exitBlock = exitBlock;
2009 }
2010 } else {
2011 const auto *concurrent =
2012 std::get_if<Fortran::parser::LoopControl::Concurrent>(
2013 &loopControl->u);
2014 assert(concurrent && "invalid DO loop variant");
2015 incrementLoopNestInfo = getConcurrentControl(
2016 std::get<Fortran::parser::ConcurrentHeader>(concurrent->t),
2017 std::get<std::list<Fortran::parser::LocalitySpec>>(concurrent->t));
2018 if (unstructuredContext) {
2019 maybeStartBlock(preheaderBlock);
2020 for (IncrementLoopInfo &info : incrementLoopNestInfo) {
2021 // The original loop body provides the body and latch blocks of the
2022 // innermost dimension. The (first) body block of a non-innermost
2023 // dimension is the preheader block of the immediately enclosed
2024 // dimension. The latch block of a non-innermost dimension is the
2025 // exit block of the immediately enclosed dimension.
2026 auto createNextExitBlock = [&]() {
2027 // Create unstructured loop exit blocks, outermost to innermost.
2028 return exitBlock = insertBlock(exitBlock);
2029 };
2030 bool isInnermost = &info == &incrementLoopNestInfo.back();
2031 bool isOutermost = &info == &incrementLoopNestInfo.front();
2032 info.headerBlock = isOutermost ? headerBlock : createNextBeginBlock();
2033 info.bodyBlock = isInnermost ? bodyBlock : createNextBeginBlock();
2034 info.exitBlock = isOutermost ? exitBlock : createNextExitBlock();
2035 if (info.maskExpr)
2036 info.maskBlock = createNextBeginBlock();
2037 }
2038 }
2039 }
2040
2041 // Increment loop begin code. (Infinite/while code was already generated.)
2042 if (!infiniteLoop && !whileCondition)
2043 genFIRIncrementLoopBegin(incrementLoopNestInfo, doStmtEval.dirs);
2044
2045 // Loop body code.
2046 auto iter = eval.getNestedEvaluations().begin();
2047 for (auto end = --eval.getNestedEvaluations().end(); iter != end; ++iter)
2048 genFIR(*iter, unstructuredContext);
2049
2050 // An EndDoStmt in unstructured code may start a new block.
2051 Fortran::lower::pft::Evaluation &endDoEval = *iter;
2052 assert(endDoEval.getIf<Fortran::parser::EndDoStmt>() && "no enddo stmt");
2053 if (unstructuredContext)
2054 maybeStartBlock(endDoEval.block);
2055
2056 // Loop end code.
2057 if (infiniteLoop || whileCondition)
2058 genBranch(headerBlock);
2059 else
2060 genFIRIncrementLoopEnd(incrementLoopNestInfo);
2061
2062 // This call may generate a branch in some contexts.
2063 genFIR(endDoEval, unstructuredContext);
2064 }
2065
2066 /// Generate FIR to evaluate loop control values (lower, upper and step).
2067 mlir::Value genControlValue(const Fortran::lower::SomeExpr *expr,
2068 const IncrementLoopInfo &info,
2069 bool *isConst = nullptr) {
2070 mlir::Location loc = toLocation();
2071 mlir::Type controlType = info.isStructured() ? builder->getIndexType()
2072 : info.getLoopVariableType();
2073 Fortran::lower::StatementContext stmtCtx;
2074 if (expr) {
2075 if (isConst)
2076 *isConst = Fortran::evaluate::IsConstantExpr(*expr);
2077 return builder->createConvert(loc, controlType,
2078 createFIRExpr(loc, expr, stmtCtx));
2079 }
2080
2081 if (isConst)
2082 *isConst = true;
2083 if (info.hasRealControl)
2084 return builder->createRealConstant(loc, controlType, 1u);
2085 return builder->createIntegerConstant(loc, controlType, 1); // step
2086 }
2087
2088 void addLoopAnnotationAttr(IncrementLoopInfo &info) {
2089 mlir::BoolAttr f = mlir::BoolAttr::get(builder->getContext(), false);
2090 mlir::LLVM::LoopVectorizeAttr va = mlir::LLVM::LoopVectorizeAttr::get(
2091 builder->getContext(), /*disable=*/f, {}, {}, {}, {}, {}, {});
2092 mlir::LLVM::LoopAnnotationAttr la = mlir::LLVM::LoopAnnotationAttr::get(
2093 builder->getContext(), {}, /*vectorize=*/va, {}, {}, {}, {}, {}, {}, {},
2094 {}, {}, {}, {}, {}, {});
2095 info.doLoop.setLoopAnnotationAttr(la);
2096 }
2097
2098 /// Generate FIR to begin a structured or unstructured increment loop nest.
2099 void genFIRIncrementLoopBegin(
2100 IncrementLoopNestInfo &incrementLoopNestInfo,
2101 llvm::SmallVectorImpl<const Fortran::parser::CompilerDirective *> &dirs) {
2102 assert(!incrementLoopNestInfo.empty() && "empty loop nest");
2103 mlir::Location loc = toLocation();
2104 for (IncrementLoopInfo &info : incrementLoopNestInfo) {
2105 info.loopVariable =
2106 genLoopVariableAddress(loc, *info.loopVariableSym, info.isUnordered);
2107 mlir::Value lowerValue = genControlValue(info.lowerExpr, info);
2108 mlir::Value upperValue = genControlValue(info.upperExpr, info);
2109 bool isConst = true;
2110 mlir::Value stepValue = genControlValue(
2111 info.stepExpr, info, info.isStructured() ? nullptr : &isConst);
2112 // Use a temp variable for unstructured loops with non-const step.
2113 if (!isConst) {
2114 info.stepVariable = builder->createTemporary(loc, stepValue.getType());
2115 builder->create<fir::StoreOp>(loc, stepValue, info.stepVariable);
2116 }
2117
2118 // Structured loop - generate fir.do_loop.
2119 if (info.isStructured()) {
2120 mlir::Type loopVarType = info.getLoopVariableType();
2121 mlir::Value loopValue;
2122 if (info.isUnordered) {
2123 llvm::SmallVector<mlir::Value> reduceOperands;
2124 llvm::SmallVector<mlir::Attribute> reduceAttrs;
2125 // Create DO CONCURRENT reduce operands and attributes
2126 for (const auto &reduceSym : info.reduceSymList) {
2127 const fir::ReduceOperationEnum reduce_operation = reduceSym.first;
2128 const Fortran::semantics::Symbol *sym = reduceSym.second;
2129 fir::ExtendedValue exv = getSymbolExtendedValue(*sym, nullptr);
2130 reduceOperands.push_back(fir::getBase(exv));
2131 auto reduce_attr =
2132 fir::ReduceAttr::get(builder->getContext(), reduce_operation);
2133 reduceAttrs.push_back(reduce_attr);
2134 }
2135 // The loop variable value is explicitly updated.
2136 info.doLoop = builder->create<fir::DoLoopOp>(
2137 loc, lowerValue, upperValue, stepValue, /*unordered=*/true,
2138 /*finalCountValue=*/false, /*iterArgs=*/std::nullopt,
2139 llvm::ArrayRef<mlir::Value>(reduceOperands), reduceAttrs);
2140 builder->setInsertionPointToStart(info.doLoop.getBody());
2141 loopValue = builder->createConvert(loc, loopVarType,
2142 info.doLoop.getInductionVar());
2143 } else {
2144 // The loop variable is a doLoop op argument.
2145 info.doLoop = builder->create<fir::DoLoopOp>(
2146 loc, lowerValue, upperValue, stepValue, /*unordered=*/false,
2147 /*finalCountValue=*/true,
2148 builder->createConvert(loc, loopVarType, lowerValue));
2149 builder->setInsertionPointToStart(info.doLoop.getBody());
2150 loopValue = info.doLoop.getRegionIterArgs()[0];
2151 }
2152 // Update the loop variable value in case it has non-index references.
2153 builder->create<fir::StoreOp>(loc, loopValue, info.loopVariable);
2154 if (info.maskExpr) {
2155 Fortran::lower::StatementContext stmtCtx;
2156 mlir::Value maskCond = createFIRExpr(loc, info.maskExpr, stmtCtx);
2157 stmtCtx.finalizeAndReset();
2158 mlir::Value maskCondCast =
2159 builder->createConvert(loc, builder->getI1Type(), maskCond);
2160 auto ifOp = builder->create<fir::IfOp>(loc, maskCondCast,
2161 /*withElseRegion=*/false);
2162 builder->setInsertionPointToStart(&ifOp.getThenRegion().front());
2163 }
2164 if (info.hasLocalitySpecs())
2165 handleLocalitySpecs(info);
2166
2167 for (const auto *dir : dirs) {
2168 Fortran::common::visit(
2169 Fortran::common::visitors{
2170 [&](const Fortran::parser::CompilerDirective::VectorAlways
2171 &d) { addLoopAnnotationAttr(info); },
2172 [&](const auto &) {}},
2173 dir->u);
2174 }
2175 continue;
2176 }
2177
2178 // Unstructured loop preheader - initialize tripVariable and loopVariable.
2179 mlir::Value tripCount;
2180 if (info.hasRealControl) {
2181 auto diff1 =
2182 builder->create<mlir::arith::SubFOp>(loc, upperValue, lowerValue);
2183 auto diff2 =
2184 builder->create<mlir::arith::AddFOp>(loc, diff1, stepValue);
2185 tripCount = builder->create<mlir::arith::DivFOp>(loc, diff2, stepValue);
2186 tripCount =
2187 builder->createConvert(loc, builder->getIndexType(), tripCount);
2188 } else {
2189 auto diff1 =
2190 builder->create<mlir::arith::SubIOp>(loc, upperValue, lowerValue);
2191 auto diff2 =
2192 builder->create<mlir::arith::AddIOp>(loc, diff1, stepValue);
2193 tripCount =
2194 builder->create<mlir::arith::DivSIOp>(loc, diff2, stepValue);
2195 }
2196 if (forceLoopToExecuteOnce) { // minimum tripCount is 1
2197 mlir::Value one =
2198 builder->createIntegerConstant(loc, tripCount.getType(), 1);
2199 auto cond = builder->create<mlir::arith::CmpIOp>(
2200 loc, mlir::arith::CmpIPredicate::slt, tripCount, one);
2201 tripCount =
2202 builder->create<mlir::arith::SelectOp>(loc, cond, one, tripCount);
2203 }
2204 info.tripVariable = builder->createTemporary(loc, tripCount.getType());
2205 builder->create<fir::StoreOp>(loc, tripCount, info.tripVariable);
2206 builder->create<fir::StoreOp>(loc, lowerValue, info.loopVariable);
2207
2208 // Unstructured loop header - generate loop condition and mask.
2209 // Note - Currently there is no way to tag a loop as a concurrent loop.
2210 startBlock(info.headerBlock);
2211 tripCount = builder->create<fir::LoadOp>(loc, info.tripVariable);
2212 mlir::Value zero =
2213 builder->createIntegerConstant(loc, tripCount.getType(), 0);
2214 auto cond = builder->create<mlir::arith::CmpIOp>(
2215 loc, mlir::arith::CmpIPredicate::sgt, tripCount, zero);
2216 if (info.maskExpr) {
2217 genConditionalBranch(cond, info.maskBlock, info.exitBlock);
2218 startBlock(info.maskBlock);
2219 mlir::Block *latchBlock = getEval().getLastNestedEvaluation().block;
2220 assert(latchBlock && "missing masked concurrent loop latch block");
2221 Fortran::lower::StatementContext stmtCtx;
2222 mlir::Value maskCond = createFIRExpr(loc, info.maskExpr, stmtCtx);
2223 stmtCtx.finalizeAndReset();
2224 genConditionalBranch(maskCond, info.bodyBlock, latchBlock);
2225 } else {
2226 genConditionalBranch(cond, info.bodyBlock, info.exitBlock);
2227 if (&info != &incrementLoopNestInfo.back()) // not innermost
2228 startBlock(info.bodyBlock); // preheader block of enclosed dimension
2229 }
2230 if (info.hasLocalitySpecs()) {
2231 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
2232 builder->setInsertionPointToStart(info.bodyBlock);
2233 handleLocalitySpecs(info);
2234 builder->restoreInsertionPoint(insertPt);
2235 }
2236 }
2237 }
2238
2239 /// Generate FIR to end a structured or unstructured increment loop nest.
2240 void genFIRIncrementLoopEnd(IncrementLoopNestInfo &incrementLoopNestInfo) {
2241 assert(!incrementLoopNestInfo.empty() && "empty loop nest");
2242 mlir::Location loc = toLocation();
2243 mlir::arith::IntegerOverflowFlags flags{};
2244 if (getLoweringOptions().getNSWOnLoopVarInc())
2245 flags = bitEnumSet(flags, mlir::arith::IntegerOverflowFlags::nsw);
2246 auto iofAttr = mlir::arith::IntegerOverflowFlagsAttr::get(
2247 builder->getContext(), flags);
2248 for (auto it = incrementLoopNestInfo.rbegin(),
2249 rend = incrementLoopNestInfo.rend();
2250 it != rend; ++it) {
2251 IncrementLoopInfo &info = *it;
2252 if (info.isStructured()) {
2253 // End fir.do_loop.
2254 if (info.isUnordered) {
2255 builder->setInsertionPointAfter(info.doLoop);
2256 continue;
2257 }
2258 // Decrement tripVariable.
2259 builder->setInsertionPointToEnd(info.doLoop.getBody());
2260 llvm::SmallVector<mlir::Value, 2> results;
2261 results.push_back(builder->create<mlir::arith::AddIOp>(
2262 loc, info.doLoop.getInductionVar(), info.doLoop.getStep(),
2263 iofAttr));
2264 // Step loopVariable to help optimizations such as vectorization.
2265 // Induction variable elimination will clean up as necessary.
2266 mlir::Value step = builder->createConvert(
2267 loc, info.getLoopVariableType(), info.doLoop.getStep());
2268 mlir::Value loopVar =
2269 builder->create<fir::LoadOp>(loc, info.loopVariable);
2270 results.push_back(
2271 builder->create<mlir::arith::AddIOp>(loc, loopVar, step, iofAttr));
2272 builder->create<fir::ResultOp>(loc, results);
2273 builder->setInsertionPointAfter(info.doLoop);
2274 // The loop control variable may be used after the loop.
2275 builder->create<fir::StoreOp>(loc, info.doLoop.getResult(1),
2276 info.loopVariable);
2277 continue;
2278 }
2279
2280 // Unstructured loop - decrement tripVariable and step loopVariable.
2281 mlir::Value tripCount =
2282 builder->create<fir::LoadOp>(loc, info.tripVariable);
2283 mlir::Value one =
2284 builder->createIntegerConstant(loc, tripCount.getType(), 1);
2285 tripCount = builder->create<mlir::arith::SubIOp>(loc, tripCount, one);
2286 builder->create<fir::StoreOp>(loc, tripCount, info.tripVariable);
2287 mlir::Value value = builder->create<fir::LoadOp>(loc, info.loopVariable);
2288 mlir::Value step;
2289 if (info.stepVariable)
2290 step = builder->create<fir::LoadOp>(loc, info.stepVariable);
2291 else
2292 step = genControlValue(info.stepExpr, info);
2293 if (info.hasRealControl)
2294 value = builder->create<mlir::arith::AddFOp>(loc, value, step);
2295 else
2296 value = builder->create<mlir::arith::AddIOp>(loc, value, step, iofAttr);
2297 builder->create<fir::StoreOp>(loc, value, info.loopVariable);
2298
2299 genBranch(info.headerBlock);
2300 if (&info != &incrementLoopNestInfo.front()) // not outermost
2301 startBlock(info.exitBlock); // latch block of enclosing dimension
2302 }
2303 }
2304
2305 /// Generate structured or unstructured FIR for an IF construct.
2306 /// The initial statement may be either an IfStmt or an IfThenStmt.
2307 void genFIR(const Fortran::parser::IfConstruct &) {
2308 Fortran::lower::pft::Evaluation &eval = getEval();
2309
2310 // Structured fir.if nest.
2311 if (eval.lowerAsStructured()) {
2312 fir::IfOp topIfOp, currentIfOp;
2313 for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) {
2314 auto genIfOp = [&](mlir::Value cond) {
2315 auto ifOp =
2316 builder->create<fir::IfOp>(toLocation(), cond, /*withElse=*/true);
2317 builder->setInsertionPointToStart(&ifOp.getThenRegion().front());
2318 return ifOp;
2319 };
2320 setCurrentPosition(e.position);
2321 if (auto *s = e.getIf<Fortran::parser::IfThenStmt>()) {
2322 topIfOp = currentIfOp = genIfOp(genIfCondition(s, e.negateCondition));
2323 } else if (auto *s = e.getIf<Fortran::parser::IfStmt>()) {
2324 topIfOp = currentIfOp = genIfOp(genIfCondition(s, e.negateCondition));
2325 } else if (auto *s = e.getIf<Fortran::parser::ElseIfStmt>()) {
2326 builder->setInsertionPointToStart(
2327 &currentIfOp.getElseRegion().front());
2328 currentIfOp = genIfOp(genIfCondition(s));
2329 } else if (e.isA<Fortran::parser::ElseStmt>()) {
2330 builder->setInsertionPointToStart(
2331 &currentIfOp.getElseRegion().front());
2332 } else if (e.isA<Fortran::parser::EndIfStmt>()) {
2333 builder->setInsertionPointAfter(topIfOp);
2334 genFIR(e, /*unstructuredContext=*/false); // may generate branch
2335 } else {
2336 genFIR(e, /*unstructuredContext=*/false);
2337 }
2338 }
2339 return;
2340 }
2341
2342 // Unstructured branch sequence.
2343 llvm::SmallVector<Fortran::lower::pft::Evaluation *> exits, fallThroughs;
2344 collectFinalEvaluations(eval, exits, fallThroughs);
2345
2346 for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) {
2347 auto genIfBranch = [&](mlir::Value cond) {
2348 if (e.lexicalSuccessor == e.controlSuccessor) // empty block -> exit
2349 genConditionalBranch(cond, e.parentConstruct->constructExit,
2350 e.controlSuccessor);
2351 else // non-empty block
2352 genConditionalBranch(cond, e.lexicalSuccessor, e.controlSuccessor);
2353 };
2354 setCurrentPosition(e.position);
2355 if (auto *s = e.getIf<Fortran::parser::IfThenStmt>()) {
2356 maybeStartBlock(e.block);
2357 genIfBranch(genIfCondition(s, e.negateCondition));
2358 } else if (auto *s = e.getIf<Fortran::parser::IfStmt>()) {
2359 maybeStartBlock(e.block);
2360 genIfBranch(genIfCondition(s, e.negateCondition));
2361 } else if (auto *s = e.getIf<Fortran::parser::ElseIfStmt>()) {
2362 startBlock(e.block);
2363 genIfBranch(genIfCondition(s));
2364 } else {
2365 genFIR(e);
2366 if (blockIsUnterminated()) {
2367 if (llvm::is_contained(exits, &e))
2368 genConstructExitBranch(*eval.constructExit);
2369 else if (llvm::is_contained(fallThroughs, &e))
2370 genBranch(e.lexicalSuccessor->block);
2371 }
2372 }
2373 }
2374 }
2375
2376 void genCaseOrRankConstruct() {
2377 Fortran::lower::pft::Evaluation &eval = getEval();
2378 Fortran::lower::StatementContext stmtCtx;
2379 pushActiveConstruct(eval, stmtCtx);
2380
2381 llvm::SmallVector<Fortran::lower::pft::Evaluation *> exits, fallThroughs;
2382 collectFinalEvaluations(eval, exits, fallThroughs);
2383
2384 for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) {
2385 if (e.getIf<Fortran::parser::EndSelectStmt>())
2386 maybeStartBlock(e.block);
2387 else
2388 genFIR(e);
2389 if (blockIsUnterminated()) {
2390 if (llvm::is_contained(exits, &e))
2391 genConstructExitBranch(*eval.constructExit);
2392 else if (llvm::is_contained(fallThroughs, &e))
2393 genBranch(e.lexicalSuccessor->block);
2394 }
2395 }
2396 popActiveConstruct();
2397 }
2398 void genFIR(const Fortran::parser::CaseConstruct &) {
2399 genCaseOrRankConstruct();
2400 }
2401
2402 template <typename A>
2403 void genNestedStatement(const Fortran::parser::Statement<A> &stmt) {
2404 setCurrentPosition(stmt.source);
2405 genFIR(stmt.statement);
2406 }
2407
2408 /// Force the binding of an explicit symbol. This is used to bind and re-bind
2409 /// a concurrent control symbol to its value.
2410 void forceControlVariableBinding(const Fortran::semantics::Symbol *sym,
2411 mlir::Value inducVar) {
2412 mlir::Location loc = toLocation();
2413 assert(sym && "There must be a symbol to bind");
2414 mlir::Type toTy = genType(*sym);
2415 // FIXME: this should be a "per iteration" temporary.
2416 mlir::Value tmp =
2417 builder->createTemporary(loc, toTy, toStringRef(sym->name()),
2418 llvm::ArrayRef<mlir::NamedAttribute>{
2419 fir::getAdaptToByRefAttr(*builder)});
2420 mlir::Value cast = builder->createConvert(loc, toTy, inducVar);
2421 builder->create<fir::StoreOp>(loc, cast, tmp);
2422 addSymbol(*sym, tmp, /*force=*/true);
2423 }
2424
2425 /// Process a concurrent header for a FORALL. (Concurrent headers for DO
2426 /// CONCURRENT loops are lowered elsewhere.)
2427 void genFIR(const Fortran::parser::ConcurrentHeader &header) {
2428 llvm::SmallVector<mlir::Value> lows;
2429 llvm::SmallVector<mlir::Value> highs;
2430 llvm::SmallVector<mlir::Value> steps;
2431 if (explicitIterSpace.isOutermostForall()) {
2432 // For the outermost forall, we evaluate the bounds expressions once.
2433 // Contrastingly, if this forall is nested, the bounds expressions are
2434 // assumed to be pure, possibly dependent on outer concurrent control
2435 // variables, possibly variant with respect to arguments, and will be
2436 // re-evaluated.
2437 mlir::Location loc = toLocation();
2438 mlir::Type idxTy = builder->getIndexType();
2439 Fortran::lower::StatementContext &stmtCtx =
2440 explicitIterSpace.stmtContext();
2441 auto lowerExpr = [&](auto &e) {
2442 return fir::getBase(genExprValue(e, stmtCtx));
2443 };
2444 for (const Fortran::parser::ConcurrentControl &ctrl :
2445 std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) {
2446 const Fortran::lower::SomeExpr *lo =
2447 Fortran::semantics::GetExpr(std::get<1>(ctrl.t));
2448 const Fortran::lower::SomeExpr *hi =
2449 Fortran::semantics::GetExpr(std::get<2>(ctrl.t));
2450 auto &optStep =
2451 std::get<std::optional<Fortran::parser::ScalarIntExpr>>(ctrl.t);
2452 lows.push_back(builder->createConvert(loc, idxTy, lowerExpr(*lo)));
2453 highs.push_back(builder->createConvert(loc, idxTy, lowerExpr(*hi)));
2454 steps.push_back(
2455 optStep.has_value()
2456 ? builder->createConvert(
2457 loc, idxTy,
2458 lowerExpr(*Fortran::semantics::GetExpr(*optStep)))
2459 : builder->createIntegerConstant(loc, idxTy, 1));
2460 }
2461 }
2462 auto lambda = [&, lows, highs, steps]() {
2463 // Create our iteration space from the header spec.
2464 mlir::Location loc = toLocation();
2465 mlir::Type idxTy = builder->getIndexType();
2466 llvm::SmallVector<fir::DoLoopOp> loops;
2467 Fortran::lower::StatementContext &stmtCtx =
2468 explicitIterSpace.stmtContext();
2469 auto lowerExpr = [&](auto &e) {
2470 return fir::getBase(genExprValue(e, stmtCtx));
2471 };
2472 const bool outermost = !lows.empty();
2473 std::size_t headerIndex = 0;
2474 for (const Fortran::parser::ConcurrentControl &ctrl :
2475 std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) {
2476 const Fortran::semantics::Symbol *ctrlVar =
2477 std::get<Fortran::parser::Name>(ctrl.t).symbol;
2478 mlir::Value lb;
2479 mlir::Value ub;
2480 mlir::Value by;
2481 if (outermost) {
2482 assert(headerIndex < lows.size());
2483 if (headerIndex == 0)
2484 explicitIterSpace.resetInnerArgs();
2485 lb = lows[headerIndex];
2486 ub = highs[headerIndex];
2487 by = steps[headerIndex++];
2488 } else {
2489 const Fortran::lower::SomeExpr *lo =
2490 Fortran::semantics::GetExpr(std::get<1>(ctrl.t));
2491 const Fortran::lower::SomeExpr *hi =
2492 Fortran::semantics::GetExpr(std::get<2>(ctrl.t));
2493 auto &optStep =
2494 std::get<std::optional<Fortran::parser::ScalarIntExpr>>(ctrl.t);
2495 lb = builder->createConvert(loc, idxTy, lowerExpr(*lo));
2496 ub = builder->createConvert(loc, idxTy, lowerExpr(*hi));
2497 by = optStep.has_value()
2498 ? builder->createConvert(
2499 loc, idxTy,
2500 lowerExpr(*Fortran::semantics::GetExpr(*optStep)))
2501 : builder->createIntegerConstant(loc, idxTy, 1);
2502 }
2503 auto lp = builder->create<fir::DoLoopOp>(
2504 loc, lb, ub, by, /*unordered=*/true,
2505 /*finalCount=*/false, explicitIterSpace.getInnerArgs());
2506 if ((!loops.empty() || !outermost) && !lp.getRegionIterArgs().empty())
2507 builder->create<fir::ResultOp>(loc, lp.getResults());
2508 explicitIterSpace.setInnerArgs(lp.getRegionIterArgs());
2509 builder->setInsertionPointToStart(lp.getBody());
2510 forceControlVariableBinding(ctrlVar, lp.getInductionVar());
2511 loops.push_back(lp);
2512 }
2513 if (outermost)
2514 explicitIterSpace.setOuterLoop(loops[0]);
2515 explicitIterSpace.appendLoops(loops);
2516 if (const auto &mask =
2517 std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>(
2518 header.t);
2519 mask.has_value()) {
2520 mlir::Type i1Ty = builder->getI1Type();
2521 fir::ExtendedValue maskExv =
2522 genExprValue(*Fortran::semantics::GetExpr(mask.value()), stmtCtx);
2523 mlir::Value cond =
2524 builder->createConvert(loc, i1Ty, fir::getBase(maskExv));
2525 auto ifOp = builder->create<fir::IfOp>(
2526 loc, explicitIterSpace.innerArgTypes(), cond,
2527 /*withElseRegion=*/true);
2528 builder->create<fir::ResultOp>(loc, ifOp.getResults());
2529 builder->setInsertionPointToStart(&ifOp.getElseRegion().front());
2530 builder->create<fir::ResultOp>(loc, explicitIterSpace.getInnerArgs());
2531 builder->setInsertionPointToStart(&ifOp.getThenRegion().front());
2532 }
2533 };
2534 // Push the lambda to gen the loop nest context.
2535 explicitIterSpace.pushLoopNest(lambda);
2536 }
2537
2538 void genFIR(const Fortran::parser::ForallAssignmentStmt &stmt) {
2539 Fortran::common::visit([&](const auto &x) { genFIR(x); }, stmt.u);
2540 }
2541
2542 void genFIR(const Fortran::parser::EndForallStmt &) {
2543 if (!lowerToHighLevelFIR())
2544 cleanupExplicitSpace();
2545 }
2546
2547 template <typename A>
2548 void prepareExplicitSpace(const A &forall) {
2549 if (!explicitIterSpace.isActive())
2550 analyzeExplicitSpace(forall);
2551 localSymbols.pushScope();
2552 explicitIterSpace.enter();
2553 }
2554
2555 /// Cleanup all the FORALL context information when we exit.
2556 void cleanupExplicitSpace() {
2557 explicitIterSpace.leave();
2558 localSymbols.popScope();
2559 }
2560
2561 /// Generate FIR for a FORALL statement.
2562 void genFIR(const Fortran::parser::ForallStmt &stmt) {
2563 const auto &concurrentHeader =
2564 std::get<
2565 Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
2566 stmt.t)
2567 .value();
2568 if (lowerToHighLevelFIR()) {
2569 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
2570 localSymbols.pushScope();
2571 genForallNest(concurrentHeader);
2572 genFIR(std::get<Fortran::parser::UnlabeledStatement<
2573 Fortran::parser::ForallAssignmentStmt>>(stmt.t)
2574 .statement);
2575 localSymbols.popScope();
2576 builder->restoreInsertionPoint(insertPt);
2577 return;
2578 }
2579 prepareExplicitSpace(stmt);
2580 genFIR(concurrentHeader);
2581 genFIR(std::get<Fortran::parser::UnlabeledStatement<
2582 Fortran::parser::ForallAssignmentStmt>>(stmt.t)
2583 .statement);
2584 cleanupExplicitSpace();
2585 }
2586
2587 /// Generate FIR for a FORALL construct.
2588 void genFIR(const Fortran::parser::ForallConstruct &forall) {
2589 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
2590 if (lowerToHighLevelFIR())
2591 localSymbols.pushScope();
2592 else
2593 prepareExplicitSpace(forall);
2594 genNestedStatement(
2595 std::get<
2596 Fortran::parser::Statement<Fortran::parser::ForallConstructStmt>>(
2597 forall.t));
2598 for (const Fortran::parser::ForallBodyConstruct &s :
2599 std::get<std::list<Fortran::parser::ForallBodyConstruct>>(forall.t)) {
2600 Fortran::common::visit(
2601 Fortran::common::visitors{
2602 [&](const Fortran::parser::WhereConstruct &b) { genFIR(b); },
2603 [&](const Fortran::common::Indirection<
2604 Fortran::parser::ForallConstruct> &b) { genFIR(b.value()); },
2605 [&](const auto &b) { genNestedStatement(b); }},
2606 s.u);
2607 }
2608 genNestedStatement(
2609 std::get<Fortran::parser::Statement<Fortran::parser::EndForallStmt>>(
2610 forall.t));
2611 if (lowerToHighLevelFIR()) {
2612 localSymbols.popScope();
2613 builder->restoreInsertionPoint(insertPt);
2614 }
2615 }
2616
2617 /// Lower the concurrent header specification.
2618 void genFIR(const Fortran::parser::ForallConstructStmt &stmt) {
2619 const auto &concurrentHeader =
2620 std::get<
2621 Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
2622 stmt.t)
2623 .value();
2624 if (lowerToHighLevelFIR())
2625 genForallNest(concurrentHeader);
2626 else
2627 genFIR(concurrentHeader);
2628 }
2629
2630 /// Generate hlfir.forall and hlfir.forall_mask nest given a Forall
2631 /// concurrent header
2632 void genForallNest(const Fortran::parser::ConcurrentHeader &header) {
2633 mlir::Location loc = getCurrentLocation();
2634 const bool isOutterForall = !isInsideHlfirForallOrWhere();
2635 hlfir::ForallOp outerForall;
2636 auto evaluateControl = [&](const auto &parserExpr, mlir::Region &region,
2637 bool isMask = false) {
2638 if (region.empty())
2639 builder->createBlock(&region);
2640 Fortran::lower::StatementContext localStmtCtx;
2641 const Fortran::semantics::SomeExpr *anlalyzedExpr =
2642 Fortran::semantics::GetExpr(parserExpr);
2643 assert(anlalyzedExpr && "expression semantics failed");
2644 // Generate the controls of outer forall outside of the hlfir.forall
2645 // region. They do not depend on any previous forall indices (C1123) and
2646 // no assignment has been made yet that could modify their value. This
2647 // will simplify hlfir.forall analysis because the SSA integer value
2648 // yielded will obviously not depend on any variable modified by the
2649 // forall when produced outside of it.
2650 // This is not done for the mask because it may (and in usual code, does)
2651 // depend on the forall indices that have just been defined as
2652 // hlfir.forall block arguments.
2653 mlir::OpBuilder::InsertPoint innerInsertionPoint;
2654 if (outerForall && !isMask) {
2655 innerInsertionPoint = builder->saveInsertionPoint();
2656 builder->setInsertionPoint(outerForall);
2657 }
2658 mlir::Value exprVal =
2659 fir::getBase(genExprValue(*anlalyzedExpr, localStmtCtx, &loc));
2660 localStmtCtx.finalizeAndPop();
2661 if (isMask)
2662 exprVal = builder->createConvert(loc, builder->getI1Type(), exprVal);
2663 if (innerInsertionPoint.isSet())
2664 builder->restoreInsertionPoint(innerInsertionPoint);
2665 builder->create<hlfir::YieldOp>(loc, exprVal);
2666 };
2667 for (const Fortran::parser::ConcurrentControl &control :
2668 std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) {
2669 auto forallOp = builder->create<hlfir::ForallOp>(loc);
2670 if (isOutterForall && !outerForall)
2671 outerForall = forallOp;
2672 evaluateControl(std::get<1>(control.t), forallOp.getLbRegion());
2673 evaluateControl(std::get<2>(control.t), forallOp.getUbRegion());
2674 if (const auto &optionalStep =
2675 std::get<std::optional<Fortran::parser::ScalarIntExpr>>(
2676 control.t))
2677 evaluateControl(*optionalStep, forallOp.getStepRegion());
2678 // Create block argument and map it to a symbol via an hlfir.forall_index
2679 // op (symbols must be mapped to in memory values).
2680 const Fortran::semantics::Symbol *controlVar =
2681 std::get<Fortran::parser::Name>(control.t).symbol;
2682 assert(controlVar && "symbol analysis failed");
2683 mlir::Type controlVarType = genType(*controlVar);
2684 mlir::Block *forallBody = builder->createBlock(&forallOp.getBody(), {},
2685 {controlVarType}, {loc});
2686 auto forallIndex = builder->create<hlfir::ForallIndexOp>(
2687 loc, fir::ReferenceType::get(controlVarType),
2688 forallBody->getArguments()[0],
2689 builder->getStringAttr(controlVar->name().ToString()));
2690 localSymbols.addVariableDefinition(*controlVar, forallIndex,
2691 /*force=*/true);
2692 auto end = builder->create<fir::FirEndOp>(loc);
2693 builder->setInsertionPoint(end);
2694 }
2695
2696 if (const auto &maskExpr =
2697 std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>(
2698 header.t)) {
2699 // Create hlfir.forall_mask and set insertion point in its body.
2700 auto forallMaskOp = builder->create<hlfir::ForallMaskOp>(loc);
2701 evaluateControl(*maskExpr, forallMaskOp.getMaskRegion(), /*isMask=*/true);
2702 builder->createBlock(&forallMaskOp.getBody());
2703 auto end = builder->create<fir::FirEndOp>(loc);
2704 builder->setInsertionPoint(end);
2705 }
2706 }
2707
2708 void attachDirectiveToLoop(const Fortran::parser::CompilerDirective &dir,
2709 Fortran::lower::pft::Evaluation *e) {
2710 while (e->isDirective())
2711 e = e->lexicalSuccessor;
2712
2713 if (e->isA<Fortran::parser::NonLabelDoStmt>())
2714 e->dirs.push_back(&dir);
2715 }
2716
2717 void genFIR(const Fortran::parser::CompilerDirective &dir) {
2718 Fortran::lower::pft::Evaluation &eval = getEval();
2719
2720 Fortran::common::visit(
2721 Fortran::common::visitors{
2722 [&](const Fortran::parser::CompilerDirective::VectorAlways &) {
2723 attachDirectiveToLoop(dir, &eval);
2724 },
2725 [&](const auto &) {}},
2726 dir.u);
2727 }
2728
2729 void genFIR(const Fortran::parser::OpenACCConstruct &acc) {
2730 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
2731 localSymbols.pushScope();
2732 mlir::Value exitCond = genOpenACCConstruct(
2733 *this, bridge.getSemanticsContext(), getEval(), acc);
2734
2735 const Fortran::parser::OpenACCLoopConstruct *accLoop =
2736 std::get_if<Fortran::parser::OpenACCLoopConstruct>(&acc.u);
2737 const Fortran::parser::OpenACCCombinedConstruct *accCombined =
2738 std::get_if<Fortran::parser::OpenACCCombinedConstruct>(&acc.u);
2739
2740 Fortran::lower::pft::Evaluation *curEval = &getEval();
2741
2742 if (accLoop || accCombined) {
2743 int64_t collapseValue;
2744 if (accLoop) {
2745 const Fortran::parser::AccBeginLoopDirective &beginLoopDir =
2746 std::get<Fortran::parser::AccBeginLoopDirective>(accLoop->t);
2747 const Fortran::parser::AccClauseList &clauseList =
2748 std::get<Fortran::parser::AccClauseList>(beginLoopDir.t);
2749 collapseValue = Fortran::lower::getCollapseValue(clauseList);
2750 } else if (accCombined) {
2751 const Fortran::parser::AccBeginCombinedDirective &beginCombinedDir =
2752 std::get<Fortran::parser::AccBeginCombinedDirective>(
2753 accCombined->t);
2754 const Fortran::parser::AccClauseList &clauseList =
2755 std::get<Fortran::parser::AccClauseList>(beginCombinedDir.t);
2756 collapseValue = Fortran::lower::getCollapseValue(clauseList);
2757 }
2758
2759 if (curEval->lowerAsStructured()) {
2760 curEval = &curEval->getFirstNestedEvaluation();
2761 for (int64_t i = 1; i < collapseValue; i++)
2762 curEval = &*std::next(curEval->getNestedEvaluations().begin());
2763 }
2764 }
2765
2766 for (Fortran::lower::pft::Evaluation &e : curEval->getNestedEvaluations())
2767 genFIR(e);
2768 localSymbols.popScope();
2769 builder->restoreInsertionPoint(insertPt);
2770
2771 if (accLoop && exitCond) {
2772 Fortran::lower::pft::FunctionLikeUnit *funit =
2773 getEval().getOwningProcedure();
2774 assert(funit && "not inside main program, function or subroutine");
2775 mlir::Block *continueBlock =
2776 builder->getBlock()->splitBlock(builder->getBlock()->end());
2777 builder->create<mlir::cf::CondBranchOp>(toLocation(), exitCond,
2778 funit->finalBlock, continueBlock);
2779 builder->setInsertionPointToEnd(continueBlock);
2780 }
2781 }
2782
2783 void genFIR(const Fortran::parser::OpenACCDeclarativeConstruct &accDecl) {
2784 genOpenACCDeclarativeConstruct(*this, bridge.getSemanticsContext(),
2785 bridge.openAccCtx(), accDecl,
2786 accRoutineInfos);
2787 for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations())
2788 genFIR(e);
2789 }
2790
2791 void genFIR(const Fortran::parser::OpenACCRoutineConstruct &acc) {
2792 // Handled by genFIR(const Fortran::parser::OpenACCDeclarativeConstruct &)
2793 }
2794
2795 void genFIR(const Fortran::parser::CUFKernelDoConstruct &kernel) {
2796 localSymbols.pushScope();
2797 const Fortran::parser::CUFKernelDoConstruct::Directive &dir =
2798 std::get<Fortran::parser::CUFKernelDoConstruct::Directive>(kernel.t);
2799
2800 mlir::Location loc = genLocation(dir.source);
2801
2802 Fortran::lower::StatementContext stmtCtx;
2803
2804 unsigned nestedLoops = 1;
2805
2806 const auto &nLoops =
2807 std::get<std::optional<Fortran::parser::ScalarIntConstantExpr>>(dir.t);
2808 if (nLoops)
2809 nestedLoops = *Fortran::semantics::GetIntValue(*nLoops);
2810
2811 mlir::IntegerAttr n;
2812 if (nestedLoops > 1)
2813 n = builder->getIntegerAttr(builder->getI64Type(), nestedLoops);
2814
2815 const std::list<Fortran::parser::CUFKernelDoConstruct::StarOrExpr> &grid =
2816 std::get<1>(dir.t);
2817 const std::list<Fortran::parser::CUFKernelDoConstruct::StarOrExpr> &block =
2818 std::get<2>(dir.t);
2819 const std::optional<Fortran::parser::ScalarIntExpr> &stream =
2820 std::get<3>(dir.t);
2821 const std::list<Fortran::parser::CUFReduction> &cufreds =
2822 std::get<4>(dir.t);
2823
2824 llvm::SmallVector<mlir::Value> reduceOperands;
2825 llvm::SmallVector<mlir::Attribute> reduceAttrs;
2826
2827 for (const Fortran::parser::CUFReduction &cufred : cufreds) {
2828 fir::ReduceOperationEnum redOpEnum = getReduceOperationEnum(
2829 std::get<Fortran::parser::ReductionOperator>(cufred.t));
2830 const std::list<Fortran::parser::Scalar<Fortran::parser::Variable>>
2831 &scalarvars = std::get<1>(cufred.t);
2832 for (const Fortran::parser::Scalar<Fortran::parser::Variable> &scalarvar :
2833 scalarvars) {
2834 auto reduce_attr =
2835 fir::ReduceAttr::get(builder->getContext(), redOpEnum);
2836 reduceAttrs.push_back(reduce_attr);
2837 const Fortran::parser::Variable &var = scalarvar.thing;
2838 if (const auto *iDesignator = std::get_if<
2839 Fortran::common::Indirection<Fortran::parser::Designator>>(
2840 &var.u)) {
2841 const Fortran::parser::Designator &designator = iDesignator->value();
2842 if (const auto *name =
2843 Fortran::semantics::getDesignatorNameIfDataRef(designator)) {
2844 auto val = getSymbolAddress(*name->symbol);
2845 reduceOperands.push_back(val);
2846 }
2847 }
2848 }
2849 }
2850
2851 auto isOnlyStars =
2852 [&](const std::list<Fortran::parser::CUFKernelDoConstruct::StarOrExpr>
2853 &list) -> bool {
2854 for (const Fortran::parser::CUFKernelDoConstruct::StarOrExpr &expr :
2855 list) {
2856 if (expr.v)
2857 return false;
2858 }
2859 return true;
2860 };
2861
2862 mlir::Value zero =
2863 builder->createIntegerConstant(loc, builder->getI32Type(), 0);
2864
2865 llvm::SmallVector<mlir::Value> gridValues;
2866 if (!isOnlyStars(grid)) {
2867 for (const Fortran::parser::CUFKernelDoConstruct::StarOrExpr &expr :
2868 grid) {
2869 if (expr.v) {
2870 gridValues.push_back(fir::getBase(
2871 genExprValue(*Fortran::semantics::GetExpr(*expr.v), stmtCtx)));
2872 } else {
2873 gridValues.push_back(zero);
2874 }
2875 }
2876 }
2877 llvm::SmallVector<mlir::Value> blockValues;
2878 if (!isOnlyStars(block)) {
2879 for (const Fortran::parser::CUFKernelDoConstruct::StarOrExpr &expr :
2880 block) {
2881 if (expr.v) {
2882 blockValues.push_back(fir::getBase(
2883 genExprValue(*Fortran::semantics::GetExpr(*expr.v), stmtCtx)));
2884 } else {
2885 blockValues.push_back(zero);
2886 }
2887 }
2888 }
2889 mlir::Value streamValue;
2890 if (stream)
2891 streamValue = builder->createConvert(
2892 loc, builder->getI32Type(),
2893 fir::getBase(
2894 genExprValue(*Fortran::semantics::GetExpr(*stream), stmtCtx)));
2895
2896 const auto &outerDoConstruct =
2897 std::get<std::optional<Fortran::parser::DoConstruct>>(kernel.t);
2898
2899 llvm::SmallVector<mlir::Location> locs;
2900 locs.push_back(loc);
2901 llvm::SmallVector<mlir::Value> lbs, ubs, steps;
2902
2903 mlir::Type idxTy = builder->getIndexType();
2904
2905 llvm::SmallVector<mlir::Type> ivTypes;
2906 llvm::SmallVector<mlir::Location> ivLocs;
2907 llvm::SmallVector<mlir::Value> ivValues;
2908 Fortran::lower::pft::Evaluation *loopEval =
2909 &getEval().getFirstNestedEvaluation();
2910 for (unsigned i = 0; i < nestedLoops; ++i) {
2911 const Fortran::parser::LoopControl *loopControl;
2912 mlir::Location crtLoc = loc;
2913 if (i == 0) {
2914 loopControl = &*outerDoConstruct->GetLoopControl();
2915 crtLoc =
2916 genLocation(Fortran::parser::FindSourceLocation(outerDoConstruct));
2917 } else {
2918 auto *doCons = loopEval->getIf<Fortran::parser::DoConstruct>();
2919 assert(doCons && "expect do construct");
2920 loopControl = &*doCons->GetLoopControl();
2921 crtLoc = genLocation(Fortran::parser::FindSourceLocation(*doCons));
2922 }
2923
2924 locs.push_back(crtLoc);
2925
2926 const Fortran::parser::LoopControl::Bounds *bounds =
2927 std::get_if<Fortran::parser::LoopControl::Bounds>(&loopControl->u);
2928 assert(bounds && "Expected bounds on the loop construct");
2929
2930 Fortran::semantics::Symbol &ivSym =
2931 bounds->name.thing.symbol->GetUltimate();
2932 ivValues.push_back(getSymbolAddress(ivSym));
2933
2934 lbs.push_back(builder->createConvert(
2935 crtLoc, idxTy,
2936 fir::getBase(genExprValue(*Fortran::semantics::GetExpr(bounds->lower),
2937 stmtCtx))));
2938 ubs.push_back(builder->createConvert(
2939 crtLoc, idxTy,
2940 fir::getBase(genExprValue(*Fortran::semantics::GetExpr(bounds->upper),
2941 stmtCtx))));
2942 if (bounds->step)
2943 steps.push_back(fir::getBase(
2944 genExprValue(*Fortran::semantics::GetExpr(bounds->step), stmtCtx)));
2945 else // If `step` is not present, assume it is `1`.
2946 steps.push_back(builder->createIntegerConstant(loc, idxTy, 1));
2947
2948 ivTypes.push_back(idxTy);
2949 ivLocs.push_back(crtLoc);
2950 if (i < nestedLoops - 1)
2951 loopEval = &*std::next(loopEval->getNestedEvaluations().begin());
2952 }
2953
2954 auto op = builder->create<cuf::KernelOp>(
2955 loc, gridValues, blockValues, streamValue, lbs, ubs, steps, n,
2956 mlir::ValueRange(reduceOperands), builder->getArrayAttr(reduceAttrs));
2957 builder->createBlock(&op.getRegion(), op.getRegion().end(), ivTypes,
2958 ivLocs);
2959 mlir::Block &b = op.getRegion().back();
2960 builder->setInsertionPointToStart(&b);
2961
2962 for (auto [arg, value] : llvm::zip(
2963 op.getLoopRegions().front()->front().getArguments(), ivValues)) {
2964 mlir::Value convArg =
2965 builder->createConvert(loc, fir::unwrapRefType(value.getType()), arg);
2966 builder->create<fir::StoreOp>(loc, convArg, value);
2967 }
2968
2969 Fortran::lower::pft::Evaluation *crtEval = &getEval();
2970 if (crtEval->lowerAsStructured()) {
2971 crtEval = &crtEval->getFirstNestedEvaluation();
2972 for (int64_t i = 1; i < nestedLoops; i++)
2973 crtEval = &*std::next(crtEval->getNestedEvaluations().begin());
2974 }
2975
2976 // Generate loop body
2977 for (Fortran::lower::pft::Evaluation &e : crtEval->getNestedEvaluations())
2978 genFIR(e);
2979
2980 builder->create<fir::FirEndOp>(loc);
2981 builder->setInsertionPointAfter(op);
2982 localSymbols.popScope();
2983 }
2984
2985 void genFIR(const Fortran::parser::OpenMPConstruct &omp) {
2986 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
2987 genOpenMPConstruct(*this, localSymbols, bridge.getSemanticsContext(),
2988 getEval(), omp);
2989 builder->restoreInsertionPoint(insertPt);
2990
2991 // Register if a target region was found
2992 ompDeviceCodeFound =
2993 ompDeviceCodeFound || Fortran::lower::isOpenMPTargetConstruct(omp);
2994 }
2995
2996 void genFIR(const Fortran::parser::OpenMPDeclarativeConstruct &ompDecl) {
2997 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint();
2998 // Register if a declare target construct intended for a target device was
2999 // found
3000 ompDeviceCodeFound =
3001 ompDeviceCodeFound ||
3002 Fortran::lower::isOpenMPDeviceDeclareTarget(
3003 *this, bridge.getSemanticsContext(), getEval(), ompDecl);
3004 Fortran::lower::gatherOpenMPDeferredDeclareTargets(
3005 *this, bridge.getSemanticsContext(), getEval(), ompDecl,
3006 ompDeferredDeclareTarget);
3007 genOpenMPDeclarativeConstruct(
3008 *this, localSymbols, bridge.getSemanticsContext(), getEval(), ompDecl);
3009 builder->restoreInsertionPoint(insertPt);
3010 }
3011
3012 /// Generate FIR for a SELECT CASE statement.
3013 /// The selector may have CHARACTER, INTEGER, or LOGICAL type.
3014 void genFIR(const Fortran::parser::SelectCaseStmt &stmt) {
3015 Fortran::lower::pft::Evaluation &eval = getEval();
3016 Fortran::lower::pft::Evaluation *parentConstruct = eval.parentConstruct;
3017 assert(!activeConstructStack.empty() &&
3018 &activeConstructStack.back().eval == parentConstruct &&
3019 "select case construct is not active");
3020 Fortran::lower::StatementContext &stmtCtx =
3021 activeConstructStack.back().stmtCtx;
3022 const Fortran::lower::SomeExpr *expr = Fortran::semantics::GetExpr(
3023 std::get<Fortran::parser::Scalar<Fortran::parser::Expr>>(stmt.t));
3024 bool isCharSelector = isCharacterCategory(expr->GetType()->category());
3025 bool isLogicalSelector = isLogicalCategory(expr->GetType()->category());
3026 mlir::MLIRContext *context = builder->getContext();
3027 mlir::Location loc = toLocation();
3028 auto charValue = [&](const Fortran::lower::SomeExpr *expr) {
3029 fir::ExtendedValue exv = genExprAddr(*expr, stmtCtx, &loc);
3030 return exv.match(
3031 [&](const fir::CharBoxValue &cbv) {
3032 return fir::factory::CharacterExprHelper{*builder, loc}
3033 .createEmboxChar(cbv.getAddr(), cbv.getLen());
3034 },
3035 [&](auto) {
3036 fir::emitFatalError(loc, "not a character");
3037 return mlir::Value{};
3038 });
3039 };
3040 mlir::Value selector;
3041 if (isCharSelector) {
3042 selector = charValue(expr);
3043 } else {
3044 selector = createFIRExpr(loc, expr, stmtCtx);
3045 if (isLogicalSelector)
3046 selector = builder->createConvert(loc, builder->getI1Type(), selector);
3047 }
3048 mlir::Type selectType = selector.getType();
3049 llvm::SmallVector<mlir::Attribute> attrList;
3050 llvm::SmallVector<mlir::Value> valueList;
3051 llvm::SmallVector<mlir::Block *> blockList;
3052 mlir::Block *defaultBlock = parentConstruct->constructExit->block;
3053 using CaseValue = Fortran::parser::Scalar<Fortran::parser::ConstantExpr>;
3054 auto addValue = [&](const CaseValue &caseValue) {
3055 const Fortran::lower::SomeExpr *expr =
3056 Fortran::semantics::GetExpr(caseValue.thing);
3057 if (isCharSelector)
3058 valueList.push_back(charValue(expr));
3059 else if (isLogicalSelector)
3060 valueList.push_back(builder->createConvert(
3061 loc, selectType, createFIRExpr(toLocation(), expr, stmtCtx)));
3062 else
3063 valueList.push_back(builder->createIntegerConstant(
3064 loc, selectType, *Fortran::evaluate::ToInt64(*expr)));
3065 };
3066 for (Fortran::lower::pft::Evaluation *e = eval.controlSuccessor; e;
3067 e = e->controlSuccessor) {
3068 const auto &caseStmt = e->getIf<Fortran::parser::CaseStmt>();
3069 assert(e->block && "missing CaseStmt block");
3070 const auto &caseSelector =
3071 std::get<Fortran::parser::CaseSelector>(caseStmt->t);
3072 const auto *caseValueRangeList =
3073 std::get_if<std::list<Fortran::parser::CaseValueRange>>(
3074 &caseSelector.u);
3075 if (!caseValueRangeList) {
3076 defaultBlock = e->block;
3077 continue;
3078 }
3079 for (const Fortran::parser::CaseValueRange &caseValueRange :
3080 *caseValueRangeList) {
3081 blockList.push_back(e->block);
3082 if (const auto *caseValue = std::get_if<CaseValue>(&caseValueRange.u)) {
3083 attrList.push_back(fir::PointIntervalAttr::get(context));
3084 addValue(*caseValue);
3085 continue;
3086 }
3087 const auto &caseRange =
3088 std::get<Fortran::parser::CaseValueRange::Range>(caseValueRange.u);
3089 if (caseRange.lower && caseRange.upper) {
3090 attrList.push_back(fir::ClosedIntervalAttr::get(context));
3091 addValue(*caseRange.lower);
3092 addValue(*caseRange.upper);
3093 } else if (caseRange.lower) {
3094 attrList.push_back(fir::LowerBoundAttr::get(context));
3095 addValue(*caseRange.lower);
3096 } else {
3097 attrList.push_back(fir::UpperBoundAttr::get(context));
3098 addValue(*caseRange.upper);
3099 }
3100 }
3101 }
3102 // Skip a logical default block that can never be referenced.
3103 if (isLogicalSelector && attrList.size() == 2)
3104 defaultBlock = parentConstruct->constructExit->block;
3105 attrList.push_back(mlir::UnitAttr::get(context));
3106 blockList.push_back(defaultBlock);
3107
3108 // Generate a fir::SelectCaseOp. Explicit branch code is better for the
3109 // LOGICAL type. The CHARACTER type does not have downstream SelectOp
3110 // support. The -no-structured-fir option can be used to force generation
3111 // of INTEGER type branch code.
3112 if (!isLogicalSelector && !isCharSelector &&
3113 !getEval().forceAsUnstructured()) {
3114 // The selector is in an ssa register. Any temps that may have been
3115 // generated while evaluating it can be cleaned up now.
3116 stmtCtx.finalizeAndReset();
3117 builder->create<fir::SelectCaseOp>(loc, selector, attrList, valueList,
3118 blockList);
3119 return;
3120 }
3121
3122 // Generate a sequence of case value comparisons and branches.
3123 auto caseValue = valueList.begin();
3124 auto caseBlock = blockList.begin();
3125 for (mlir::Attribute attr : attrList) {
3126 if (mlir::isa<mlir::UnitAttr>(attr)) {
3127 genBranch(*caseBlock++);
3128 break;
3129 }
3130 auto genCond = [&](mlir::Value rhs,
3131 mlir::arith::CmpIPredicate pred) -> mlir::Value {
3132 if (!isCharSelector)
3133 return builder->create<mlir::arith::CmpIOp>(loc, pred, selector, rhs);
3134 fir::factory::CharacterExprHelper charHelper{*builder, loc};
3135 std::pair<mlir::Value, mlir::Value> lhsVal =
3136 charHelper.createUnboxChar(selector);
3137 std::pair<mlir::Value, mlir::Value> rhsVal =
3138 charHelper.createUnboxChar(rhs);
3139 return fir::runtime::genCharCompare(*builder, loc, pred, lhsVal.first,
3140 lhsVal.second, rhsVal.first,
3141 rhsVal.second);
3142 };
3143 mlir::Block *newBlock = insertBlock(*caseBlock);
3144 if (mlir::isa<fir::ClosedIntervalAttr>(attr)) {
3145 mlir::Block *newBlock2 = insertBlock(*caseBlock);
3146 mlir::Value cond =
3147 genCond(*caseValue++, mlir::arith::CmpIPredicate::sge);
3148 genConditionalBranch(cond, newBlock, newBlock2);
3149 builder->setInsertionPointToEnd(newBlock);
3150 mlir::Value cond2 =
3151 genCond(*caseValue++, mlir::arith::CmpIPredicate::sle);
3152 genConditionalBranch(cond2, *caseBlock++, newBlock2);
3153 builder->setInsertionPointToEnd(newBlock2);
3154 continue;
3155 }
3156 mlir::arith::CmpIPredicate pred;
3157 if (mlir::isa<fir::PointIntervalAttr>(attr)) {
3158 pred = mlir::arith::CmpIPredicate::eq;
3159 } else if (mlir::isa<fir::LowerBoundAttr>(attr)) {
3160 pred = mlir::arith::CmpIPredicate::sge;
3161 } else {
3162 assert(mlir::isa<fir::UpperBoundAttr>(attr) && "unexpected predicate");
3163 pred = mlir::arith::CmpIPredicate::sle;
3164 }
3165 mlir::Value cond = genCond(*caseValue++, pred);
3166 genConditionalBranch(cond, *caseBlock++, newBlock);
3167 builder->setInsertionPointToEnd(newBlock);
3168 }
3169 assert(caseValue == valueList.end() && caseBlock == blockList.end() &&
3170 "select case list mismatch");
3171 }
3172
3173 fir::ExtendedValue
3174 genAssociateSelector(const Fortran::lower::SomeExpr &selector,
3175 Fortran::lower::StatementContext &stmtCtx) {
3176 if (lowerToHighLevelFIR())
3177 return genExprAddr(selector, stmtCtx);
3178 return Fortran::lower::isArraySectionWithoutVectorSubscript(selector)
3179 ? Fortran::lower::createSomeArrayBox(*this, selector,
3180 localSymbols, stmtCtx)
3181 : genExprAddr(selector, stmtCtx);
3182 }
3183
3184 void genFIR(const Fortran::parser::AssociateConstruct &) {
3185 Fortran::lower::pft::Evaluation &eval = getEval();
3186 Fortran::lower::StatementContext stmtCtx;
3187 pushActiveConstruct(eval, stmtCtx);
3188 for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) {
3189 setCurrentPosition(e.position);
3190 if (auto *stmt = e.getIf<Fortran::parser::AssociateStmt>()) {
3191 if (eval.lowerAsUnstructured())
3192 maybeStartBlock(e.block);
3193 localSymbols.pushScope();
3194 for (const Fortran::parser::Association &assoc :
3195 std::get<std::list<Fortran::parser::Association>>(stmt->t)) {
3196 Fortran::semantics::Symbol &sym =
3197 *std::get<Fortran::parser::Name>(assoc.t).symbol;
3198 const Fortran::lower::SomeExpr &selector =
3199 *sym.get<Fortran::semantics::AssocEntityDetails>().expr();
3200 addSymbol(sym, genAssociateSelector(selector, stmtCtx));
3201 }
3202 } else if (e.getIf<Fortran::parser::EndAssociateStmt>()) {
3203 if (eval.lowerAsUnstructured())
3204 maybeStartBlock(e.block);
3205 localSymbols.popScope();
3206 } else {
3207 genFIR(e);
3208 }
3209 }
3210 popActiveConstruct();
3211 }
3212
3213 void genFIR(const Fortran::parser::BlockConstruct &blockConstruct) {
3214 Fortran::lower::pft::Evaluation &eval = getEval();
3215 Fortran::lower::StatementContext stmtCtx;
3216 pushActiveConstruct(eval, stmtCtx);
3217 for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) {
3218 setCurrentPosition(e.position);
3219 if (e.getIf<Fortran::parser::BlockStmt>()) {
3220 if (eval.lowerAsUnstructured())
3221 maybeStartBlock(e.block);
3222 const Fortran::parser::CharBlock &endPosition =
3223 eval.getLastNestedEvaluation().position;
3224 localSymbols.pushScope();
3225 mlir::func::FuncOp stackSave = fir::factory::getLlvmStackSave(*builder);
3226 mlir::func::FuncOp stackRestore =
3227 fir::factory::getLlvmStackRestore(*builder);
3228 mlir::Value stackPtr =
3229 builder->create<fir::CallOp>(toLocation(), stackSave).getResult(0);
3230 mlir::Location endLoc = genLocation(endPosition);
3231 stmtCtx.attachCleanup([=]() {
3232 builder->create<fir::CallOp>(endLoc, stackRestore, stackPtr);
3233 });
3234 Fortran::semantics::Scope &scope =
3235 bridge.getSemanticsContext().FindScope(endPosition);
3236 scopeBlockIdMap.try_emplace(&scope, ++blockId);
3237 Fortran::lower::AggregateStoreMap storeMap;
3238 for (const Fortran::lower::pft::Variable &var :
3239 Fortran::lower::pft::getScopeVariableList(scope)) {
3240 // Do no instantiate again variables from the block host
3241 // that appears in specification of block variables.
3242 if (!var.hasSymbol() || !lookupSymbol(var.getSymbol()))
3243 instantiateVar(var, storeMap);
3244 }
3245 } else if (e.getIf<Fortran::parser::EndBlockStmt>()) {
3246 if (eval.lowerAsUnstructured())
3247 maybeStartBlock(e.block);
3248 localSymbols.popScope();
3249 } else {
3250 genFIR(e);
3251 }
3252 }
3253 popActiveConstruct();
3254 }
3255
3256 void genFIR(const Fortran::parser::ChangeTeamConstruct &construct) {
3257 TODO(toLocation(), "coarray: ChangeTeamConstruct");
3258 }
3259 void genFIR(const Fortran::parser::ChangeTeamStmt &stmt) {
3260 TODO(toLocation(), "coarray: ChangeTeamStmt");
3261 }
3262 void genFIR(const Fortran::parser::EndChangeTeamStmt &stmt) {
3263 TODO(toLocation(), "coarray: EndChangeTeamStmt");
3264 }
3265
3266 void genFIR(const Fortran::parser::CriticalConstruct &criticalConstruct) {
3267 setCurrentPositionAt(criticalConstruct);
3268 TODO(toLocation(), "coarray: CriticalConstruct");
3269 }
3270 void genFIR(const Fortran::parser::CriticalStmt &) {
3271 TODO(toLocation(), "coarray: CriticalStmt");
3272 }
3273 void genFIR(const Fortran::parser::EndCriticalStmt &) {
3274 TODO(toLocation(), "coarray: EndCriticalStmt");
3275 }
3276
3277 void genFIR(const Fortran::parser::SelectRankConstruct &selectRankConstruct) {
3278 setCurrentPositionAt(selectRankConstruct);
3279 genCaseOrRankConstruct();
3280 }
3281
3282 void genFIR(const Fortran::parser::SelectRankStmt &selectRankStmt) {
3283 // Generate a fir.select_case with the selector rank. The RANK(*) case,
3284 // if any, is handles with a conditional branch before the fir.select_case.
3285 mlir::Type rankType = builder->getIntegerType(8);
3286 mlir::MLIRContext *context = builder->getContext();
3287 mlir::Location loc = toLocation();
3288 // Build block list for fir.select_case, and identify RANK(*) block, if any.
3289 // Default block must be placed last in the fir.select_case block list.
3290 mlir::Block *rankStarBlock = nullptr;
3291 Fortran::lower::pft::Evaluation &eval = getEval();
3292 mlir::Block *defaultBlock = eval.parentConstruct->constructExit->block;
3293 llvm::SmallVector<mlir::Attribute> attrList;
3294 llvm::SmallVector<mlir::Value> valueList;
3295 llvm::SmallVector<mlir::Block *> blockList;
3296 for (Fortran::lower::pft::Evaluation *e = eval.controlSuccessor; e;
3297 e = e->controlSuccessor) {
3298 if (const auto *rankCaseStmt =
3299 e->getIf<Fortran::parser::SelectRankCaseStmt>()) {
3300 const auto &rank = std::get<Fortran::parser::SelectRankCaseStmt::Rank>(
3301 rankCaseStmt->t);
3302 assert(e->block && "missing SelectRankCaseStmt block");
3303 Fortran::common::visit(
3304 Fortran::common::visitors{
3305 [&](const Fortran::parser::ScalarIntConstantExpr &rankExpr) {
3306 blockList.emplace_back(e->block);
3307 attrList.emplace_back(fir::PointIntervalAttr::get(context));
3308 std::optional<std::int64_t> rankCst =
3309 Fortran::evaluate::ToInt64(
3310 Fortran::semantics::GetExpr(rankExpr));
3311 assert(rankCst.has_value() &&
3312 "rank expr must be constant integer");
3313 valueList.emplace_back(
3314 builder->createIntegerConstant(loc, rankType, *rankCst));
3315 },
3316 [&](const Fortran::parser::Star &) {
3317 rankStarBlock = e->block;
3318 },
3319 [&](const Fortran::parser::Default &) {
3320 defaultBlock = e->block;
3321 }},
3322 rank.u);
3323 }
3324 }
3325 attrList.push_back(mlir::UnitAttr::get(context));
3326 blockList.push_back(defaultBlock);
3327
3328 // Lower selector.
3329 assert(!activeConstructStack.empty() && "must be inside construct");
3330 assert(!activeConstructStack.back().selector &&
3331 "selector should not yet be set");
3332 Fortran::lower::StatementContext &stmtCtx =
3333 activeConstructStack.back().stmtCtx;
3334 const Fortran::lower::SomeExpr *selectorExpr = Fortran::common::visit(
3335 [](const auto &x) { return Fortran::semantics::GetExpr(x); },
3336 std::get<Fortran::parser::Selector>(selectRankStmt.t).u);
3337 assert(selectorExpr && "failed to retrieve selector expr");
3338 hlfir::Entity selector = Fortran::lower::convertExprToHLFIR(
3339 loc, *this, *selectorExpr, localSymbols, stmtCtx);
3340 activeConstructStack.back().selector = selector;
3341
3342 // Deal with assumed-size first. They must fall into RANK(*) if present, or
3343 // the default case (F'2023 11.1.10.2.). The selector cannot be an
3344 // assumed-size if it is allocatable or pointer, so the check is skipped.
3345 if (!Fortran::evaluate::IsAllocatableOrPointerObject(*selectorExpr)) {
3346 mlir::Value isAssumedSize = builder->create<fir::IsAssumedSizeOp>(
3347 loc, builder->getI1Type(), selector);
3348 // Create new block to hold the fir.select_case for the non assumed-size
3349 // cases.
3350 mlir::Block *selectCaseBlock = insertBlock(blockList[0]);
3351 mlir::Block *assumedSizeBlock =
3352 rankStarBlock ? rankStarBlock : defaultBlock;
3353 builder->create<mlir::cf::CondBranchOp>(loc, isAssumedSize,
3354 assumedSizeBlock, std::nullopt,
3355 selectCaseBlock, std::nullopt);
3356 startBlock(selectCaseBlock);
3357 }
3358 // Create fir.select_case for the other rank cases.
3359 mlir::Value rank = builder->create<fir::BoxRankOp>(loc, rankType, selector);
3360 stmtCtx.finalizeAndReset();
3361 builder->create<fir::SelectCaseOp>(loc, rank, attrList, valueList,
3362 blockList);
3363 }
3364
3365 // Get associating entity symbol inside case statement scope.
3366 static const Fortran::semantics::Symbol &
3367 getAssociatingEntitySymbol(const Fortran::semantics::Scope &scope) {
3368 const Fortran::semantics::Symbol *assocSym = nullptr;
3369 for (const auto &sym : scope.GetSymbols()) {
3370 if (sym->has<Fortran::semantics::AssocEntityDetails>()) {
3371 assert(!assocSym &&
3372 "expect only one associating entity symbol in this scope");
3373 assocSym = &*sym;
3374 }
3375 }
3376 assert(assocSym && "should contain associating entity symbol");
3377 return *assocSym;
3378 }
3379
3380 void genFIR(const Fortran::parser::SelectRankCaseStmt &stmt) {
3381 assert(!activeConstructStack.empty() &&
3382 "must be inside select rank construct");
3383 // Pop previous associating entity mapping, if any, and push scope for new
3384 // mapping.
3385 if (activeConstructStack.back().pushedScope)
3386 localSymbols.popScope();
3387 localSymbols.pushScope();
3388 activeConstructStack.back().pushedScope = true;
3389 const Fortran::semantics::Symbol &assocEntitySymbol =
3390 getAssociatingEntitySymbol(
3391 bridge.getSemanticsContext().FindScope(getEval().position));
3392 const auto &details =
3393 assocEntitySymbol.get<Fortran::semantics::AssocEntityDetails>();
3394 assert(!activeConstructStack.empty() &&
3395 activeConstructStack.back().selector.has_value() &&
3396 "selector must have been created");
3397 // Get lowered value for the selector.
3398 hlfir::Entity selector = *activeConstructStack.back().selector;
3399 assert(selector.isVariable() && "assumed-rank selector are variables");
3400 // Cook selector mlir::Value according to rank case and map it to
3401 // associating entity symbol.
3402 Fortran::lower::StatementContext stmtCtx;
3403 mlir::Location loc = toLocation();
3404 if (details.IsAssumedRank()) {
3405 fir::ExtendedValue selectorExv = Fortran::lower::translateToExtendedValue(
3406 loc, *builder, selector, stmtCtx);
3407 addSymbol(assocEntitySymbol, selectorExv);
3408 } else if (details.IsAssumedSize()) {
3409 // Create rank-1 assumed-size from descriptor. Assumed-size are contiguous
3410 // so a new entity can be built from scratch using the base address, type
3411 // parameters and dynamic type. The selector cannot be a
3412 // POINTER/ALLOCATBLE as per F'2023 C1160.
3413 fir::ExtendedValue newExv;
3414 llvm::SmallVector assumeSizeExtents{
3415 builder->createMinusOneInteger(loc, builder->getIndexType())};
3416 mlir::Value baseAddr =
3417 hlfir::genVariableRawAddress(loc, *builder, selector);
3418 mlir::Type eleType =
3419 fir::unwrapSequenceType(fir::unwrapRefType(baseAddr.getType()));
3420 mlir::Type rank1Type =
3421 fir::ReferenceType::get(builder->getVarLenSeqTy(eleType, 1));
3422 baseAddr = builder->createConvert(loc, rank1Type, baseAddr);
3423 if (selector.isCharacter()) {
3424 mlir::Value len = hlfir::genCharLength(loc, *builder, selector);
3425 newExv = fir::CharArrayBoxValue{baseAddr, len, assumeSizeExtents};
3426 } else if (selector.isDerivedWithLengthParameters()) {
3427 TODO(loc, "RANK(*) with parameterized derived type selector");
3428 } else if (selector.isPolymorphic()) {
3429 TODO(loc, "RANK(*) with polymorphic selector");
3430 } else {
3431 // Simple intrinsic or derived type.
3432 newExv = fir::ArrayBoxValue{baseAddr, assumeSizeExtents};
3433 }
3434 addSymbol(assocEntitySymbol, newExv);
3435 } else {
3436 int rank = details.rank().value();
3437 auto boxTy =
3438 mlir::cast<fir::BaseBoxType>(fir::unwrapRefType(selector.getType()));
3439 mlir::Type newBoxType = boxTy.getBoxTypeWithNewShape(rank);
3440 if (fir::isa_ref_type(selector.getType()))
3441 newBoxType = fir::ReferenceType::get(newBoxType);
3442 // Give rank info to value via cast, and get rid of the box if not needed
3443 // (simple scalars, contiguous arrays... This is done by
3444 // translateVariableToExtendedValue).
3445 hlfir::Entity rankedBox{
3446 builder->createConvert(loc, newBoxType, selector)};
3447 bool isSimplyContiguous = Fortran::evaluate::IsSimplyContiguous(
3448 assocEntitySymbol, getFoldingContext());
3449 fir::ExtendedValue newExv = Fortran::lower::translateToExtendedValue(
3450 loc, *builder, rankedBox, stmtCtx, isSimplyContiguous);
3451
3452 // Non deferred length parameters of character allocatable/pointer
3453 // MutableBoxValue should be properly set before binding it to a symbol in
3454 // order to get correct assignment semantics.
3455 if (const fir::MutableBoxValue *mutableBox =
3456 newExv.getBoxOf<fir::MutableBoxValue>()) {
3457 if (selector.isCharacter()) {
3458 auto dynamicType =
3459 Fortran::evaluate::DynamicType::From(assocEntitySymbol);
3460 if (!dynamicType.value().HasDeferredTypeParameter()) {
3461 llvm::SmallVector<mlir::Value> lengthParams;
3462 hlfir::genLengthParameters(loc, *builder, selector, lengthParams);
3463 newExv = fir::MutableBoxValue{rankedBox, lengthParams,
3464 mutableBox->getMutableProperties()};
3465 }
3466 }
3467 }
3468 addSymbol(assocEntitySymbol, newExv);
3469 }
3470 // Statements inside rank case are lowered by SelectRankConstruct visit.
3471 }
3472
3473 void genFIR(const Fortran::parser::SelectTypeConstruct &selectTypeConstruct) {
3474 mlir::MLIRContext *context = builder->getContext();
3475 Fortran::lower::StatementContext stmtCtx;
3476 fir::ExtendedValue selector;
3477 llvm::SmallVector<mlir::Attribute> attrList;
3478 llvm::SmallVector<mlir::Block *> blockList;
3479 unsigned typeGuardIdx = 0;
3480 std::size_t defaultAttrPos = std::numeric_limits<size_t>::max();
3481 bool hasLocalScope = false;
3482 llvm::SmallVector<const Fortran::semantics::Scope *> typeCaseScopes;
3483
3484 const auto &typeCaseList =
3485 std::get<std::list<Fortran::parser::SelectTypeConstruct::TypeCase>>(
3486 selectTypeConstruct.t);
3487 for (const auto &typeCase : typeCaseList) {
3488 const auto &stmt =
3489 std::get<Fortran::parser::Statement<Fortran::parser::TypeGuardStmt>>(
3490 typeCase.t);
3491 const Fortran::semantics::Scope &scope =
3492 bridge.getSemanticsContext().FindScope(stmt.source);
3493 typeCaseScopes.push_back(&scope);
3494 }
3495
3496 pushActiveConstruct(getEval(), stmtCtx);
3497 llvm::SmallVector<Fortran::lower::pft::Evaluation *> exits, fallThroughs;
3498 collectFinalEvaluations(getEval(), exits, fallThroughs);
3499 Fortran::lower::pft::Evaluation &constructExit = *getEval().constructExit;
3500
3501 for (Fortran::lower::pft::Evaluation &eval :
3502 getEval().getNestedEvaluations()) {
3503 setCurrentPosition(eval.position);
3504 mlir::Location loc = toLocation();
3505 if (auto *selectTypeStmt =
3506 eval.getIf<Fortran::parser::SelectTypeStmt>()) {
3507 // A genFIR(SelectTypeStmt) call would have unwanted side effects.
3508 maybeStartBlock(eval.block);
3509 // Retrieve the selector
3510 const auto &s = std::get<Fortran::parser::Selector>(selectTypeStmt->t);
3511 if (const auto *v = std::get_if<Fortran::parser::Variable>(&s.u))
3512 selector = genExprBox(loc, *Fortran::semantics::GetExpr(*v), stmtCtx);
3513 else if (const auto *e = std::get_if<Fortran::parser::Expr>(&s.u))
3514 selector = genExprBox(loc, *Fortran::semantics::GetExpr(*e), stmtCtx);
3515
3516 // Going through the controlSuccessor first to create the
3517 // fir.select_type operation.
3518 mlir::Block *defaultBlock = eval.parentConstruct->constructExit->block;
3519 for (Fortran::lower::pft::Evaluation *e = eval.controlSuccessor; e;
3520 e = e->controlSuccessor) {
3521 const auto &typeGuardStmt =
3522 e->getIf<Fortran::parser::TypeGuardStmt>();
3523 const auto &guard =
3524 std::get<Fortran::parser::TypeGuardStmt::Guard>(typeGuardStmt->t);
3525 assert(e->block && "missing TypeGuardStmt block");
3526 // CLASS DEFAULT
3527 if (std::holds_alternative<Fortran::parser::Default>(guard.u)) {
3528 defaultBlock = e->block;
3529 // Keep track of the actual position of the CLASS DEFAULT type guard
3530 // in the SELECT TYPE construct.
3531 defaultAttrPos = attrList.size();
3532 continue;
3533 }
3534
3535 blockList.push_back(e->block);
3536 if (const auto *typeSpec =
3537 std::get_if<Fortran::parser::TypeSpec>(&guard.u)) {
3538 // TYPE IS
3539 mlir::Type ty;
3540 if (std::holds_alternative<Fortran::parser::IntrinsicTypeSpec>(
3541 typeSpec->u)) {
3542 const Fortran::semantics::IntrinsicTypeSpec *intrinsic =
3543 typeSpec->declTypeSpec->AsIntrinsic();
3544 int kind =
3545 Fortran::evaluate::ToInt64(intrinsic->kind()).value_or(kind);
3546 llvm::SmallVector<Fortran::lower::LenParameterTy> params;
3547 ty = genType(intrinsic->category(), kind, params);
3548 } else {
3549 const Fortran::semantics::DerivedTypeSpec *derived =
3550 typeSpec->declTypeSpec->AsDerived();
3551 ty = genType(*derived);
3552 }
3553 attrList.push_back(fir::ExactTypeAttr::get(ty));
3554 } else if (const auto *derived =
3555 std::get_if<Fortran::parser::DerivedTypeSpec>(
3556 &guard.u)) {
3557 // CLASS IS
3558 assert(derived->derivedTypeSpec && "derived type spec is null");
3559 mlir::Type ty = genType(*(derived->derivedTypeSpec));
3560 attrList.push_back(fir::SubclassAttr::get(ty));
3561 }
3562 }
3563 attrList.push_back(mlir::UnitAttr::get(context));
3564 blockList.push_back(defaultBlock);
3565 builder->create<fir::SelectTypeOp>(loc, fir::getBase(selector),
3566 attrList, blockList);
3567
3568 // If the actual position of CLASS DEFAULT type guard is not the last
3569 // one, it needs to be put back at its correct position for the rest of
3570 // the processing. TypeGuardStmt are processed in the same order they
3571 // appear in the Fortran code.
3572 if (defaultAttrPos < attrList.size() - 1) {
3573 auto attrIt = attrList.begin();
3574 attrIt = attrIt + defaultAttrPos;
3575 auto blockIt = blockList.begin();
3576 blockIt = blockIt + defaultAttrPos;
3577 attrList.insert(attrIt, mlir::UnitAttr::get(context));
3578 blockList.insert(blockIt, defaultBlock);
3579 attrList.pop_back();
3580 blockList.pop_back();
3581 }
3582 } else if (auto *typeGuardStmt =
3583 eval.getIf<Fortran::parser::TypeGuardStmt>()) {
3584 // Map the type guard local symbol for the selector to a more precise
3585 // typed entity in the TypeGuardStmt when necessary.
3586 genFIR(eval);
3587 const auto &guard =
3588 std::get<Fortran::parser::TypeGuardStmt::Guard>(typeGuardStmt->t);
3589 if (hasLocalScope)
3590 localSymbols.popScope();
3591 localSymbols.pushScope();
3592 hasLocalScope = true;
3593 assert(attrList.size() >= typeGuardIdx &&
3594 "TypeGuard attribute missing");
3595 mlir::Attribute typeGuardAttr = attrList[typeGuardIdx];
3596 mlir::Block *typeGuardBlock = blockList[typeGuardIdx];
3597 mlir::OpBuilder::InsertPoint crtInsPt = builder->saveInsertionPoint();
3598 builder->setInsertionPointToStart(typeGuardBlock);
3599
3600 auto addAssocEntitySymbol = [&](fir::ExtendedValue exv) {
3601 for (auto &symbol : typeCaseScopes[typeGuardIdx]->GetSymbols()) {
3602 if (symbol->GetUltimate()
3603 .detailsIf<Fortran::semantics::AssocEntityDetails>()) {
3604 addSymbol(symbol, exv);
3605 break;
3606 }
3607 }
3608 };
3609
3610 mlir::Type baseTy = fir::getBase(selector).getType();
3611 bool isPointer = fir::isPointerType(baseTy);
3612 bool isAllocatable = fir::isAllocatableType(baseTy);
3613 bool isArray =
3614 mlir::isa<fir::SequenceType>(fir::dyn_cast_ptrOrBoxEleTy(baseTy));
3615 const fir::BoxValue *selectorBox = selector.getBoxOf<fir::BoxValue>();
3616 if (std::holds_alternative<Fortran::parser::Default>(guard.u)) {
3617 // CLASS DEFAULT
3618 addAssocEntitySymbol(selector);
3619 } else if (const auto *typeSpec =
3620 std::get_if<Fortran::parser::TypeSpec>(&guard.u)) {
3621 // TYPE IS
3622 fir::ExactTypeAttr attr =
3623 mlir::dyn_cast<fir::ExactTypeAttr>(typeGuardAttr);
3624 mlir::Value exactValue;
3625 mlir::Type addrTy = attr.getType();
3626 if (isArray) {
3627 auto seqTy = mlir::dyn_cast<fir::SequenceType>(
3628 fir::dyn_cast_ptrOrBoxEleTy(baseTy));
3629 addrTy = fir::SequenceType::get(seqTy.getShape(), attr.getType());
3630 }
3631 if (isPointer)
3632 addrTy = fir::PointerType::get(addrTy);
3633 if (isAllocatable)
3634 addrTy = fir::HeapType::get(addrTy);
3635 if (std::holds_alternative<Fortran::parser::IntrinsicTypeSpec>(
3636 typeSpec->u)) {
3637 mlir::Type refTy = fir::ReferenceType::get(addrTy);
3638 if (isPointer || isAllocatable)
3639 refTy = addrTy;
3640 exactValue = builder->create<fir::BoxAddrOp>(
3641 loc, refTy, fir::getBase(selector));
3642 const Fortran::semantics::IntrinsicTypeSpec *intrinsic =
3643 typeSpec->declTypeSpec->AsIntrinsic();
3644 if (isArray) {
3645 mlir::Value exact = builder->create<fir::ConvertOp>(
3646 loc, fir::BoxType::get(addrTy), fir::getBase(selector));
3647 addAssocEntitySymbol(selectorBox->clone(exact));
3648 } else if (intrinsic->category() ==
3649 Fortran::common::TypeCategory::Character) {
3650 auto charTy = mlir::dyn_cast<fir::CharacterType>(attr.getType());
3651 mlir::Value charLen =
3652 fir::factory::CharacterExprHelper(*builder, loc)
3653 .readLengthFromBox(fir::getBase(selector), charTy);
3654 addAssocEntitySymbol(fir::CharBoxValue(exactValue, charLen));
3655 } else {
3656 addAssocEntitySymbol(exactValue);
3657 }
3658 } else if (std::holds_alternative<Fortran::parser::DerivedTypeSpec>(
3659 typeSpec->u)) {
3660 exactValue = builder->create<fir::ConvertOp>(
3661 loc, fir::BoxType::get(addrTy), fir::getBase(selector));
3662 addAssocEntitySymbol(selectorBox->clone(exactValue));
3663 }
3664 } else if (std::holds_alternative<Fortran::parser::DerivedTypeSpec>(
3665 guard.u)) {
3666 // CLASS IS
3667 fir::SubclassAttr attr =
3668 mlir::dyn_cast<fir::SubclassAttr>(typeGuardAttr);
3669 mlir::Type addrTy = attr.getType();
3670 if (isArray) {
3671 auto seqTy = mlir::dyn_cast<fir::SequenceType>(
3672 fir::dyn_cast_ptrOrBoxEleTy(baseTy));
3673 addrTy = fir::SequenceType::get(seqTy.getShape(), attr.getType());
3674 }
3675 if (isPointer)
3676 addrTy = fir::PointerType::get(addrTy);
3677 if (isAllocatable)
3678 addrTy = fir::HeapType::get(addrTy);
3679 mlir::Type classTy = fir::ClassType::get(addrTy);
3680 if (classTy == baseTy) {
3681 addAssocEntitySymbol(selector);
3682 } else {
3683 mlir::Value derived = builder->create<fir::ConvertOp>(
3684 loc, classTy, fir::getBase(selector));
3685 addAssocEntitySymbol(selectorBox->clone(derived));
3686 }
3687 }
3688 builder->restoreInsertionPoint(crtInsPt);
3689 ++typeGuardIdx;
3690 } else if (eval.getIf<Fortran::parser::EndSelectStmt>()) {
3691 maybeStartBlock(eval.block);
3692 if (hasLocalScope)
3693 localSymbols.popScope();
3694 } else {
3695 genFIR(eval);
3696 }
3697 if (blockIsUnterminated()) {
3698 if (llvm::is_contained(exits, &eval))
3699 genConstructExitBranch(constructExit);
3700 else if (llvm::is_contained(fallThroughs, &eval))
3701 genBranch(eval.lexicalSuccessor->block);
3702 }
3703 }
3704 popActiveConstruct();
3705 }
3706
3707 //===--------------------------------------------------------------------===//
3708 // IO statements (see io.h)
3709 //===--------------------------------------------------------------------===//
3710
3711 void genFIR(const Fortran::parser::BackspaceStmt &stmt) {
3712 mlir::Value iostat = genBackspaceStatement(*this, stmt);
3713 genIoConditionBranches(getEval(), stmt.v, iostat);
3714 }
3715 void genFIR(const Fortran::parser::CloseStmt &stmt) {
3716 mlir::Value iostat = genCloseStatement(*this, stmt);
3717 genIoConditionBranches(getEval(), stmt.v, iostat);
3718 }
3719 void genFIR(const Fortran::parser::EndfileStmt &stmt) {
3720 mlir::Value iostat = genEndfileStatement(*this, stmt);
3721 genIoConditionBranches(getEval(), stmt.v, iostat);
3722 }
3723 void genFIR(const Fortran::parser::FlushStmt &stmt) {
3724 mlir::Value iostat = genFlushStatement(*this, stmt);
3725 genIoConditionBranches(getEval(), stmt.v, iostat);
3726 }
3727 void genFIR(const Fortran::parser::InquireStmt &stmt) {
3728 mlir::Value iostat = genInquireStatement(*this, stmt);
3729 if (const auto *specs =
3730 std::get_if<std::list<Fortran::parser::InquireSpec>>(&stmt.u))
3731 genIoConditionBranches(getEval(), *specs, iostat);
3732 }
3733 void genFIR(const Fortran::parser::OpenStmt &stmt) {
3734 mlir::Value iostat = genOpenStatement(*this, stmt);
3735 genIoConditionBranches(getEval(), stmt.v, iostat);
3736 }
3737 void genFIR(const Fortran::parser::PrintStmt &stmt) {
3738 genPrintStatement(*this, stmt);
3739 }
3740 void genFIR(const Fortran::parser::ReadStmt &stmt) {
3741 mlir::Value iostat = genReadStatement(*this, stmt);
3742 genIoConditionBranches(getEval(), stmt.controls, iostat);
3743 }
3744 void genFIR(const Fortran::parser::RewindStmt &stmt) {
3745 mlir::Value iostat = genRewindStatement(*this, stmt);
3746 genIoConditionBranches(getEval(), stmt.v, iostat);
3747 }
3748 void genFIR(const Fortran::parser::WaitStmt &stmt) {
3749 mlir::Value iostat = genWaitStatement(*this, stmt);
3750 genIoConditionBranches(getEval(), stmt.v, iostat);
3751 }
3752 void genFIR(const Fortran::parser::WriteStmt &stmt) {
3753 mlir::Value iostat = genWriteStatement(*this, stmt);
3754 genIoConditionBranches(getEval(), stmt.controls, iostat);
3755 }
3756
3757 template <typename A>
3758 void genIoConditionBranches(Fortran::lower::pft::Evaluation &eval,
3759 const A &specList, mlir::Value iostat) {
3760 if (!iostat)
3761 return;
3762
3763 Fortran::parser::Label endLabel{};
3764 Fortran::parser::Label eorLabel{};
3765 Fortran::parser::Label errLabel{};
3766 bool hasIostat{};
3767 for (const auto &spec : specList) {
3768 Fortran::common::visit(
3769 Fortran::common::visitors{
3770 [&](const Fortran::parser::EndLabel &label) {
3771 endLabel = label.v;
3772 },
3773 [&](const Fortran::parser::EorLabel &label) {
3774 eorLabel = label.v;
3775 },
3776 [&](const Fortran::parser::ErrLabel &label) {
3777 errLabel = label.v;
3778 },
3779 [&](const Fortran::parser::StatVariable &) { hasIostat = true; },
3780 [](const auto &) {}},
3781 spec.u);
3782 }
3783 if (!endLabel && !eorLabel && !errLabel)
3784 return;
3785
3786 // An ERR specifier branch is taken on any positive error value rather than
3787 // some single specific value. If ERR and IOSTAT specifiers are given and
3788 // END and EOR specifiers are allowed, the latter two specifiers must have
3789 // explicit branch targets to allow the ERR branch to be implemented as a
3790 // default/else target. A label=0 target for an absent END or EOR specifier
3791 // indicates that these specifiers have a fallthrough target. END and EOR
3792 // specifiers may appear on READ and WAIT statements.
3793 bool allSpecifiersRequired = errLabel && hasIostat &&
3794 (eval.isA<Fortran::parser::ReadStmt>() ||
3795 eval.isA<Fortran::parser::WaitStmt>());
3796 mlir::Value selector =
3797 builder->createConvert(toLocation(), builder->getIndexType(), iostat);
3798 llvm::SmallVector<int64_t> valueList;
3799 llvm::SmallVector<Fortran::parser::Label> labelList;
3800 if (eorLabel || allSpecifiersRequired) {
3801 valueList.push_back(Fortran::runtime::io::IostatEor);
3802 labelList.push_back(eorLabel ? eorLabel : 0);
3803 }
3804 if (endLabel || allSpecifiersRequired) {
3805 valueList.push_back(Fortran::runtime::io::IostatEnd);
3806 labelList.push_back(endLabel ? endLabel : 0);
3807 }
3808 if (errLabel) {
3809 // Must be last. Value 0 is interpreted as any positive value, or
3810 // equivalently as any value other than 0, IostatEor, or IostatEnd.
3811 valueList.push_back(0);
3812 labelList.push_back(errLabel);
3813 }
3814 genMultiwayBranch(selector, valueList, labelList, eval.nonNopSuccessor());
3815 }
3816
3817 //===--------------------------------------------------------------------===//
3818 // Memory allocation and deallocation
3819 //===--------------------------------------------------------------------===//
3820
3821 void genFIR(const Fortran::parser::AllocateStmt &stmt) {
3822 Fortran::lower::genAllocateStmt(*this, stmt, toLocation());
3823 }
3824
3825 void genFIR(const Fortran::parser::DeallocateStmt &stmt) {
3826 Fortran::lower::genDeallocateStmt(*this, stmt, toLocation());
3827 }
3828
3829 /// Nullify pointer object list
3830 ///
3831 /// For each pointer object, reset the pointer to a disassociated status.
3832 /// We do this by setting each pointer to null.
3833 void genFIR(const Fortran::parser::NullifyStmt &stmt) {
3834 mlir::Location loc = toLocation();
3835 for (auto &pointerObject : stmt.v) {
3836 const Fortran::lower::SomeExpr *expr =
3837 Fortran::semantics::GetExpr(pointerObject);
3838 assert(expr);
3839 if (Fortran::evaluate::IsProcedurePointer(*expr)) {
3840 Fortran::lower::StatementContext stmtCtx;
3841 hlfir::Entity pptr = Fortran::lower::convertExprToHLFIR(
3842 loc, *this, *expr, localSymbols, stmtCtx);
3843 auto boxTy{
3844 Fortran::lower::getUntypedBoxProcType(builder->getContext())};
3845 hlfir::Entity nullBoxProc(
3846 fir::factory::createNullBoxProc(*builder, loc, boxTy));
3847 builder->createStoreWithConvert(loc, nullBoxProc, pptr);
3848 } else {
3849 fir::MutableBoxValue box = genExprMutableBox(loc, *expr);
3850 fir::factory::disassociateMutableBox(*builder, loc, box);
3851 }
3852 }
3853 }
3854
3855 //===--------------------------------------------------------------------===//
3856
3857 void genFIR(const Fortran::parser::NotifyWaitStmt &stmt) {
3858 genNotifyWaitStatement(*this, stmt);
3859 }
3860
3861 void genFIR(const Fortran::parser::EventPostStmt &stmt) {
3862 genEventPostStatement(*this, stmt);
3863 }
3864
3865 void genFIR(const Fortran::parser::EventWaitStmt &stmt) {
3866 genEventWaitStatement(*this, stmt);
3867 }
3868
3869 void genFIR(const Fortran::parser::FormTeamStmt &stmt) {
3870 genFormTeamStatement(*this, getEval(), stmt);
3871 }
3872
3873 void genFIR(const Fortran::parser::LockStmt &stmt) {
3874 genLockStatement(*this, stmt);
3875 }
3876
3877 fir::ExtendedValue
3878 genInitializerExprValue(const Fortran::lower::SomeExpr &expr,
3879 Fortran::lower::StatementContext &stmtCtx) {
3880 return Fortran::lower::createSomeInitializerExpression(
3881 toLocation(), *this, expr, localSymbols, stmtCtx);
3882 }
3883
3884 /// Return true if the current context is a conditionalized and implied
3885 /// iteration space.
3886 bool implicitIterationSpace() { return !implicitIterSpace.empty(); }
3887
3888 /// Return true if context is currently an explicit iteration space. A scalar
3889 /// assignment expression may be contextually within a user-defined iteration
3890 /// space, transforming it into an array expression.
3891 bool explicitIterationSpace() { return explicitIterSpace.isActive(); }
3892
3893 /// Generate an array assignment.
3894 /// This is an assignment expression with rank > 0. The assignment may or may
3895 /// not be in a WHERE and/or FORALL context.
3896 /// In a FORALL context, the assignment may be a pointer assignment and the \p
3897 /// lbounds and \p ubounds parameters should only be used in such a pointer
3898 /// assignment case. (If both are None then the array assignment cannot be a
3899 /// pointer assignment.)
3900 void genArrayAssignment(
3901 const Fortran::evaluate::Assignment &assign,
3902 Fortran::lower::StatementContext &localStmtCtx,
3903 std::optional<llvm::SmallVector<mlir::Value>> lbounds = std::nullopt,
3904 std::optional<llvm::SmallVector<mlir::Value>> ubounds = std::nullopt) {
3905
3906 Fortran::lower::StatementContext &stmtCtx =
3907 explicitIterationSpace()
3908 ? explicitIterSpace.stmtContext()
3909 : (implicitIterationSpace() ? implicitIterSpace.stmtContext()
3910 : localStmtCtx);
3911 if (Fortran::lower::isWholeAllocatable(assign.lhs)) {
3912 // Assignment to allocatables may require the lhs to be
3913 // deallocated/reallocated. See Fortran 2018 10.2.1.3 p3
3914 Fortran::lower::createAllocatableArrayAssignment(
3915 *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace,
3916 localSymbols, stmtCtx);
3917 return;
3918 }
3919
3920 if (lbounds) {
3921 // Array of POINTER entities, with elemental assignment.
3922 if (!Fortran::lower::isWholePointer(assign.lhs))
3923 fir::emitFatalError(toLocation(), "pointer assignment to non-pointer");
3924
3925 Fortran::lower::createArrayOfPointerAssignment(
3926 *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace,
3927 *lbounds, ubounds, localSymbols, stmtCtx);
3928 return;
3929 }
3930
3931 if (!implicitIterationSpace() && !explicitIterationSpace()) {
3932 // No masks and the iteration space is implied by the array, so create a
3933 // simple array assignment.
3934 Fortran::lower::createSomeArrayAssignment(*this, assign.lhs, assign.rhs,
3935 localSymbols, stmtCtx);
3936 return;
3937 }
3938
3939 // If there is an explicit iteration space, generate an array assignment
3940 // with a user-specified iteration space and possibly with masks. These
3941 // assignments may *appear* to be scalar expressions, but the scalar
3942 // expression is evaluated at all points in the user-defined space much like
3943 // an ordinary array assignment. More specifically, the semantics inside the
3944 // FORALL much more closely resembles that of WHERE than a scalar
3945 // assignment.
3946 // Otherwise, generate a masked array assignment. The iteration space is
3947 // implied by the lhs array expression.
3948 Fortran::lower::createAnyMaskedArrayAssignment(
3949 *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace,
3950 localSymbols, stmtCtx);
3951 }
3952
3953 #if !defined(NDEBUG)
3954 static bool isFuncResultDesignator(const Fortran::lower::SomeExpr &expr) {
3955 const Fortran::semantics::Symbol *sym =
3956 Fortran::evaluate::GetFirstSymbol(expr);
3957 return sym && sym->IsFuncResult();
3958 }
3959 #endif
3960
3961 inline fir::MutableBoxValue
3962 genExprMutableBox(mlir::Location loc,
3963 const Fortran::lower::SomeExpr &expr) override final {
3964 if (lowerToHighLevelFIR())
3965 return Fortran::lower::convertExprToMutableBox(loc, *this, expr,
3966 localSymbols);
3967 return Fortran::lower::createMutableBox(loc, *this, expr, localSymbols);
3968 }
3969
3970 // Create the [newRank] array with the lower bounds to be passed to the
3971 // runtime as a descriptor.
3972 mlir::Value createLboundArray(llvm::ArrayRef<mlir::Value> lbounds,
3973 mlir::Location loc) {
3974 mlir::Type indexTy = builder->getIndexType();
3975 mlir::Type boundArrayTy = fir::SequenceType::get(
3976 {static_cast<int64_t>(lbounds.size())}, builder->getI64Type());
3977 mlir::Value boundArray = builder->create<fir::AllocaOp>(loc, boundArrayTy);
3978 mlir::Value array = builder->create<fir::UndefOp>(loc, boundArrayTy);
3979 for (unsigned i = 0; i < lbounds.size(); ++i) {
3980 array = builder->create<fir::InsertValueOp>(
3981 loc, boundArrayTy, array, lbounds[i],
3982 builder->getArrayAttr({builder->getIntegerAttr(
3983 builder->getIndexType(), static_cast<int>(i))}));
3984 }
3985 builder->create<fir::StoreOp>(loc, array, boundArray);
3986 mlir::Type boxTy = fir::BoxType::get(boundArrayTy);
3987 mlir::Value ext =
3988 builder->createIntegerConstant(loc, indexTy, lbounds.size());
3989 llvm::SmallVector<mlir::Value> shapes = {ext};
3990 mlir::Value shapeOp = builder->genShape(loc, shapes);
3991 return builder->create<fir::EmboxOp>(loc, boxTy, boundArray, shapeOp);
3992 }
3993
3994 // Generate pointer assignment with possibly empty bounds-spec. R1035: a
3995 // bounds-spec is a lower bound value.
3996 void genPointerAssignment(
3997 mlir::Location loc, const Fortran::evaluate::Assignment &assign,
3998 const Fortran::evaluate::Assignment::BoundsSpec &lbExprs) {
3999 Fortran::lower::StatementContext stmtCtx;
4000
4001 if (!lowerToHighLevelFIR() &&
4002 Fortran::evaluate::IsProcedureDesignator(assign.rhs))
4003 TODO(loc, "procedure pointer assignment");
4004 if (Fortran::evaluate::IsProcedurePointer(assign.lhs)) {
4005 hlfir::Entity lhs = Fortran::lower::convertExprToHLFIR(
4006 loc, *this, assign.lhs, localSymbols, stmtCtx);
4007 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
4008 assign.rhs)) {
4009 // rhs is null(). rhs being null(pptr) is handled in genNull.
4010 auto boxTy{
4011 Fortran::lower::getUntypedBoxProcType(builder->getContext())};
4012 hlfir::Entity rhs(
4013 fir::factory::createNullBoxProc(*builder, loc, boxTy));
4014 builder->createStoreWithConvert(loc, rhs, lhs);
4015 return;
4016 }
4017 hlfir::Entity rhs(getBase(Fortran::lower::convertExprToAddress(
4018 loc, *this, assign.rhs, localSymbols, stmtCtx)));
4019 builder->createStoreWithConvert(loc, rhs, lhs);
4020 return;
4021 }
4022
4023 std::optional<Fortran::evaluate::DynamicType> lhsType =
4024 assign.lhs.GetType();
4025 // Delegate pointer association to unlimited polymorphic pointer
4026 // to the runtime. element size, type code, attribute and of
4027 // course base_addr might need to be updated.
4028 if (lhsType && lhsType->IsPolymorphic()) {
4029 if (!lowerToHighLevelFIR() && explicitIterationSpace())
4030 TODO(loc, "polymorphic pointer assignment in FORALL");
4031 llvm::SmallVector<mlir::Value> lbounds;
4032 for (const Fortran::evaluate::ExtentExpr &lbExpr : lbExprs)
4033 lbounds.push_back(
4034 fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx)));
4035 fir::MutableBoxValue lhsMutableBox = genExprMutableBox(loc, assign.lhs);
4036 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
4037 assign.rhs)) {
4038 fir::factory::disassociateMutableBox(*builder, loc, lhsMutableBox);
4039 return;
4040 }
4041 mlir::Value lhs = lhsMutableBox.getAddr();
4042 mlir::Value rhs = fir::getBase(genExprBox(loc, assign.rhs, stmtCtx));
4043 if (!lbounds.empty()) {
4044 mlir::Value boundsDesc = createLboundArray(lbounds, loc);
4045 Fortran::lower::genPointerAssociateLowerBounds(*builder, loc, lhs, rhs,
4046 boundsDesc);
4047 return;
4048 }
4049 Fortran::lower::genPointerAssociate(*builder, loc, lhs, rhs);
4050 return;
4051 }
4052
4053 llvm::SmallVector<mlir::Value> lbounds;
4054 for (const Fortran::evaluate::ExtentExpr &lbExpr : lbExprs)
4055 lbounds.push_back(fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx)));
4056 if (!lowerToHighLevelFIR() && explicitIterationSpace()) {
4057 // Pointer assignment in FORALL context. Copy the rhs box value
4058 // into the lhs box variable.
4059 genArrayAssignment(assign, stmtCtx, lbounds);
4060 return;
4061 }
4062 fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs);
4063 Fortran::lower::associateMutableBox(*this, loc, lhs, assign.rhs, lbounds,
4064 stmtCtx);
4065 }
4066
4067 // Create the 2 x newRank array with the bounds to be passed to the runtime as
4068 // a descriptor.
4069 mlir::Value createBoundArray(llvm::ArrayRef<mlir::Value> lbounds,
4070 llvm::ArrayRef<mlir::Value> ubounds,
4071 mlir::Location loc) {
4072 assert(lbounds.size() && ubounds.size());
4073 mlir::Type indexTy = builder->getIndexType();
4074 mlir::Type boundArrayTy = fir::SequenceType::get(
4075 {2, static_cast<int64_t>(lbounds.size())}, builder->getI64Type());
4076 mlir::Value boundArray = builder->create<fir::AllocaOp>(loc, boundArrayTy);
4077 mlir::Value array = builder->create<fir::UndefOp>(loc, boundArrayTy);
4078 for (unsigned i = 0; i < lbounds.size(); ++i) {
4079 array = builder->create<fir::InsertValueOp>(
4080 loc, boundArrayTy, array, lbounds[i],
4081 builder->getArrayAttr(
4082 {builder->getIntegerAttr(builder->getIndexType(), 0),
4083 builder->getIntegerAttr(builder->getIndexType(),
4084 static_cast<int>(i))}));
4085 array = builder->create<fir::InsertValueOp>(
4086 loc, boundArrayTy, array, ubounds[i],
4087 builder->getArrayAttr(
4088 {builder->getIntegerAttr(builder->getIndexType(), 1),
4089 builder->getIntegerAttr(builder->getIndexType(),
4090 static_cast<int>(i))}));
4091 }
4092 builder->create<fir::StoreOp>(loc, array, boundArray);
4093 mlir::Type boxTy = fir::BoxType::get(boundArrayTy);
4094 mlir::Value ext =
4095 builder->createIntegerConstant(loc, indexTy, lbounds.size());
4096 mlir::Value c2 = builder->createIntegerConstant(loc, indexTy, 2);
4097 llvm::SmallVector<mlir::Value> shapes = {c2, ext};
4098 mlir::Value shapeOp = builder->genShape(loc, shapes);
4099 return builder->create<fir::EmboxOp>(loc, boxTy, boundArray, shapeOp);
4100 }
4101
4102 // Pointer assignment with bounds-remapping. R1036: a bounds-remapping is a
4103 // pair, lower bound and upper bound.
4104 void genPointerAssignment(
4105 mlir::Location loc, const Fortran::evaluate::Assignment &assign,
4106 const Fortran::evaluate::Assignment::BoundsRemapping &boundExprs) {
4107 Fortran::lower::StatementContext stmtCtx;
4108 llvm::SmallVector<mlir::Value> lbounds;
4109 llvm::SmallVector<mlir::Value> ubounds;
4110 for (const std::pair<Fortran::evaluate::ExtentExpr,
4111 Fortran::evaluate::ExtentExpr> &pair : boundExprs) {
4112 const Fortran::evaluate::ExtentExpr &lbExpr = pair.first;
4113 const Fortran::evaluate::ExtentExpr &ubExpr = pair.second;
4114 lbounds.push_back(fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx)));
4115 ubounds.push_back(fir::getBase(genExprValue(toEvExpr(ubExpr), stmtCtx)));
4116 }
4117
4118 std::optional<Fortran::evaluate::DynamicType> lhsType =
4119 assign.lhs.GetType();
4120 std::optional<Fortran::evaluate::DynamicType> rhsType =
4121 assign.rhs.GetType();
4122 // Polymorphic lhs/rhs need more care. See F2018 10.2.2.3.
4123 if ((lhsType && lhsType->IsPolymorphic()) ||
4124 (rhsType && rhsType->IsPolymorphic())) {
4125 if (!lowerToHighLevelFIR() && explicitIterationSpace())
4126 TODO(loc, "polymorphic pointer assignment in FORALL");
4127
4128 fir::MutableBoxValue lhsMutableBox = genExprMutableBox(loc, assign.lhs);
4129 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
4130 assign.rhs)) {
4131 fir::factory::disassociateMutableBox(*builder, loc, lhsMutableBox);
4132 return;
4133 }
4134 mlir::Value lhs = lhsMutableBox.getAddr();
4135 mlir::Value rhs = fir::getBase(genExprBox(loc, assign.rhs, stmtCtx));
4136 mlir::Value boundsDesc = createBoundArray(lbounds, ubounds, loc);
4137 Fortran::lower::genPointerAssociateRemapping(*builder, loc, lhs, rhs,
4138 boundsDesc);
4139 return;
4140 }
4141 if (!lowerToHighLevelFIR() && explicitIterationSpace()) {
4142 // Pointer assignment in FORALL context. Copy the rhs box value
4143 // into the lhs box variable.
4144 genArrayAssignment(assign, stmtCtx, lbounds, ubounds);
4145 return;
4146 }
4147 fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs);
4148 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
4149 assign.rhs)) {
4150 fir::factory::disassociateMutableBox(*builder, loc, lhs);
4151 return;
4152 }
4153 if (lowerToHighLevelFIR()) {
4154 fir::ExtendedValue rhs = genExprAddr(assign.rhs, stmtCtx);
4155 fir::factory::associateMutableBoxWithRemap(*builder, loc, lhs, rhs,
4156 lbounds, ubounds);
4157 return;
4158 }
4159 // Legacy lowering below.
4160 // Do not generate a temp in case rhs is an array section.
4161 fir::ExtendedValue rhs =
4162 Fortran::lower::isArraySectionWithoutVectorSubscript(assign.rhs)
4163 ? Fortran::lower::createSomeArrayBox(*this, assign.rhs,
4164 localSymbols, stmtCtx)
4165 : genExprAddr(assign.rhs, stmtCtx);
4166 fir::factory::associateMutableBoxWithRemap(*builder, loc, lhs, rhs, lbounds,
4167 ubounds);
4168 if (explicitIterationSpace()) {
4169 mlir::ValueRange inners = explicitIterSpace.getInnerArgs();
4170 if (!inners.empty())
4171 builder->create<fir::ResultOp>(loc, inners);
4172 }
4173 }
4174
4175 /// Given converted LHS and RHS of the assignment, materialize any
4176 /// implicit conversion of the RHS to the LHS type. The front-end
4177 /// usually already makes those explicit, except for non-standard
4178 /// LOGICAL <-> INTEGER, or if the LHS is a whole allocatable
4179 /// (making the conversion explicit in the front-end would prevent
4180 /// propagation of the LHS lower bound in the reallocation).
4181 /// If array temporaries or values are created, the cleanups are
4182 /// added in the statement context.
4183 hlfir::Entity genImplicitConvert(const Fortran::evaluate::Assignment &assign,
4184 hlfir::Entity rhs, bool preserveLowerBounds,
4185 Fortran::lower::StatementContext &stmtCtx) {
4186 mlir::Location loc = toLocation();
4187 auto &builder = getFirOpBuilder();
4188 mlir::Type toType = genType(assign.lhs);
4189 auto valueAndPair = hlfir::genTypeAndKindConvert(loc, builder, rhs, toType,
4190 preserveLowerBounds);
4191 if (valueAndPair.second)
4192 stmtCtx.attachCleanup(*valueAndPair.second);
4193 return hlfir::Entity{valueAndPair.first};
4194 }
4195
4196 bool firstDummyIsPointerOrAllocatable(
4197 const Fortran::evaluate::ProcedureRef &userDefinedAssignment) {
4198 using DummyAttr = Fortran::evaluate::characteristics::DummyDataObject::Attr;
4199 if (auto procedure =
4200 Fortran::evaluate::characteristics::Procedure::Characterize(
4201 userDefinedAssignment.proc(), getFoldingContext(),
4202 /*emitError=*/false))
4203 if (!procedure->dummyArguments.empty())
4204 if (const auto *dataArg = std::get_if<
4205 Fortran::evaluate::characteristics::DummyDataObject>(
4206 &procedure->dummyArguments[0].u))
4207 return dataArg->attrs.test(DummyAttr::Pointer) ||
4208 dataArg->attrs.test(DummyAttr::Allocatable);
4209 return false;
4210 }
4211
4212 void genCUDADataTransfer(fir::FirOpBuilder &builder, mlir::Location loc,
4213 const Fortran::evaluate::Assignment &assign,
4214 hlfir::Entity &lhs, hlfir::Entity &rhs) {
4215 bool lhsIsDevice = Fortran::evaluate::HasCUDADeviceAttrs(assign.lhs);
4216 bool rhsIsDevice = Fortran::evaluate::HasCUDADeviceAttrs(assign.rhs);
4217
4218 auto getRefIfLoaded = [](mlir::Value val) -> mlir::Value {
4219 if (auto loadOp =
4220 mlir::dyn_cast_or_null<fir::LoadOp>(val.getDefiningOp()))
4221 return loadOp.getMemref();
4222 return val;
4223 };
4224
4225 mlir::Value rhsVal = getRefIfLoaded(rhs.getBase());
4226 mlir::Value lhsVal = getRefIfLoaded(lhs.getBase());
4227
4228 // device = host
4229 if (lhsIsDevice && !rhsIsDevice) {
4230 auto transferKindAttr = cuf::DataTransferKindAttr::get(
4231 builder.getContext(), cuf::DataTransferKind::HostDevice);
4232 if (!rhs.isVariable()) {
4233 mlir::Value base = rhs;
4234 if (auto convertOp =
4235 mlir::dyn_cast<fir::ConvertOp>(rhs.getDefiningOp()))
4236 base = convertOp.getValue();
4237 // Special case if the rhs is a constant.
4238 if (matchPattern(base.getDefiningOp(), mlir::m_Constant())) {
4239 builder.create<cuf::DataTransferOp>(loc, base, lhsVal,
4240 transferKindAttr);
4241 } else {
4242 auto associate = hlfir::genAssociateExpr(
4243 loc, builder, rhs, rhs.getType(), ".cuf_host_tmp");
4244 builder.create<cuf::DataTransferOp>(loc, associate.getBase(), lhsVal,
4245 transferKindAttr);
4246 builder.create<hlfir::EndAssociateOp>(loc, associate);
4247 }
4248 } else {
4249 builder.create<cuf::DataTransferOp>(loc, rhsVal, lhsVal,
4250 transferKindAttr);
4251 }
4252 return;
4253 }
4254
4255 // host = device
4256 if (!lhsIsDevice && rhsIsDevice) {
4257 auto transferKindAttr = cuf::DataTransferKindAttr::get(
4258 builder.getContext(), cuf::DataTransferKind::DeviceHost);
4259 builder.create<cuf::DataTransferOp>(loc, rhsVal, lhsVal,
4260 transferKindAttr);
4261 return;
4262 }
4263
4264 // device = device
4265 if (lhsIsDevice && rhsIsDevice) {
4266 assert(rhs.isVariable() && "CUDA Fortran assignment rhs is not legal");
4267 auto transferKindAttr = cuf::DataTransferKindAttr::get(
4268 builder.getContext(), cuf::DataTransferKind::DeviceDevice);
4269 builder.create<cuf::DataTransferOp>(loc, rhsVal, lhsVal,
4270 transferKindAttr);
4271 return;
4272 }
4273 llvm_unreachable("Unhandled CUDA data transfer");
4274 }
4275
4276 llvm::SmallVector<mlir::Value>
4277 genCUDAImplicitDataTransfer(fir::FirOpBuilder &builder, mlir::Location loc,
4278 const Fortran::evaluate::Assignment &assign) {
4279 llvm::SmallVector<mlir::Value> temps;
4280 localSymbols.pushScope();
4281 auto transferKindAttr = cuf::DataTransferKindAttr::get(
4282 builder.getContext(), cuf::DataTransferKind::DeviceHost);
4283 [[maybe_unused]] unsigned nbDeviceResidentObject = 0;
4284 for (const Fortran::semantics::Symbol &sym :
4285 Fortran::evaluate::CollectSymbols(assign.rhs)) {
4286 if (const auto *details =
4287 sym.GetUltimate()
4288 .detailsIf<Fortran::semantics::ObjectEntityDetails>()) {
4289 if (details->cudaDataAttr() &&
4290 *details->cudaDataAttr() != Fortran::common::CUDADataAttr::Pinned) {
4291 if (sym.owner().IsDerivedType() && IsAllocatable(sym.GetUltimate()))
4292 TODO(loc, "Device resident allocatable derived-type component");
4293 // TODO: This should probably being checked in semantic and give a
4294 // proper error.
4295 assert(
4296 nbDeviceResidentObject <= 1 &&
4297 "Only one reference to the device resident object is supported");
4298 auto addr = getSymbolAddress(sym);
4299 hlfir::Entity entity{addr};
4300 auto [temp, cleanup] =
4301 hlfir::createTempFromMold(loc, builder, entity);
4302 auto needCleanup = fir::getIntIfConstant(cleanup);
4303 if (needCleanup && *needCleanup) {
4304 if (auto declareOp =
4305 mlir::dyn_cast<hlfir::DeclareOp>(temp.getDefiningOp()))
4306 temps.push_back(declareOp.getMemref());
4307 else
4308 temps.push_back(temp);
4309 }
4310 addSymbol(sym,
4311 hlfir::translateToExtendedValue(loc, builder, temp).first,
4312 /*forced=*/true);
4313 builder.create<cuf::DataTransferOp>(loc, addr, temp,
4314 transferKindAttr);
4315 ++nbDeviceResidentObject;
4316 }
4317 }
4318 }
4319 return temps;
4320 }
4321
4322 // Check if the insertion point is currently in a device context. HostDevice
4323 // subprogram are not considered fully device context so it will return false
4324 // for it.
4325 static bool isDeviceContext(fir::FirOpBuilder &builder) {
4326 if (builder.getRegion().getParentOfType<cuf::KernelOp>())
4327 return true;
4328 if (auto funcOp =
4329 builder.getRegion().getParentOfType<mlir::func::FuncOp>()) {
4330 if (auto cudaProcAttr =
4331 funcOp.getOperation()->getAttrOfType<cuf::ProcAttributeAttr>(
4332 cuf::getProcAttrName())) {
4333 return cudaProcAttr.getValue() != cuf::ProcAttribute::Host &&
4334 cudaProcAttr.getValue() != cuf::ProcAttribute::HostDevice;
4335 }
4336 }
4337 return false;
4338 }
4339
4340 void genDataAssignment(
4341 const Fortran::evaluate::Assignment &assign,
4342 const Fortran::evaluate::ProcedureRef *userDefinedAssignment) {
4343 mlir::Location loc = getCurrentLocation();
4344 fir::FirOpBuilder &builder = getFirOpBuilder();
4345
4346 bool isInDeviceContext = isDeviceContext(builder);
4347 bool isCUDATransfer = (Fortran::evaluate::HasCUDADeviceAttrs(assign.lhs) ||
4348 Fortran::evaluate::HasCUDADeviceAttrs(assign.rhs)) &&
4349 !isInDeviceContext;
4350 bool hasCUDAImplicitTransfer =
4351 Fortran::evaluate::HasCUDAImplicitTransfer(assign.rhs);
4352 llvm::SmallVector<mlir::Value> implicitTemps;
4353 if (hasCUDAImplicitTransfer && !isInDeviceContext)
4354 implicitTemps = genCUDAImplicitDataTransfer(builder, loc, assign);
4355
4356 // Gather some information about the assignment that will impact how it is
4357 // lowered.
4358 const bool isWholeAllocatableAssignment =
4359 !userDefinedAssignment && !isInsideHlfirWhere() &&
4360 Fortran::lower::isWholeAllocatable(assign.lhs);
4361 const bool isUserDefAssignToPointerOrAllocatable =
4362 userDefinedAssignment &&
4363 firstDummyIsPointerOrAllocatable(*userDefinedAssignment);
4364 std::optional<Fortran::evaluate::DynamicType> lhsType =
4365 assign.lhs.GetType();
4366 const bool keepLhsLengthInAllocatableAssignment =
4367 isWholeAllocatableAssignment && lhsType.has_value() &&
4368 lhsType->category() == Fortran::common::TypeCategory::Character &&
4369 !lhsType->HasDeferredTypeParameter();
4370 const bool lhsHasVectorSubscripts =
4371 Fortran::evaluate::HasVectorSubscript(assign.lhs);
4372
4373 // Helper to generate the code evaluating the right-hand side.
4374 auto evaluateRhs = [&](Fortran::lower::StatementContext &stmtCtx) {
4375 hlfir::Entity rhs = Fortran::lower::convertExprToHLFIR(
4376 loc, *this, assign.rhs, localSymbols, stmtCtx);
4377 // Load trivial scalar RHS to allow the loads to be hoisted outside of
4378 // loops early if possible. This also dereferences pointer and
4379 // allocatable RHS: the target is being assigned from.
4380 rhs = hlfir::loadTrivialScalar(loc, builder, rhs);
4381 // In intrinsic assignments, the LHS type may not match the RHS type, in
4382 // which case an implicit conversion of the LHS must be done. The
4383 // front-end usually makes it explicit, unless it cannot (whole
4384 // allocatable LHS or Logical<->Integer assignment extension). Recognize
4385 // any type mismatches here and insert explicit scalar convert or
4386 // ElementalOp for array assignment. Preserve the RHS lower bounds on the
4387 // converted entity in case of assignment to whole allocatables so to
4388 // propagate the lower bounds to the LHS in case of reallocation.
4389 if (!userDefinedAssignment)
4390 rhs = genImplicitConvert(assign, rhs, isWholeAllocatableAssignment,
4391 stmtCtx);
4392 return rhs;
4393 };
4394
4395 // Helper to generate the code evaluating the left-hand side.
4396 auto evaluateLhs = [&](Fortran::lower::StatementContext &stmtCtx) {
4397 hlfir::Entity lhs = Fortran::lower::convertExprToHLFIR(
4398 loc, *this, assign.lhs, localSymbols, stmtCtx);
4399 // Dereference pointer LHS: the target is being assigned to.
4400 // Same for allocatables outside of whole allocatable assignments.
4401 if (!isWholeAllocatableAssignment &&
4402 !isUserDefAssignToPointerOrAllocatable)
4403 lhs = hlfir::derefPointersAndAllocatables(loc, builder, lhs);
4404 return lhs;
4405 };
4406
4407 if (!isInsideHlfirForallOrWhere() && !lhsHasVectorSubscripts &&
4408 !userDefinedAssignment) {
4409 Fortran::lower::StatementContext localStmtCtx;
4410 hlfir::Entity rhs = evaluateRhs(localStmtCtx);
4411 hlfir::Entity lhs = evaluateLhs(localStmtCtx);
4412 if (isCUDATransfer && !hasCUDAImplicitTransfer)
4413 genCUDADataTransfer(builder, loc, assign, lhs, rhs);
4414 else
4415 builder.create<hlfir::AssignOp>(loc, rhs, lhs,
4416 isWholeAllocatableAssignment,
4417 keepLhsLengthInAllocatableAssignment);
4418 if (hasCUDAImplicitTransfer && !isInDeviceContext) {
4419 localSymbols.popScope();
4420 for (mlir::Value temp : implicitTemps)
4421 builder.create<fir::FreeMemOp>(loc, temp);
4422 }
4423 return;
4424 }
4425 // Assignments inside Forall, Where, or assignments to a vector subscripted
4426 // left-hand side requires using an hlfir.region_assign in HLFIR. The
4427 // right-hand side and left-hand side must be evaluated inside the
4428 // hlfir.region_assign regions.
4429 auto regionAssignOp = builder.create<hlfir::RegionAssignOp>(loc);
4430
4431 // Lower RHS in its own region.
4432 builder.createBlock(&regionAssignOp.getRhsRegion());
4433 Fortran::lower::StatementContext rhsContext;
4434 hlfir::Entity rhs = evaluateRhs(rhsContext);
4435 auto rhsYieldOp = builder.create<hlfir::YieldOp>(loc, rhs);
4436 Fortran::lower::genCleanUpInRegionIfAny(
4437 loc, builder, rhsYieldOp.getCleanup(), rhsContext);
4438 // Lower LHS in its own region.
4439 builder.createBlock(&regionAssignOp.getLhsRegion());
4440 Fortran::lower::StatementContext lhsContext;
4441 mlir::Value lhsYield = nullptr;
4442 if (!lhsHasVectorSubscripts) {
4443 hlfir::Entity lhs = evaluateLhs(lhsContext);
4444 auto lhsYieldOp = builder.create<hlfir::YieldOp>(loc, lhs);
4445 Fortran::lower::genCleanUpInRegionIfAny(
4446 loc, builder, lhsYieldOp.getCleanup(), lhsContext);
4447 lhsYield = lhs;
4448 } else {
4449 hlfir::ElementalAddrOp elementalAddr =
4450 Fortran::lower::convertVectorSubscriptedExprToElementalAddr(
4451 loc, *this, assign.lhs, localSymbols, lhsContext);
4452 Fortran::lower::genCleanUpInRegionIfAny(
4453 loc, builder, elementalAddr.getCleanup(), lhsContext);
4454 lhsYield = elementalAddr.getYieldOp().getEntity();
4455 }
4456 assert(lhsYield && "must have been set");
4457
4458 // Add "realloc" flag to hlfir.region_assign.
4459 if (isWholeAllocatableAssignment)
4460 TODO(loc, "assignment to a whole allocatable inside FORALL");
4461
4462 // Generate the hlfir.region_assign userDefinedAssignment region.
4463 if (userDefinedAssignment) {
4464 mlir::Type rhsType = rhs.getType();
4465 mlir::Type lhsType = lhsYield.getType();
4466 if (userDefinedAssignment->IsElemental()) {
4467 rhsType = hlfir::getEntityElementType(rhs);
4468 lhsType = hlfir::getEntityElementType(hlfir::Entity{lhsYield});
4469 }
4470 builder.createBlock(&regionAssignOp.getUserDefinedAssignment(),
4471 mlir::Region::iterator{}, {rhsType, lhsType},
4472 {loc, loc});
4473 auto end = builder.create<fir::FirEndOp>(loc);
4474 builder.setInsertionPoint(end);
4475 hlfir::Entity lhsBlockArg{regionAssignOp.getUserAssignmentLhs()};
4476 hlfir::Entity rhsBlockArg{regionAssignOp.getUserAssignmentRhs()};
4477 Fortran::lower::convertUserDefinedAssignmentToHLFIR(
4478 loc, *this, *userDefinedAssignment, lhsBlockArg, rhsBlockArg,
4479 localSymbols);
4480 }
4481 builder.setInsertionPointAfter(regionAssignOp);
4482 }
4483
4484 /// Shared for both assignments and pointer assignments.
4485 void genAssignment(const Fortran::evaluate::Assignment &assign) {
4486 mlir::Location loc = toLocation();
4487 if (lowerToHighLevelFIR()) {
4488 Fortran::common::visit(
4489 Fortran::common::visitors{
4490 [&](const Fortran::evaluate::Assignment::Intrinsic &) {
4491 genDataAssignment(assign, /*userDefinedAssignment=*/nullptr);
4492 },
4493 [&](const Fortran::evaluate::ProcedureRef &procRef) {
4494 genDataAssignment(assign, /*userDefinedAssignment=*/&procRef);
4495 },
4496 [&](const Fortran::evaluate::Assignment::BoundsSpec &lbExprs) {
4497 if (isInsideHlfirForallOrWhere())
4498 TODO(loc, "pointer assignment inside FORALL");
4499 genPointerAssignment(loc, assign, lbExprs);
4500 },
4501 [&](const Fortran::evaluate::Assignment::BoundsRemapping
4502 &boundExprs) {
4503 if (isInsideHlfirForallOrWhere())
4504 TODO(loc, "pointer assignment inside FORALL");
4505 genPointerAssignment(loc, assign, boundExprs);
4506 },
4507 },
4508 assign.u);
4509 return;
4510 }
4511 if (explicitIterationSpace()) {
4512 Fortran::lower::createArrayLoads(*this, explicitIterSpace, localSymbols);
4513 explicitIterSpace.genLoopNest();
4514 }
4515 Fortran::lower::StatementContext stmtCtx;
4516 Fortran::common::visit(
4517 Fortran::common::visitors{
4518 // [1] Plain old assignment.
4519 [&](const Fortran::evaluate::Assignment::Intrinsic &) {
4520 const Fortran::semantics::Symbol *sym =
4521 Fortran::evaluate::GetLastSymbol(assign.lhs);
4522
4523 if (!sym)
4524 TODO(loc, "assignment to pointer result of function reference");
4525
4526 std::optional<Fortran::evaluate::DynamicType> lhsType =
4527 assign.lhs.GetType();
4528 assert(lhsType && "lhs cannot be typeless");
4529 std::optional<Fortran::evaluate::DynamicType> rhsType =
4530 assign.rhs.GetType();
4531
4532 // Assignment to/from polymorphic entities are done with the
4533 // runtime.
4534 if (lhsType->IsPolymorphic() ||
4535 lhsType->IsUnlimitedPolymorphic() ||
4536 (rhsType && (rhsType->IsPolymorphic() ||
4537 rhsType->IsUnlimitedPolymorphic()))) {
4538 mlir::Value lhs;
4539 if (Fortran::lower::isWholeAllocatable(assign.lhs))
4540 lhs = genExprMutableBox(loc, assign.lhs).getAddr();
4541 else
4542 lhs = fir::getBase(genExprBox(loc, assign.lhs, stmtCtx));
4543 mlir::Value rhs =
4544 fir::getBase(genExprBox(loc, assign.rhs, stmtCtx));
4545 if ((lhsType->IsPolymorphic() ||
4546 lhsType->IsUnlimitedPolymorphic()) &&
4547 Fortran::lower::isWholeAllocatable(assign.lhs))
4548 fir::runtime::genAssignPolymorphic(*builder, loc, lhs, rhs);
4549 else
4550 fir::runtime::genAssign(*builder, loc, lhs, rhs);
4551 return;
4552 }
4553
4554 // Note: No ad-hoc handling for pointers is required here. The
4555 // target will be assigned as per 2018 10.2.1.3 p2. genExprAddr
4556 // on a pointer returns the target address and not the address of
4557 // the pointer variable.
4558
4559 if (assign.lhs.Rank() > 0 || explicitIterationSpace()) {
4560 if (isDerivedCategory(lhsType->category()) &&
4561 Fortran::semantics::IsFinalizable(
4562 lhsType->GetDerivedTypeSpec()))
4563 TODO(loc, "derived-type finalization with array assignment");
4564 // Array assignment
4565 // See Fortran 2018 10.2.1.3 p5, p6, and p7
4566 genArrayAssignment(assign, stmtCtx);
4567 return;
4568 }
4569
4570 // Scalar assignment
4571 const bool isNumericScalar =
4572 isNumericScalarCategory(lhsType->category());
4573 const bool isVector =
4574 isDerivedCategory(lhsType->category()) &&
4575 lhsType->GetDerivedTypeSpec().IsVectorType();
4576 fir::ExtendedValue rhs = (isNumericScalar || isVector)
4577 ? genExprValue(assign.rhs, stmtCtx)
4578 : genExprAddr(assign.rhs, stmtCtx);
4579 const bool lhsIsWholeAllocatable =
4580 Fortran::lower::isWholeAllocatable(assign.lhs);
4581 std::optional<fir::factory::MutableBoxReallocation> lhsRealloc;
4582 std::optional<fir::MutableBoxValue> lhsMutableBox;
4583
4584 // Set flag to know if the LHS needs finalization. Polymorphic,
4585 // unlimited polymorphic assignment will be done with genAssign.
4586 // Assign runtime function performs the finalization.
4587 bool needFinalization = !lhsType->IsPolymorphic() &&
4588 !lhsType->IsUnlimitedPolymorphic() &&
4589 (isDerivedCategory(lhsType->category()) &&
4590 Fortran::semantics::IsFinalizable(
4591 lhsType->GetDerivedTypeSpec()));
4592
4593 auto lhs = [&]() -> fir::ExtendedValue {
4594 if (lhsIsWholeAllocatable) {
4595 lhsMutableBox = genExprMutableBox(loc, assign.lhs);
4596 // Finalize if needed.
4597 if (needFinalization) {
4598 mlir::Value isAllocated =
4599 fir::factory::genIsAllocatedOrAssociatedTest(
4600 *builder, loc, *lhsMutableBox);
4601 builder->genIfThen(loc, isAllocated)
4602 .genThen([&]() {
4603 fir::runtime::genDerivedTypeDestroy(
4604 *builder, loc, fir::getBase(*lhsMutableBox));
4605 })
4606 .end();
4607 needFinalization = false;
4608 }
4609
4610 llvm::SmallVector<mlir::Value> lengthParams;
4611 if (const fir::CharBoxValue *charBox = rhs.getCharBox())
4612 lengthParams.push_back(charBox->getLen());
4613 else if (fir::isDerivedWithLenParameters(rhs))
4614 TODO(loc, "assignment to derived type allocatable with "
4615 "LEN parameters");
4616 lhsRealloc = fir::factory::genReallocIfNeeded(
4617 *builder, loc, *lhsMutableBox,
4618 /*shape=*/std::nullopt, lengthParams);
4619 return lhsRealloc->newValue;
4620 }
4621 return genExprAddr(assign.lhs, stmtCtx);
4622 }();
4623
4624 if (isNumericScalar || isVector) {
4625 // Fortran 2018 10.2.1.3 p8 and p9
4626 // Conversions should have been inserted by semantic analysis,
4627 // but they can be incorrect between the rhs and lhs. Correct
4628 // that here.
4629 mlir::Value addr = fir::getBase(lhs);
4630 mlir::Value val = fir::getBase(rhs);
4631 // A function with multiple entry points returning different
4632 // types tags all result variables with one of the largest
4633 // types to allow them to share the same storage. Assignment
4634 // to a result variable of one of the other types requires
4635 // conversion to the actual type.
4636 mlir::Type toTy = genType(assign.lhs);
4637
4638 // If Cray pointee, need to handle the address
4639 // Array is handled in genCoordinateOp.
4640 if (sym->test(Fortran::semantics::Symbol::Flag::CrayPointee) &&
4641 sym->Rank() == 0) {
4642 // get the corresponding Cray pointer
4643
4644 const Fortran::semantics::Symbol &ptrSym =
4645 Fortran::semantics::GetCrayPointer(*sym);
4646 fir::ExtendedValue ptr =
4647 getSymbolExtendedValue(ptrSym, nullptr);
4648 mlir::Value ptrVal = fir::getBase(ptr);
4649 mlir::Type ptrTy = genType(ptrSym);
4650
4651 fir::ExtendedValue pte =
4652 getSymbolExtendedValue(*sym, nullptr);
4653 mlir::Value pteVal = fir::getBase(pte);
4654 mlir::Value cnvrt = Fortran::lower::addCrayPointerInst(
4655 loc, *builder, ptrVal, ptrTy, pteVal.getType());
4656 addr = builder->create<fir::LoadOp>(loc, cnvrt);
4657 }
4658 mlir::Value cast =
4659 isVector ? val
4660 : builder->convertWithSemantics(loc, toTy, val);
4661 if (fir::dyn_cast_ptrEleTy(addr.getType()) != toTy) {
4662 assert(isFuncResultDesignator(assign.lhs) && "type mismatch");
4663 addr = builder->createConvert(
4664 toLocation(), builder->getRefType(toTy), addr);
4665 }
4666 builder->create<fir::StoreOp>(loc, cast, addr);
4667 } else if (isCharacterCategory(lhsType->category())) {
4668 // Fortran 2018 10.2.1.3 p10 and p11
4669 fir::factory::CharacterExprHelper{*builder, loc}.createAssign(
4670 lhs, rhs);
4671 } else if (isDerivedCategory(lhsType->category())) {
4672 // Handle parent component.
4673 if (Fortran::lower::isParentComponent(assign.lhs)) {
4674 if (!mlir::isa<fir::BaseBoxType>(fir::getBase(lhs).getType()))
4675 lhs = fir::getBase(builder->createBox(loc, lhs));
4676 lhs = Fortran::lower::updateBoxForParentComponent(*this, lhs,
4677 assign.lhs);
4678 }
4679
4680 // Fortran 2018 10.2.1.3 p13 and p14
4681 // Recursively gen an assignment on each element pair.
4682 fir::factory::genRecordAssignment(*builder, loc, lhs, rhs,
4683 needFinalization);
4684 } else {
4685 llvm_unreachable("unknown category");
4686 }
4687 if (lhsIsWholeAllocatable) {
4688 assert(lhsRealloc.has_value());
4689 fir::factory::finalizeRealloc(*builder, loc, *lhsMutableBox,
4690 /*lbounds=*/std::nullopt,
4691 /*takeLboundsIfRealloc=*/false,
4692 *lhsRealloc);
4693 }
4694 },
4695
4696 // [2] User defined assignment. If the context is a scalar
4697 // expression then call the procedure.
4698 [&](const Fortran::evaluate::ProcedureRef &procRef) {
4699 Fortran::lower::StatementContext &ctx =
4700 explicitIterationSpace() ? explicitIterSpace.stmtContext()
4701 : stmtCtx;
4702 Fortran::lower::createSubroutineCall(
4703 *this, procRef, explicitIterSpace, implicitIterSpace,
4704 localSymbols, ctx, /*isUserDefAssignment=*/true);
4705 },
4706
4707 [&](const Fortran::evaluate::Assignment::BoundsSpec &lbExprs) {
4708 return genPointerAssignment(loc, assign, lbExprs);
4709 },
4710 [&](const Fortran::evaluate::Assignment::BoundsRemapping
4711 &boundExprs) {
4712 return genPointerAssignment(loc, assign, boundExprs);
4713 },
4714 },
4715 assign.u);
4716 if (explicitIterationSpace())
4717 Fortran::lower::createArrayMergeStores(*this, explicitIterSpace);
4718 }
4719
4720 // Is the insertion point of the builder directly or indirectly set
4721 // inside any operation of type "Op"?
4722 template <typename... Op>
4723 bool isInsideOp() const {
4724 mlir::Block *block = builder->getInsertionBlock();
4725 mlir::Operation *op = block ? block->getParentOp() : nullptr;
4726 while (op) {
4727 if (mlir::isa<Op...>(op))
4728 return true;
4729 op = op->getParentOp();
4730 }
4731 return false;
4732 }
4733 bool isInsideHlfirForallOrWhere() const {
4734 return isInsideOp<hlfir::ForallOp, hlfir::WhereOp>();
4735 }
4736 bool isInsideHlfirWhere() const { return isInsideOp<hlfir::WhereOp>(); }
4737
4738 void genFIR(const Fortran::parser::WhereConstruct &c) {
4739 mlir::Location loc = getCurrentLocation();
4740 hlfir::WhereOp whereOp;
4741
4742 if (!lowerToHighLevelFIR()) {
4743 implicitIterSpace.growStack();
4744 } else {
4745 whereOp = builder->create<hlfir::WhereOp>(loc);
4746 builder->createBlock(&whereOp.getMaskRegion());
4747 }
4748
4749 // Lower the where mask. For HLFIR, this is done in the hlfir.where mask
4750 // region.
4751 genNestedStatement(
4752 std::get<
4753 Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>(
4754 c.t));
4755
4756 // Lower WHERE body. For HLFIR, this is done in the hlfir.where body
4757 // region.
4758 if (whereOp)
4759 builder->createBlock(&whereOp.getBody());
4760
4761 for (const auto &body :
4762 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t))
4763 genFIR(body);
4764 for (const auto &e :
4765 std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>(
4766 c.t))
4767 genFIR(e);
4768 if (const auto &e =
4769 std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>(
4770 c.t);
4771 e.has_value())
4772 genFIR(*e);
4773 genNestedStatement(
4774 std::get<Fortran::parser::Statement<Fortran::parser::EndWhereStmt>>(
4775 c.t));
4776
4777 if (whereOp) {
4778 // For HLFIR, create fir.end terminator in the last hlfir.elsewhere, or
4779 // in the hlfir.where if it had no elsewhere.
4780 builder->create<fir::FirEndOp>(loc);
4781 builder->setInsertionPointAfter(whereOp);
4782 }
4783 }
4784 void genFIR(const Fortran::parser::WhereBodyConstruct &body) {
4785 Fortran::common::visit(
4786 Fortran::common::visitors{
4787 [&](const Fortran::parser::Statement<
4788 Fortran::parser::AssignmentStmt> &stmt) {
4789 genNestedStatement(stmt);
4790 },
4791 [&](const Fortran::parser::Statement<Fortran::parser::WhereStmt>
4792 &stmt) { genNestedStatement(stmt); },
4793 [&](const Fortran::common::Indirection<
4794 Fortran::parser::WhereConstruct> &c) { genFIR(c.value()); },
4795 },
4796 body.u);
4797 }
4798
4799 /// Lower a Where or Elsewhere mask into an hlfir mask region.
4800 void lowerWhereMaskToHlfir(mlir::Location loc,
4801 const Fortran::semantics::SomeExpr *maskExpr) {
4802 assert(maskExpr && "mask semantic analysis failed");
4803 Fortran::lower::StatementContext maskContext;
4804 hlfir::Entity mask = Fortran::lower::convertExprToHLFIR(
4805 loc, *this, *maskExpr, localSymbols, maskContext);
4806 mask = hlfir::loadTrivialScalar(loc, *builder, mask);
4807 auto yieldOp = builder->create<hlfir::YieldOp>(loc, mask);
4808 Fortran::lower::genCleanUpInRegionIfAny(loc, *builder, yieldOp.getCleanup(),
4809 maskContext);
4810 }
4811 void genFIR(const Fortran::parser::WhereConstructStmt &stmt) {
4812 const Fortran::semantics::SomeExpr *maskExpr = Fortran::semantics::GetExpr(
4813 std::get<Fortran::parser::LogicalExpr>(stmt.t));
4814 if (lowerToHighLevelFIR())
4815 lowerWhereMaskToHlfir(getCurrentLocation(), maskExpr);
4816 else
4817 implicitIterSpace.append(maskExpr);
4818 }
4819 void genFIR(const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) {
4820 mlir::Location loc = getCurrentLocation();
4821 hlfir::ElseWhereOp elsewhereOp;
4822 if (lowerToHighLevelFIR()) {
4823 elsewhereOp = builder->create<hlfir::ElseWhereOp>(loc);
4824 // Lower mask in the mask region.
4825 builder->createBlock(&elsewhereOp.getMaskRegion());
4826 }
4827 genNestedStatement(
4828 std::get<
4829 Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>(
4830 ew.t));
4831
4832 // For HLFIR, lower the body in the hlfir.elsewhere body region.
4833 if (elsewhereOp)
4834 builder->createBlock(&elsewhereOp.getBody());
4835
4836 for (const auto &body :
4837 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t))
4838 genFIR(body);
4839 }
4840 void genFIR(const Fortran::parser::MaskedElsewhereStmt &stmt) {
4841 const auto *maskExpr = Fortran::semantics::GetExpr(
4842 std::get<Fortran::parser::LogicalExpr>(stmt.t));
4843 if (lowerToHighLevelFIR())
4844 lowerWhereMaskToHlfir(getCurrentLocation(), maskExpr);
4845 else
4846 implicitIterSpace.append(maskExpr);
4847 }
4848 void genFIR(const Fortran::parser::WhereConstruct::Elsewhere &ew) {
4849 if (lowerToHighLevelFIR()) {
4850 auto elsewhereOp =
4851 builder->create<hlfir::ElseWhereOp>(getCurrentLocation());
4852 builder->createBlock(&elsewhereOp.getBody());
4853 }
4854 genNestedStatement(
4855 std::get<Fortran::parser::Statement<Fortran::parser::ElsewhereStmt>>(
4856 ew.t));
4857 for (const auto &body :
4858 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t))
4859 genFIR(body);
4860 }
4861 void genFIR(const Fortran::parser::ElsewhereStmt &stmt) {
4862 if (!lowerToHighLevelFIR())
4863 implicitIterSpace.append(nullptr);
4864 }
4865 void genFIR(const Fortran::parser::EndWhereStmt &) {
4866 if (!lowerToHighLevelFIR())
4867 implicitIterSpace.shrinkStack();
4868 }
4869
4870 void genFIR(const Fortran::parser::WhereStmt &stmt) {
4871 Fortran::lower::StatementContext stmtCtx;
4872 const auto &assign = std::get<Fortran::parser::AssignmentStmt>(stmt.t);
4873 const auto *mask = Fortran::semantics::GetExpr(
4874 std::get<Fortran::parser::LogicalExpr>(stmt.t));
4875 if (lowerToHighLevelFIR()) {
4876 mlir::Location loc = getCurrentLocation();
4877 auto whereOp = builder->create<hlfir::WhereOp>(loc);
4878 builder->createBlock(&whereOp.getMaskRegion());
4879 lowerWhereMaskToHlfir(loc, mask);
4880 builder->createBlock(&whereOp.getBody());
4881 genAssignment(*assign.typedAssignment->v);
4882 builder->create<fir::FirEndOp>(loc);
4883 builder->setInsertionPointAfter(whereOp);
4884 return;
4885 }
4886 implicitIterSpace.growStack();
4887 implicitIterSpace.append(mask);
4888 genAssignment(*assign.typedAssignment->v);
4889 implicitIterSpace.shrinkStack();
4890 }
4891
4892 void genFIR(const Fortran::parser::PointerAssignmentStmt &stmt) {
4893 genAssignment(*stmt.typedAssignment->v);
4894 }
4895
4896 void genFIR(const Fortran::parser::AssignmentStmt &stmt) {
4897 genAssignment(*stmt.typedAssignment->v);
4898 }
4899
4900 void genFIR(const Fortran::parser::SyncAllStmt &stmt) {
4901 genSyncAllStatement(*this, stmt);
4902 }
4903
4904 void genFIR(const Fortran::parser::SyncImagesStmt &stmt) {
4905 genSyncImagesStatement(*this, stmt);
4906 }
4907
4908 void genFIR(const Fortran::parser::SyncMemoryStmt &stmt) {
4909 genSyncMemoryStatement(*this, stmt);
4910 }
4911
4912 void genFIR(const Fortran::parser::SyncTeamStmt &stmt) {
4913 genSyncTeamStatement(*this, stmt);
4914 }
4915
4916 void genFIR(const Fortran::parser::UnlockStmt &stmt) {
4917 genUnlockStatement(*this, stmt);
4918 }
4919
4920 void genFIR(const Fortran::parser::AssignStmt &stmt) {
4921 const Fortran::semantics::Symbol &symbol =
4922 *std::get<Fortran::parser::Name>(stmt.t).symbol;
4923 mlir::Location loc = toLocation();
4924 mlir::Value labelValue = builder->createIntegerConstant(
4925 loc, genType(symbol), std::get<Fortran::parser::Label>(stmt.t));
4926 builder->create<fir::StoreOp>(loc, labelValue, getSymbolAddress(symbol));
4927 }
4928
4929 void genFIR(const Fortran::parser::FormatStmt &) {
4930 // do nothing.
4931
4932 // FORMAT statements have no semantics. They may be lowered if used by a
4933 // data transfer statement.
4934 }
4935
4936 void genFIR(const Fortran::parser::PauseStmt &stmt) {
4937 genPauseStatement(*this, stmt);
4938 }
4939
4940 // call FAIL IMAGE in runtime
4941 void genFIR(const Fortran::parser::FailImageStmt &stmt) {
4942 genFailImageStatement(*this);
4943 }
4944
4945 // call STOP, ERROR STOP in runtime
4946 void genFIR(const Fortran::parser::StopStmt &stmt) {
4947 genStopStatement(*this, stmt);
4948 }
4949
4950 void genFIR(const Fortran::parser::ReturnStmt &stmt) {
4951 Fortran::lower::pft::FunctionLikeUnit *funit =
4952 getEval().getOwningProcedure();
4953 assert(funit && "not inside main program, function or subroutine");
4954 for (auto it = activeConstructStack.rbegin(),
4955 rend = activeConstructStack.rend();
4956 it != rend; ++it) {
4957 it->stmtCtx.finalizeAndKeep();
4958 }
4959 if (funit->isMainProgram()) {
4960 bridge.fctCtx().finalizeAndKeep();
4961 genExitRoutine();
4962 return;
4963 }
4964 mlir::Location loc = toLocation();
4965 if (stmt.v) {
4966 // Alternate return statement - If this is a subroutine where some
4967 // alternate entries have alternate returns, but the active entry point
4968 // does not, ignore the alternate return value. Otherwise, assign it
4969 // to the compiler-generated result variable.
4970 const Fortran::semantics::Symbol &symbol = funit->getSubprogramSymbol();
4971 if (Fortran::semantics::HasAlternateReturns(symbol)) {
4972 Fortran::lower::StatementContext stmtCtx;
4973 const Fortran::lower::SomeExpr *expr =
4974 Fortran::semantics::GetExpr(*stmt.v);
4975 assert(expr && "missing alternate return expression");
4976 mlir::Value altReturnIndex = builder->createConvert(
4977 loc, builder->getIndexType(), createFIRExpr(loc, expr, stmtCtx));
4978 builder->create<fir::StoreOp>(loc, altReturnIndex,
4979 getAltReturnResult(symbol));
4980 }
4981 }
4982 // Branch to the last block of the SUBROUTINE, which has the actual return.
4983 if (!funit->finalBlock) {
4984 mlir::OpBuilder::InsertPoint insPt = builder->saveInsertionPoint();
4985 Fortran::lower::setInsertionPointAfterOpenACCLoopIfInside(*builder);
4986 funit->finalBlock = builder->createBlock(&builder->getRegion());
4987 builder->restoreInsertionPoint(insPt);
4988 }
4989
4990 if (Fortran::lower::isInOpenACCLoop(*builder))
4991 Fortran::lower::genEarlyReturnInOpenACCLoop(*builder, loc);
4992 else
4993 builder->create<mlir::cf::BranchOp>(loc, funit->finalBlock);
4994 }
4995
4996 void genFIR(const Fortran::parser::CycleStmt &) {
4997 genConstructExitBranch(*getEval().controlSuccessor);
4998 }
4999 void genFIR(const Fortran::parser::ExitStmt &) {
5000 genConstructExitBranch(*getEval().controlSuccessor);
5001 }
5002 void genFIR(const Fortran::parser::GotoStmt &) {
5003 genConstructExitBranch(*getEval().controlSuccessor);
5004 }
5005
5006 // Nop statements - No code, or code is generated at the construct level.
5007 // But note that the genFIR call immediately below that wraps one of these
5008 // calls does block management, possibly starting a new block, and possibly
5009 // generating a branch to end a block. So these calls may still be required
5010 // for that functionality.
5011 void genFIR(const Fortran::parser::AssociateStmt &) {} // nop
5012 void genFIR(const Fortran::parser::BlockStmt &) {} // nop
5013 void genFIR(const Fortran::parser::CaseStmt &) {} // nop
5014 void genFIR(const Fortran::parser::ContinueStmt &) {} // nop
5015 void genFIR(const Fortran::parser::ElseIfStmt &) {} // nop
5016 void genFIR(const Fortran::parser::ElseStmt &) {} // nop
5017 void genFIR(const Fortran::parser::EndAssociateStmt &) {} // nop
5018 void genFIR(const Fortran::parser::EndBlockStmt &) {} // nop
5019 void genFIR(const Fortran::parser::EndDoStmt &) {} // nop
5020 void genFIR(const Fortran::parser::EndFunctionStmt &) {} // nop
5021 void genFIR(const Fortran::parser::EndIfStmt &) {} // nop
5022 void genFIR(const Fortran::parser::EndMpSubprogramStmt &) {} // nop
5023 void genFIR(const Fortran::parser::EndProgramStmt &) {} // nop
5024 void genFIR(const Fortran::parser::EndSelectStmt &) {} // nop
5025 void genFIR(const Fortran::parser::EndSubroutineStmt &) {} // nop
5026 void genFIR(const Fortran::parser::EntryStmt &) {} // nop
5027 void genFIR(const Fortran::parser::IfStmt &) {} // nop
5028 void genFIR(const Fortran::parser::IfThenStmt &) {} // nop
5029 void genFIR(const Fortran::parser::NonLabelDoStmt &) {} // nop
5030 void genFIR(const Fortran::parser::OmpEndLoopDirective &) {} // nop
5031 void genFIR(const Fortran::parser::SelectTypeStmt &) {} // nop
5032 void genFIR(const Fortran::parser::TypeGuardStmt &) {} // nop
5033
5034 /// Generate FIR for Evaluation \p eval.
5035 void genFIR(Fortran::lower::pft::Evaluation &eval,
5036 bool unstructuredContext = true) {
5037 // Start a new unstructured block when applicable. When transitioning
5038 // from unstructured to structured code, unstructuredContext is true,
5039 // which accounts for the possibility that the structured code could be
5040 // a target that starts a new block.
5041 if (unstructuredContext)
5042 maybeStartBlock(eval.isConstruct() && eval.lowerAsStructured()
5043 ? eval.getFirstNestedEvaluation().block
5044 : eval.block);
5045
5046 // Generate evaluation specific code. Even nop calls should usually reach
5047 // here in case they start a new block or require generation of a generic
5048 // end-of-block branch. An alternative is to add special case code
5049 // elsewhere, such as in the genFIR code for a parent construct.
5050 setCurrentEval(eval);
5051 setCurrentPosition(eval.position);
5052 eval.visit([&](const auto &stmt) { genFIR(stmt); });
5053 }
5054
5055 /// Map mlir function block arguments to the corresponding Fortran dummy
5056 /// variables. When the result is passed as a hidden argument, the Fortran
5057 /// result is also mapped. The symbol map is used to hold this mapping.
5058 void mapDummiesAndResults(Fortran::lower::pft::FunctionLikeUnit &funit,
5059 const Fortran::lower::CalleeInterface &callee) {
5060 assert(builder && "require a builder object at this point");
5061 using PassBy = Fortran::lower::CalleeInterface::PassEntityBy;
5062 auto mapPassedEntity = [&](const auto arg, bool isResult = false) {
5063 if (arg.passBy == PassBy::AddressAndLength) {
5064 if (callee.characterize().IsBindC())
5065 return;
5066 // TODO: now that fir call has some attributes regarding character
5067 // return, PassBy::AddressAndLength should be retired.
5068 mlir::Location loc = toLocation();
5069 fir::factory::CharacterExprHelper charHelp{*builder, loc};
5070 mlir::Value box =
5071 charHelp.createEmboxChar(arg.firArgument, arg.firLength);
5072 mapBlockArgToDummyOrResult(arg.entity->get(), box, isResult);
5073 } else {
5074 if (arg.entity.has_value()) {
5075 mapBlockArgToDummyOrResult(arg.entity->get(), arg.firArgument,
5076 isResult);
5077 } else {
5078 assert(funit.parentHasTupleHostAssoc() && "expect tuple argument");
5079 }
5080 }
5081 };
5082 for (const Fortran::lower::CalleeInterface::PassedEntity &arg :
5083 callee.getPassedArguments())
5084 mapPassedEntity(arg);
5085 if (lowerToHighLevelFIR() && !callee.getPassedArguments().empty()) {
5086 mlir::Value scopeOp = builder->create<fir::DummyScopeOp>(toLocation());
5087 setDummyArgsScope(scopeOp);
5088 }
5089 if (std::optional<Fortran::lower::CalleeInterface::PassedEntity>
5090 passedResult = callee.getPassedResult()) {
5091 mapPassedEntity(*passedResult, /*isResult=*/true);
5092 // FIXME: need to make sure things are OK here. addSymbol may not be OK
5093 if (funit.primaryResult &&
5094 passedResult->entity->get() != *funit.primaryResult)
5095 mapBlockArgToDummyOrResult(
5096 *funit.primaryResult, getSymbolAddress(passedResult->entity->get()),
5097 /*isResult=*/true);
5098 }
5099 }
5100
5101 /// Instantiate variable \p var and add it to the symbol map.
5102 /// See ConvertVariable.cpp.
5103 void instantiateVar(const Fortran::lower::pft::Variable &var,
5104 Fortran::lower::AggregateStoreMap &storeMap) {
5105 Fortran::lower::instantiateVariable(*this, var, localSymbols, storeMap);
5106 if (var.hasSymbol())
5107 genOpenMPSymbolProperties(*this, var);
5108 }
5109
5110 /// Where applicable, save the exception state and halting and rounding
5111 /// modes at function entry and restore them at function exits.
5112 void manageFPEnvironment(Fortran::lower::pft::FunctionLikeUnit &funit) {
5113 mlir::Location loc = toLocation();
5114 mlir::Location endLoc =
5115 toLocation(Fortran::lower::pft::stmtSourceLoc(funit.endStmt));
5116 if (funit.hasIeeeAccess) {
5117 // Subject to F18 Clause 17.1p3, 17.3p3 states: If a flag is signaling
5118 // on entry to a procedure [...], the processor will set it to quiet
5119 // on entry and restore it to signaling on return. If a flag signals
5120 // during execution of a procedure, the processor shall not set it to
5121 // quiet on return.
5122 mlir::func::FuncOp testExcept = fir::factory::getFetestexcept(*builder);
5123 mlir::func::FuncOp clearExcept = fir::factory::getFeclearexcept(*builder);
5124 mlir::func::FuncOp raiseExcept = fir::factory::getFeraiseexcept(*builder);
5125 mlir::Value ones = builder->createIntegerConstant(
5126 loc, testExcept.getFunctionType().getInput(0), -1);
5127 mlir::Value exceptSet =
5128 builder->create<fir::CallOp>(loc, testExcept, ones).getResult(0);
5129 builder->create<fir::CallOp>(loc, clearExcept, exceptSet);
5130 bridge.fctCtx().attachCleanup([=]() {
5131 builder->create<fir::CallOp>(endLoc, raiseExcept, exceptSet);
5132 });
5133 }
5134 if (funit.mayModifyHaltingMode) {
5135 // F18 Clause 17.6p1: In a procedure [...], the processor shall not
5136 // change the halting mode on entry, and on return shall ensure that
5137 // the halting mode is the same as it was on entry.
5138 mlir::func::FuncOp getExcept = fir::factory::getFegetexcept(*builder);
5139 mlir::func::FuncOp disableExcept =
5140 fir::factory::getFedisableexcept(*builder);
5141 mlir::func::FuncOp enableExcept =
5142 fir::factory::getFeenableexcept(*builder);
5143 mlir::Value exceptSet =
5144 builder->create<fir::CallOp>(loc, getExcept).getResult(0);
5145 mlir::Value ones = builder->createIntegerConstant(
5146 loc, disableExcept.getFunctionType().getInput(0), -1);
5147 bridge.fctCtx().attachCleanup([=]() {
5148 builder->create<fir::CallOp>(endLoc, disableExcept, ones);
5149 builder->create<fir::CallOp>(endLoc, enableExcept, exceptSet);
5150 });
5151 }
5152 if (funit.mayModifyRoundingMode) {
5153 // F18 Clause 17.4.5: In a procedure [...], the processor shall not
5154 // change the rounding modes on entry, and on return shall ensure that
5155 // the rounding modes are the same as they were on entry.
5156 mlir::func::FuncOp getRounding =
5157 fir::factory::getLlvmGetRounding(*builder);
5158 mlir::func::FuncOp setRounding =
5159 fir::factory::getLlvmSetRounding(*builder);
5160 mlir::Value roundingMode =
5161 builder->create<fir::CallOp>(loc, getRounding).getResult(0);
5162 bridge.fctCtx().attachCleanup([=]() {
5163 builder->create<fir::CallOp>(endLoc, setRounding, roundingMode);
5164 });
5165 }
5166 }
5167
5168 /// Start translation of a function.
5169 void startNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) {
5170 assert(!builder && "expected nullptr");
5171 bridge.fctCtx().pushScope();
5172 bridge.openAccCtx().pushScope();
5173 const Fortran::semantics::Scope &scope = funit.getScope();
5174 LLVM_DEBUG(llvm::dbgs() << "\n[bridge - startNewFunction]";
5175 if (auto *sym = scope.symbol()) llvm::dbgs() << " " << *sym;
5176 llvm::dbgs() << "\n");
5177 Fortran::lower::CalleeInterface callee(funit, *this);
5178 mlir::func::FuncOp func = callee.addEntryBlockAndMapArguments();
5179 builder =
5180 new fir::FirOpBuilder(func, bridge.getKindMap(), &mlirSymbolTable);
5181 assert(builder && "FirOpBuilder did not instantiate");
5182 builder->setFastMathFlags(bridge.getLoweringOptions().getMathOptions());
5183 builder->setInsertionPointToStart(&func.front());
5184 if (funit.parent.isA<Fortran::lower::pft::FunctionLikeUnit>()) {
5185 // Give internal linkage to internal functions. There are no name clash
5186 // risks, but giving global linkage to internal procedure will break the
5187 // static link register in shared libraries because of the system calls.
5188 // Also, it should be possible to eliminate the procedure code if all the
5189 // uses have been inlined.
5190 fir::factory::setInternalLinkage(func);
5191 } else {
5192 func.setVisibility(mlir::SymbolTable::Visibility::Public);
5193 }
5194 assert(blockId == 0 && "invalid blockId");
5195 assert(activeConstructStack.empty() && "invalid construct stack state");
5196
5197 // Manage floating point exception, halting mode, and rounding mode
5198 // settings at function entry and exit.
5199 if (!funit.isMainProgram())
5200 manageFPEnvironment(funit);
5201
5202 mapDummiesAndResults(funit, callee);
5203
5204 // Map host associated symbols from parent procedure if any.
5205 if (funit.parentHasHostAssoc())
5206 funit.parentHostAssoc().internalProcedureBindings(*this, localSymbols);
5207
5208 // Non-primary results of a function with multiple entry points.
5209 // These result values share storage with the primary result.
5210 llvm::SmallVector<Fortran::lower::pft::Variable> deferredFuncResultList;
5211
5212 // Backup actual argument for entry character results with different
5213 // lengths. It needs to be added to the non-primary results symbol before
5214 // mapSymbolAttributes is called.
5215 Fortran::lower::SymbolBox resultArg;
5216 if (std::optional<Fortran::lower::CalleeInterface::PassedEntity>
5217 passedResult = callee.getPassedResult())
5218 resultArg = lookupSymbol(passedResult->entity->get());
5219
5220 Fortran::lower::AggregateStoreMap storeMap;
5221
5222 // Map all containing submodule and module equivalences and variables, in
5223 // case they are referenced. It might be better to limit this to variables
5224 // that are actually referenced, although that is more complicated when
5225 // there are equivalenced variables.
5226 auto &scopeVariableListMap =
5227 Fortran::lower::pft::getScopeVariableListMap(funit);
5228 for (auto *scp = &scope.parent(); !scp->IsGlobal(); scp = &scp->parent())
5229 if (scp->kind() == Fortran::semantics::Scope::Kind::Module)
5230 for (const auto &var : Fortran::lower::pft::getScopeVariableList(
5231 *scp, scopeVariableListMap))
5232 if (!var.isRuntimeTypeInfoData())
5233 instantiateVar(var, storeMap);
5234
5235 // Map function equivalences and variables.
5236 mlir::Value primaryFuncResultStorage;
5237 for (const Fortran::lower::pft::Variable &var :
5238 Fortran::lower::pft::getScopeVariableList(scope)) {
5239 // Always instantiate aggregate storage blocks.
5240 if (var.isAggregateStore()) {
5241 instantiateVar(var, storeMap);
5242 continue;
5243 }
5244 const Fortran::semantics::Symbol &sym = var.getSymbol();
5245 if (funit.parentHasHostAssoc()) {
5246 // Never instantiate host associated variables, as they are already
5247 // instantiated from an argument tuple. Instead, just bind the symbol
5248 // to the host variable, which must be in the map.
5249 const Fortran::semantics::Symbol &ultimate = sym.GetUltimate();
5250 if (funit.parentHostAssoc().isAssociated(ultimate)) {
5251 copySymbolBinding(ultimate, sym);
5252 continue;
5253 }
5254 }
5255 if (!sym.IsFuncResult() || !funit.primaryResult) {
5256 instantiateVar(var, storeMap);
5257 } else if (&sym == funit.primaryResult) {
5258 instantiateVar(var, storeMap);
5259 primaryFuncResultStorage = getSymbolAddress(sym);
5260 } else {
5261 deferredFuncResultList.push_back(var);
5262 }
5263 }
5264
5265 // TODO: should use same mechanism as equivalence?
5266 // One blocking point is character entry returns that need special handling
5267 // since they are not locally allocated but come as argument. CHARACTER(*)
5268 // is not something that fits well with equivalence lowering.
5269 for (const Fortran::lower::pft::Variable &altResult :
5270 deferredFuncResultList) {
5271 Fortran::lower::StatementContext stmtCtx;
5272 if (std::optional<Fortran::lower::CalleeInterface::PassedEntity>
5273 passedResult = callee.getPassedResult()) {
5274 mapBlockArgToDummyOrResult(altResult.getSymbol(), resultArg.getAddr(),
5275 /*isResult=*/true);
5276 Fortran::lower::mapSymbolAttributes(*this, altResult, localSymbols,
5277 stmtCtx);
5278 } else {
5279 // catch cases where the allocation for the function result storage type
5280 // doesn't match the type of this symbol
5281 mlir::Value preAlloc = primaryFuncResultStorage;
5282 mlir::Type resTy = primaryFuncResultStorage.getType();
5283 mlir::Type symTy = genType(altResult);
5284 mlir::Type wrappedSymTy = fir::ReferenceType::get(symTy);
5285 if (resTy != wrappedSymTy) {
5286 // check size of the pointed to type so we can't overflow by writing
5287 // double precision to a single precision allocation, etc
5288 LLVM_ATTRIBUTE_UNUSED auto getBitWidth = [this](mlir::Type ty) {
5289 // 15.6.2.6.3: differering result types should be integer, real,
5290 // complex or logical
5291 if (auto cmplx = mlir::dyn_cast_or_null<fir::ComplexType>(ty)) {
5292 fir::KindTy kind = cmplx.getFKind();
5293 return 2 * builder->getKindMap().getRealBitsize(kind);
5294 }
5295 if (auto logical = mlir::dyn_cast_or_null<fir::LogicalType>(ty)) {
5296 fir::KindTy kind = logical.getFKind();
5297 return builder->getKindMap().getLogicalBitsize(kind);
5298 }
5299 return ty.getIntOrFloatBitWidth();
5300 };
5301 assert(getBitWidth(fir::unwrapRefType(resTy)) >= getBitWidth(symTy));
5302
5303 // convert the storage to the symbol type so that the hlfir.declare
5304 // gets the correct type for this symbol
5305 preAlloc = builder->create<fir::ConvertOp>(getCurrentLocation(),
5306 wrappedSymTy, preAlloc);
5307 }
5308
5309 Fortran::lower::mapSymbolAttributes(*this, altResult, localSymbols,
5310 stmtCtx, preAlloc);
5311 }
5312 }
5313
5314 // If this is a host procedure with host associations, then create the tuple
5315 // of pointers for passing to the internal procedures.
5316 if (!funit.getHostAssoc().empty())
5317 funit.getHostAssoc().hostProcedureBindings(*this, localSymbols);
5318
5319 // Unregister all dummy symbols, so that their cloning (e.g. for OpenMP
5320 // privatization) does not create the cloned hlfir.declare operations
5321 // with dummy_scope operands.
5322 resetRegisteredDummySymbols();
5323
5324 // Create most function blocks in advance.
5325 createEmptyBlocks(funit.evaluationList);
5326
5327 // Reinstate entry block as the current insertion point.
5328 builder->setInsertionPointToEnd(&func.front());
5329
5330 if (callee.hasAlternateReturns()) {
5331 // Create a local temp to hold the alternate return index.
5332 // Give it an integer index type and the subroutine name (for dumps).
5333 // Attach it to the subroutine symbol in the localSymbols map.
5334 // Initialize it to zero, the "fallthrough" alternate return value.
5335 const Fortran::semantics::Symbol &symbol = funit.getSubprogramSymbol();
5336 mlir::Location loc = toLocation();
5337 mlir::Type idxTy = builder->getIndexType();
5338 mlir::Value altResult =
5339 builder->createTemporary(loc, idxTy, toStringRef(symbol.name()));
5340 addSymbol(symbol, altResult);
5341 mlir::Value zero = builder->createIntegerConstant(loc, idxTy, 0);
5342 builder->create<fir::StoreOp>(loc, zero, altResult);
5343 }
5344
5345 if (Fortran::lower::pft::Evaluation *alternateEntryEval =
5346 funit.getEntryEval())
5347 genBranch(alternateEntryEval->lexicalSuccessor->block);
5348 }
5349
5350 /// Create global blocks for the current function. This eliminates the
5351 /// distinction between forward and backward targets when generating
5352 /// branches. A block is "global" if it can be the target of a GOTO or
5353 /// other source code branch. A block that can only be targeted by a
5354 /// compiler generated branch is "local". For example, a DO loop preheader
5355 /// block containing loop initialization code is global. A loop header
5356 /// block, which is the target of the loop back edge, is local. Blocks
5357 /// belong to a region. Any block within a nested region must be replaced
5358 /// with a block belonging to that region. Branches may not cross region
5359 /// boundaries.
5360 void createEmptyBlocks(
5361 std::list<Fortran::lower::pft::Evaluation> &evaluationList) {
5362 mlir::Region *region = &builder->getRegion();
5363 for (Fortran::lower::pft::Evaluation &eval : evaluationList) {
5364 if (eval.isNewBlock)
5365 eval.block = builder->createBlock(region);
5366 if (eval.isConstruct() || eval.isDirective()) {
5367 if (eval.lowerAsUnstructured()) {
5368 createEmptyBlocks(eval.getNestedEvaluations());
5369 } else if (eval.hasNestedEvaluations()) {
5370 // A structured construct that is a target starts a new block.
5371 Fortran::lower::pft::Evaluation &constructStmt =
5372 eval.getFirstNestedEvaluation();
5373 if (constructStmt.isNewBlock)
5374 constructStmt.block = builder->createBlock(region);
5375 }
5376 }
5377 }
5378 }
5379
5380 /// Return the predicate: "current block does not have a terminator branch".
5381 bool blockIsUnterminated() {
5382 mlir::Block *currentBlock = builder->getBlock();
5383 return currentBlock->empty() ||
5384 !currentBlock->back().hasTrait<mlir::OpTrait::IsTerminator>();
5385 }
5386
5387 /// Unconditionally switch code insertion to a new block.
5388 void startBlock(mlir::Block *newBlock) {
5389 assert(newBlock && "missing block");
5390 // Default termination for the current block is a fallthrough branch to
5391 // the new block.
5392 if (blockIsUnterminated())
5393 genBranch(newBlock);
5394 // Some blocks may be re/started more than once, and might not be empty.
5395 // If the new block already has (only) a terminator, set the insertion
5396 // point to the start of the block. Otherwise set it to the end.
5397 builder->setInsertionPointToStart(newBlock);
5398 if (blockIsUnterminated())
5399 builder->setInsertionPointToEnd(newBlock);
5400 }
5401
5402 /// Conditionally switch code insertion to a new block.
5403 void maybeStartBlock(mlir::Block *newBlock) {
5404 if (newBlock)
5405 startBlock(newBlock);
5406 }
5407
5408 void eraseDeadCodeAndBlocks(mlir::RewriterBase &rewriter,
5409 llvm::MutableArrayRef<mlir::Region> regions) {
5410 // WARNING: Do not add passes that can do folding or code motion here
5411 // because they might cross omp.target region boundaries, which can result
5412 // in incorrect code. Optimization passes like these must be added after
5413 // OMP early outlining has been done.
5414 (void)mlir::eraseUnreachableBlocks(rewriter, regions);
5415 (void)mlir::runRegionDCE(rewriter, regions);
5416 }
5417
5418 /// Finish translation of a function.
5419 void endNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) {
5420 setCurrentPosition(Fortran::lower::pft::stmtSourceLoc(funit.endStmt));
5421 if (funit.isMainProgram()) {
5422 bridge.openAccCtx().finalizeAndPop();
5423 bridge.fctCtx().finalizeAndPop();
5424 genExitRoutine();
5425 } else {
5426 genFIRProcedureExit(funit, funit.getSubprogramSymbol());
5427 }
5428 funit.finalBlock = nullptr;
5429 LLVM_DEBUG(llvm::dbgs() << "\n[bridge - endNewFunction";
5430 if (auto *sym = funit.scope->symbol()) llvm::dbgs()
5431 << " " << sym->name();
5432 llvm::dbgs() << "] generated IR:\n\n"
5433 << *builder->getFunction() << '\n');
5434 // Eliminate dead code as a prerequisite to calling other IR passes.
5435 // FIXME: This simplification should happen in a normal pass, not here.
5436 mlir::IRRewriter rewriter(*builder);
5437 (void)eraseDeadCodeAndBlocks(rewriter, {builder->getRegion()});
5438 delete builder;
5439 builder = nullptr;
5440 hostAssocTuple = mlir::Value{};
5441 localSymbols.clear();
5442 blockId = 0;
5443 dummyArgsScope = mlir::Value{};
5444 resetRegisteredDummySymbols();
5445 }
5446
5447 /// Helper to generate GlobalOps when the builder is not positioned in any
5448 /// region block. This is required because the FirOpBuilder assumes it is
5449 /// always positioned inside a region block when creating globals, the easiest
5450 /// way comply is to create a dummy function and to throw it afterwards.
5451 void createGlobalOutsideOfFunctionLowering(
5452 const std::function<void()> &createGlobals) {
5453 // FIXME: get rid of the bogus function context and instantiate the
5454 // globals directly into the module.
5455 mlir::MLIRContext *context = &getMLIRContext();
5456 mlir::SymbolTable *symbolTable = getMLIRSymbolTable();
5457 mlir::func::FuncOp func = fir::FirOpBuilder::createFunction(
5458 mlir::UnknownLoc::get(context), getModuleOp(),
5459 fir::NameUniquer::doGenerated("Sham"),
5460 mlir::FunctionType::get(context, std::nullopt, std::nullopt),
5461 symbolTable);
5462 func.addEntryBlock();
5463 builder = new fir::FirOpBuilder(func, bridge.getKindMap(), symbolTable);
5464 assert(builder && "FirOpBuilder did not instantiate");
5465 builder->setFastMathFlags(bridge.getLoweringOptions().getMathOptions());
5466 createGlobals();
5467 if (mlir::Region *region = func.getCallableRegion())
5468 region->dropAllReferences();
5469 func.erase();
5470 delete builder;
5471 builder = nullptr;
5472 localSymbols.clear();
5473 resetRegisteredDummySymbols();
5474 }
5475
5476 /// Instantiate the data from a BLOCK DATA unit.
5477 void lowerBlockData(Fortran::lower::pft::BlockDataUnit &bdunit) {
5478 createGlobalOutsideOfFunctionLowering([&]() {
5479 Fortran::lower::AggregateStoreMap fakeMap;
5480 for (const auto &[_, sym] : bdunit.symTab) {
5481 if (sym->has<Fortran::semantics::ObjectEntityDetails>()) {
5482 Fortran::lower::pft::Variable var(*sym, true);
5483 instantiateVar(var, fakeMap);
5484 }
5485 }
5486 });
5487 }
5488
5489 /// Create fir::Global for all the common blocks that appear in the program.
5490 void
5491 lowerCommonBlocks(const Fortran::semantics::CommonBlockList &commonBlocks) {
5492 createGlobalOutsideOfFunctionLowering(
5493 [&]() { Fortran::lower::defineCommonBlocks(*this, commonBlocks); });
5494 }
5495
5496 /// Create intrinsic module array constant definitions.
5497 void createIntrinsicModuleDefinitions(Fortran::lower::pft::Program &pft) {
5498 // The intrinsic module scope, if present, is the first scope.
5499 const Fortran::semantics::Scope *intrinsicModuleScope = nullptr;
5500 for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) {
5501 Fortran::common::visit(
5502 Fortran::common::visitors{
5503 [&](Fortran::lower::pft::FunctionLikeUnit &f) {
5504 intrinsicModuleScope = &f.getScope().parent();
5505 },
5506 [&](Fortran::lower::pft::ModuleLikeUnit &m) {
5507 intrinsicModuleScope = &m.getScope().parent();
5508 },
5509 [&](Fortran::lower::pft::BlockDataUnit &b) {},
5510 [&](Fortran::lower::pft::CompilerDirectiveUnit &d) {},
5511 [&](Fortran::lower::pft::OpenACCDirectiveUnit &d) {},
5512 },
5513 u);
5514 if (intrinsicModuleScope) {
5515 while (!intrinsicModuleScope->IsGlobal())
5516 intrinsicModuleScope = &intrinsicModuleScope->parent();
5517 intrinsicModuleScope = &intrinsicModuleScope->children().front();
5518 break;
5519 }
5520 }
5521 if (!intrinsicModuleScope || !intrinsicModuleScope->IsIntrinsicModules())
5522 return;
5523 for (const auto &scope : intrinsicModuleScope->children()) {
5524 llvm::StringRef modName = toStringRef(scope.symbol()->name());
5525 if (modName != "__fortran_ieee_exceptions")
5526 continue;
5527 for (auto &var : Fortran::lower::pft::getScopeVariableList(scope)) {
5528 const Fortran::semantics::Symbol &sym = var.getSymbol();
5529 if (sym.test(Fortran::semantics::Symbol::Flag::CompilerCreated))
5530 continue;
5531 const auto *object =
5532 sym.detailsIf<Fortran::semantics::ObjectEntityDetails>();
5533 if (object && object->IsArray() && object->init())
5534 Fortran::lower::createIntrinsicModuleGlobal(*this, var);
5535 }
5536 }
5537 }
5538
5539 /// Lower a procedure (nest).
5540 void lowerFunc(Fortran::lower::pft::FunctionLikeUnit &funit) {
5541 setCurrentPosition(funit.getStartingSourceLoc());
5542 for (int entryIndex = 0, last = funit.entryPointList.size();
5543 entryIndex < last; ++entryIndex) {
5544 funit.setActiveEntry(entryIndex);
5545 startNewFunction(funit); // the entry point for lowering this procedure
5546 for (Fortran::lower::pft::Evaluation &eval : funit.evaluationList)
5547 genFIR(eval);
5548 endNewFunction(funit);
5549 }
5550 funit.setActiveEntry(0);
5551 for (Fortran::lower::pft::ContainedUnit &unit : funit.containedUnitList)
5552 if (auto *f = std::get_if<Fortran::lower::pft::FunctionLikeUnit>(&unit))
5553 lowerFunc(*f); // internal procedure
5554 }
5555
5556 /// Lower module variable definitions to fir::globalOp and OpenMP/OpenACC
5557 /// declarative construct.
5558 void lowerModuleDeclScope(Fortran::lower::pft::ModuleLikeUnit &mod) {
5559 setCurrentPosition(mod.getStartingSourceLoc());
5560 createGlobalOutsideOfFunctionLowering([&]() {
5561 auto &scopeVariableListMap =
5562 Fortran::lower::pft::getScopeVariableListMap(mod);
5563 for (const auto &var : Fortran::lower::pft::getScopeVariableList(
5564 mod.getScope(), scopeVariableListMap)) {
5565 // Only define the variables owned by this module.
5566 const Fortran::semantics::Scope *owningScope = var.getOwningScope();
5567 if (!owningScope || mod.getScope() == *owningScope)
5568 Fortran::lower::defineModuleVariable(*this, var);
5569 }
5570 for (auto &eval : mod.evaluationList)
5571 genFIR(eval);
5572 });
5573 }
5574
5575 /// Lower functions contained in a module.
5576 void lowerMod(Fortran::lower::pft::ModuleLikeUnit &mod) {
5577 for (Fortran::lower::pft::ContainedUnit &unit : mod.containedUnitList)
5578 if (auto *f = std::get_if<Fortran::lower::pft::FunctionLikeUnit>(&unit))
5579 lowerFunc(*f);
5580 }
5581
5582 void setCurrentPosition(const Fortran::parser::CharBlock &position) {
5583 if (position != Fortran::parser::CharBlock{})
5584 currentPosition = position;
5585 }
5586
5587 /// Set current position at the location of \p parseTreeNode. Note that the
5588 /// position is updated automatically when visiting statements, but not when
5589 /// entering higher level nodes like constructs or procedures. This helper is
5590 /// intended to cover the latter cases.
5591 template <typename A>
5592 void setCurrentPositionAt(const A &parseTreeNode) {
5593 setCurrentPosition(Fortran::parser::FindSourceLocation(parseTreeNode));
5594 }
5595
5596 //===--------------------------------------------------------------------===//
5597 // Utility methods
5598 //===--------------------------------------------------------------------===//
5599
5600 /// Convert a parser CharBlock to a Location
5601 mlir::Location toLocation(const Fortran::parser::CharBlock &cb) {
5602 return genLocation(cb);
5603 }
5604
5605 mlir::Location toLocation() { return toLocation(currentPosition); }
5606 void setCurrentEval(Fortran::lower::pft::Evaluation &eval) {
5607 evalPtr = &eval;
5608 }
5609 Fortran::lower::pft::Evaluation &getEval() {
5610 assert(evalPtr);
5611 return *evalPtr;
5612 }
5613
5614 std::optional<Fortran::evaluate::Shape>
5615 getShape(const Fortran::lower::SomeExpr &expr) {
5616 return Fortran::evaluate::GetShape(foldingContext, expr);
5617 }
5618
5619 //===--------------------------------------------------------------------===//
5620 // Analysis on a nested explicit iteration space.
5621 //===--------------------------------------------------------------------===//
5622
5623 void analyzeExplicitSpace(const Fortran::parser::ConcurrentHeader &header) {
5624 explicitIterSpace.pushLevel();
5625 for (const Fortran::parser::ConcurrentControl &ctrl :
5626 std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) {
5627 const Fortran::semantics::Symbol *ctrlVar =
5628 std::get<Fortran::parser::Name>(ctrl.t).symbol;
5629 explicitIterSpace.addSymbol(ctrlVar);
5630 }
5631 if (const auto &mask =
5632 std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>(
5633 header.t);
5634 mask.has_value())
5635 analyzeExplicitSpace(*Fortran::semantics::GetExpr(*mask));
5636 }
5637 template <bool LHS = false, typename A>
5638 void analyzeExplicitSpace(const Fortran::evaluate::Expr<A> &e) {
5639 explicitIterSpace.exprBase(&e, LHS);
5640 }
5641 void analyzeExplicitSpace(const Fortran::evaluate::Assignment *assign) {
5642 auto analyzeAssign = [&](const Fortran::lower::SomeExpr &lhs,
5643 const Fortran::lower::SomeExpr &rhs) {
5644 analyzeExplicitSpace</*LHS=*/true>(lhs);
5645 analyzeExplicitSpace(rhs);
5646 };
5647 Fortran::common::visit(
5648 Fortran::common::visitors{
5649 [&](const Fortran::evaluate::ProcedureRef &procRef) {
5650 // Ensure the procRef expressions are the one being visited.
5651 assert(procRef.arguments().size() == 2);
5652 const Fortran::lower::SomeExpr *lhs =
5653 procRef.arguments()[0].value().UnwrapExpr();
5654 const Fortran::lower::SomeExpr *rhs =
5655 procRef.arguments()[1].value().UnwrapExpr();
5656 assert(lhs && rhs &&
5657 "user defined assignment arguments must be expressions");
5658 analyzeAssign(*lhs, *rhs);
5659 },
5660 [&](const auto &) { analyzeAssign(assign->lhs, assign->rhs); }},
5661 assign->u);
5662 explicitIterSpace.endAssign();
5663 }
5664 void analyzeExplicitSpace(const Fortran::parser::ForallAssignmentStmt &stmt) {
5665 Fortran::common::visit([&](const auto &s) { analyzeExplicitSpace(s); },
5666 stmt.u);
5667 }
5668 void analyzeExplicitSpace(const Fortran::parser::AssignmentStmt &s) {
5669 analyzeExplicitSpace(s.typedAssignment->v.operator->());
5670 }
5671 void analyzeExplicitSpace(const Fortran::parser::PointerAssignmentStmt &s) {
5672 analyzeExplicitSpace(s.typedAssignment->v.operator->());
5673 }
5674 void analyzeExplicitSpace(const Fortran::parser::WhereConstruct &c) {
5675 analyzeExplicitSpace(
5676 std::get<
5677 Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>(
5678 c.t)
5679 .statement);
5680 for (const Fortran::parser::WhereBodyConstruct &body :
5681 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t))
5682 analyzeExplicitSpace(body);
5683 for (const Fortran::parser::WhereConstruct::MaskedElsewhere &e :
5684 std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>(
5685 c.t))
5686 analyzeExplicitSpace(e);
5687 if (const auto &e =
5688 std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>(
5689 c.t);
5690 e.has_value())
5691 analyzeExplicitSpace(e.operator->());
5692 }
5693 void analyzeExplicitSpace(const Fortran::parser::WhereConstructStmt &ws) {
5694 const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr(
5695 std::get<Fortran::parser::LogicalExpr>(ws.t));
5696 addMaskVariable(exp);
5697 analyzeExplicitSpace(*exp);
5698 }
5699 void analyzeExplicitSpace(
5700 const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) {
5701 analyzeExplicitSpace(
5702 std::get<
5703 Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>(
5704 ew.t)
5705 .statement);
5706 for (const Fortran::parser::WhereBodyConstruct &e :
5707 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t))
5708 analyzeExplicitSpace(e);
5709 }
5710 void analyzeExplicitSpace(const Fortran::parser::WhereBodyConstruct &body) {
5711 Fortran::common::visit(
5712 Fortran::common::visitors{
5713 [&](const Fortran::common::Indirection<
5714 Fortran::parser::WhereConstruct> &wc) {
5715 analyzeExplicitSpace(wc.value());
5716 },
5717 [&](const auto &s) { analyzeExplicitSpace(s.statement); }},
5718 body.u);
5719 }
5720 void analyzeExplicitSpace(const Fortran::parser::MaskedElsewhereStmt &stmt) {
5721 const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr(
5722 std::get<Fortran::parser::LogicalExpr>(stmt.t));
5723 addMaskVariable(exp);
5724 analyzeExplicitSpace(*exp);
5725 }
5726 void
5727 analyzeExplicitSpace(const Fortran::parser::WhereConstruct::Elsewhere *ew) {
5728 for (const Fortran::parser::WhereBodyConstruct &e :
5729 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew->t))
5730 analyzeExplicitSpace(e);
5731 }
5732 void analyzeExplicitSpace(const Fortran::parser::WhereStmt &stmt) {
5733 const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr(
5734 std::get<Fortran::parser::LogicalExpr>(stmt.t));
5735 addMaskVariable(exp);
5736 analyzeExplicitSpace(*exp);
5737 const std::optional<Fortran::evaluate::Assignment> &assign =
5738 std::get<Fortran::parser::AssignmentStmt>(stmt.t).typedAssignment->v;
5739 assert(assign.has_value() && "WHERE has no statement");
5740 analyzeExplicitSpace(assign.operator->());
5741 }
5742 void analyzeExplicitSpace(const Fortran::parser::ForallStmt &forall) {
5743 analyzeExplicitSpace(
5744 std::get<
5745 Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
5746 forall.t)
5747 .value());
5748 analyzeExplicitSpace(std::get<Fortran::parser::UnlabeledStatement<
5749 Fortran::parser::ForallAssignmentStmt>>(forall.t)
5750 .statement);
5751 analyzeExplicitSpacePop();
5752 }
5753 void
5754 analyzeExplicitSpace(const Fortran::parser::ForallConstructStmt &forall) {
5755 analyzeExplicitSpace(
5756 std::get<
5757 Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>(
5758 forall.t)
5759 .value());
5760 }
5761 void analyzeExplicitSpace(const Fortran::parser::ForallConstruct &forall) {
5762 analyzeExplicitSpace(
5763 std::get<
5764 Fortran::parser::Statement<Fortran::parser::ForallConstructStmt>>(
5765 forall.t)
5766 .statement);
5767 for (const Fortran::parser::ForallBodyConstruct &s :
5768 std::get<std::list<Fortran::parser::ForallBodyConstruct>>(forall.t)) {
5769 Fortran::common::visit(
5770 Fortran::common::visitors{
5771 [&](const Fortran::common::Indirection<
5772 Fortran::parser::ForallConstruct> &b) {
5773 analyzeExplicitSpace(b.value());
5774 },
5775 [&](const Fortran::parser::WhereConstruct &w) {
5776 analyzeExplicitSpace(w);
5777 },
5778 [&](const auto &b) { analyzeExplicitSpace(b.statement); }},
5779 s.u);
5780 }
5781 analyzeExplicitSpacePop();
5782 }
5783
5784 void analyzeExplicitSpacePop() { explicitIterSpace.popLevel(); }
5785
5786 void addMaskVariable(Fortran::lower::FrontEndExpr exp) {
5787 // Note: use i8 to store bool values. This avoids round-down behavior found
5788 // with sequences of i1. That is, an array of i1 will be truncated in size
5789 // and be too small. For example, a buffer of type fir.array<7xi1> will have
5790 // 0 size.
5791 mlir::Type i64Ty = builder->getIntegerType(64);
5792 mlir::TupleType ty = fir::factory::getRaggedArrayHeaderType(*builder);
5793 mlir::Type buffTy = ty.getType(1);
5794 mlir::Type shTy = ty.getType(2);
5795 mlir::Location loc = toLocation();
5796 mlir::Value hdr = builder->createTemporary(loc, ty);
5797 // FIXME: Is there a way to create a `zeroinitializer` in LLVM-IR dialect?
5798 // For now, explicitly set lazy ragged header to all zeros.
5799 // auto nilTup = builder->createNullConstant(loc, ty);
5800 // builder->create<fir::StoreOp>(loc, nilTup, hdr);
5801 mlir::Type i32Ty = builder->getIntegerType(32);
5802 mlir::Value zero = builder->createIntegerConstant(loc, i32Ty, 0);
5803 mlir::Value zero64 = builder->createIntegerConstant(loc, i64Ty, 0);
5804 mlir::Value flags = builder->create<fir::CoordinateOp>(
5805 loc, builder->getRefType(i64Ty), hdr, zero);
5806 builder->create<fir::StoreOp>(loc, zero64, flags);
5807 mlir::Value one = builder->createIntegerConstant(loc, i32Ty, 1);
5808 mlir::Value nullPtr1 = builder->createNullConstant(loc, buffTy);
5809 mlir::Value var = builder->create<fir::CoordinateOp>(
5810 loc, builder->getRefType(buffTy), hdr, one);
5811 builder->create<fir::StoreOp>(loc, nullPtr1, var);
5812 mlir::Value two = builder->createIntegerConstant(loc, i32Ty, 2);
5813 mlir::Value nullPtr2 = builder->createNullConstant(loc, shTy);
5814 mlir::Value shape = builder->create<fir::CoordinateOp>(
5815 loc, builder->getRefType(shTy), hdr, two);
5816 builder->create<fir::StoreOp>(loc, nullPtr2, shape);
5817 implicitIterSpace.addMaskVariable(exp, var, shape, hdr);
5818 explicitIterSpace.outermostContext().attachCleanup(
5819 [builder = this->builder, hdr, loc]() {
5820 fir::runtime::genRaggedArrayDeallocate(loc, *builder, hdr);
5821 });
5822 }
5823
5824 void createRuntimeTypeInfoGlobals() {}
5825
5826 bool lowerToHighLevelFIR() const {
5827 return bridge.getLoweringOptions().getLowerToHighLevelFIR();
5828 }
5829
5830 // Returns the mangling prefix for the given constant expression.
5831 std::string getConstantExprManglePrefix(mlir::Location loc,
5832 const Fortran::lower::SomeExpr &expr,
5833 mlir::Type eleTy) {
5834 return Fortran::common::visit(
5835 [&](const auto &x) -> std::string {
5836 using T = std::decay_t<decltype(x)>;
5837 if constexpr (Fortran::common::HasMember<
5838 T, Fortran::lower::CategoryExpression>) {
5839 if constexpr (T::Result::category ==
5840 Fortran::common::TypeCategory::Derived) {
5841 if (const auto *constant =
5842 std::get_if<Fortran::evaluate::Constant<
5843 Fortran::evaluate::SomeDerived>>(&x.u))
5844 return Fortran::lower::mangle::mangleArrayLiteral(eleTy,
5845 *constant);
5846 fir::emitFatalError(loc,
5847 "non a constant derived type expression");
5848 } else {
5849 return Fortran::common::visit(
5850 [&](const auto &someKind) -> std::string {
5851 using T = std::decay_t<decltype(someKind)>;
5852 using TK = Fortran::evaluate::Type<T::Result::category,
5853 T::Result::kind>;
5854 if (const auto *constant =
5855 std::get_if<Fortran::evaluate::Constant<TK>>(
5856 &someKind.u)) {
5857 return Fortran::lower::mangle::mangleArrayLiteral(
5858 nullptr, *constant);
5859 }
5860 fir::emitFatalError(
5861 loc, "not a Fortran::evaluate::Constant<T> expression");
5862 return {};
5863 },
5864 x.u);
5865 }
5866 } else {
5867 fir::emitFatalError(loc, "unexpected expression");
5868 }
5869 },
5870 expr.u);
5871 }
5872
5873 /// Performing OpenACC lowering action that were deferred to the end of
5874 /// lowering.
5875 void finalizeOpenACCLowering() {
5876 Fortran::lower::finalizeOpenACCRoutineAttachment(getModuleOp(),
5877 accRoutineInfos);
5878 }
5879
5880 /// Performing OpenMP lowering actions that were deferred to the end of
5881 /// lowering.
5882 void finalizeOpenMPLowering(
5883 const Fortran::semantics::Symbol *globalOmpRequiresSymbol) {
5884 if (!ompDeferredDeclareTarget.empty()) {
5885 bool deferredDeviceFuncFound =
5886 Fortran::lower::markOpenMPDeferredDeclareTargetFunctions(
5887 getModuleOp().getOperation(), ompDeferredDeclareTarget, *this);
5888 ompDeviceCodeFound = ompDeviceCodeFound || deferredDeviceFuncFound;
5889 }
5890
5891 // Set the module attribute related to OpenMP requires directives
5892 if (ompDeviceCodeFound)
5893 Fortran::lower::genOpenMPRequires(getModuleOp().getOperation(),
5894 globalOmpRequiresSymbol);
5895 }
5896
5897 /// Record fir.dummy_scope operation for this function.
5898 /// It will be used to set dummy_scope operand of the hlfir.declare
5899 /// operations.
5900 void setDummyArgsScope(mlir::Value val) {
5901 assert(!dummyArgsScope && val);
5902 dummyArgsScope = val;
5903 }
5904
5905 /// Record the given symbol as a dummy argument of this function.
5906 void registerDummySymbol(Fortran::semantics::SymbolRef symRef) {
5907 auto *sym = &*symRef;
5908 registeredDummySymbols.insert(sym);
5909 }
5910
5911 /// Reset all registered dummy symbols.
5912 void resetRegisteredDummySymbols() { registeredDummySymbols.clear(); }
5913
5914 //===--------------------------------------------------------------------===//
5915
5916 Fortran::lower::LoweringBridge &bridge;
5917 Fortran::evaluate::FoldingContext foldingContext;
5918 fir::FirOpBuilder *builder = nullptr;
5919 Fortran::lower::pft::Evaluation *evalPtr = nullptr;
5920 Fortran::lower::SymMap localSymbols;
5921 Fortran::parser::CharBlock currentPosition;
5922 TypeInfoConverter typeInfoConverter;
5923
5924 // Stack to manage object deallocation and finalization at construct exits.
5925 llvm::SmallVector<ConstructContext> activeConstructStack;
5926
5927 /// BLOCK name mangling component map
5928 int blockId = 0;
5929 Fortran::lower::mangle::ScopeBlockIdMap scopeBlockIdMap;
5930
5931 /// FORALL statement/construct context
5932 Fortran::lower::ExplicitIterSpace explicitIterSpace;
5933
5934 /// WHERE statement/construct mask expression stack
5935 Fortran::lower::ImplicitIterSpace implicitIterSpace;
5936
5937 /// Tuple of host associated variables
5938 mlir::Value hostAssocTuple;
5939
5940 /// Value of fir.dummy_scope operation for this function.
5941 mlir::Value dummyArgsScope;
5942
5943 /// A set of dummy argument symbols for this function.
5944 /// The set is only preserved during the instatiation
5945 /// of variables for this function.
5946 llvm::SmallPtrSet<const Fortran::semantics::Symbol *, 16>
5947 registeredDummySymbols;
5948
5949 /// A map of unique names for constant expressions.
5950 /// The names are used for representing the constant expressions
5951 /// with global constant initialized objects.
5952 /// The names are usually prefixed by a mangling string based
5953 /// on the element type of the constant expression, but the element
5954 /// type is not used as a key into the map (so the assumption is that
5955 /// the equivalent constant expressions are prefixed using the same
5956 /// element type).
5957 llvm::DenseMap<const Fortran::lower::SomeExpr *, std::string> literalNamesMap;
5958
5959 /// Storage for Constant expressions used as keys for literalNamesMap.
5960 llvm::SmallVector<std::unique_ptr<Fortran::lower::SomeExpr>>
5961 literalExprsStorage;
5962
5963 /// A counter for uniquing names in `literalNamesMap`.
5964 std::uint64_t uniqueLitId = 0;
5965
5966 /// Deferred OpenACC routine attachment.
5967 Fortran::lower::AccRoutineInfoMappingList accRoutineInfos;
5968
5969 /// Whether an OpenMP target region or declare target function/subroutine
5970 /// intended for device offloading has been detected
5971 bool ompDeviceCodeFound = false;
5972
5973 /// Keeps track of symbols defined as declare target that could not be
5974 /// processed at the time of lowering the declare target construct, such
5975 /// as certain cases where interfaces are declared but not defined within
5976 /// a module.
5977 llvm::SmallVector<Fortran::lower::OMPDeferredDeclareTargetInfo>
5978 ompDeferredDeclareTarget;
5979
5980 const Fortran::lower::ExprToValueMap *exprValueOverrides{nullptr};
5981
5982 /// Stack of derived type under construction to avoid infinite loops when
5983 /// dealing with recursive derived types. This is held in the bridge because
5984 /// the state needs to be maintained between data and function type lowering
5985 /// utilities to deal with procedure pointer components whose arguments have
5986 /// the type of the containing derived type.
5987 Fortran::lower::TypeConstructionStack typeConstructionStack;
5988 /// MLIR symbol table of the fir.global/func.func operations. Note that it is
5989 /// not guaranteed to contain all operations of the ModuleOp with Symbol
5990 /// attribute since mlirSymbolTable must pro-actively be maintained when
5991 /// new Symbol operations are created.
5992 mlir::SymbolTable mlirSymbolTable;
5993 };
5994
5995 } // namespace
5996
5997 Fortran::evaluate::FoldingContext
5998 Fortran::lower::LoweringBridge::createFoldingContext() {
5999 return {getDefaultKinds(), getIntrinsicTable(), getTargetCharacteristics(),
6000 getLanguageFeatures(), tempNames};
6001 }
6002
6003 void Fortran::lower::LoweringBridge::lower(
6004 const Fortran::parser::Program &prg,
6005 const Fortran::semantics::SemanticsContext &semanticsContext) {
6006 std::unique_ptr<Fortran::lower::pft::Program> pft =
6007 Fortran::lower::createPFT(prg, semanticsContext);
6008 if (dumpBeforeFir)
6009 Fortran::lower::dumpPFT(llvm::errs(), *pft);
6010 FirConverter converter{*this};
6011 converter.run(*pft);
6012 }
6013
6014 void Fortran::lower::LoweringBridge::parseSourceFile(llvm::SourceMgr &srcMgr) {
6015 mlir::OwningOpRef<mlir::ModuleOp> owningRef =
6016 mlir::parseSourceFile<mlir::ModuleOp>(srcMgr, &context);
6017 module.reset(new mlir::ModuleOp(owningRef.get().getOperation()));
6018 owningRef.release();
6019 }
6020
6021 Fortran::lower::LoweringBridge::LoweringBridge(
6022 mlir::MLIRContext &context,
6023 Fortran::semantics::SemanticsContext &semanticsContext,
6024 const Fortran::common::IntrinsicTypeDefaultKinds &defaultKinds,
6025 const Fortran::evaluate::IntrinsicProcTable &intrinsics,
6026 const Fortran::evaluate::TargetCharacteristics &targetCharacteristics,
6027 const Fortran::parser::AllCookedSources &cooked, llvm::StringRef triple,
6028 fir::KindMapping &kindMap,
6029 const Fortran::lower::LoweringOptions &loweringOptions,
6030 const std::vector<Fortran::lower::EnvironmentDefault> &envDefaults,
6031 const Fortran::common::LanguageFeatureControl &languageFeatures,
6032 const llvm::TargetMachine &targetMachine, const llvm::StringRef tuneCPU)
6033 : semanticsContext{semanticsContext}, defaultKinds{defaultKinds},
6034 intrinsics{intrinsics}, targetCharacteristics{targetCharacteristics},
6035 cooked{&cooked}, context{context}, kindMap{kindMap},
6036 loweringOptions{loweringOptions}, envDefaults{envDefaults},
6037 languageFeatures{languageFeatures} {
6038 // Register the diagnostic handler.
6039 context.getDiagEngine().registerHandler([](mlir::Diagnostic &diag) {
6040 llvm::raw_ostream &os = llvm::errs();
6041 switch (diag.getSeverity()) {
6042 case mlir::DiagnosticSeverity::Error:
6043 os << "error: ";
6044 break;
6045 case mlir::DiagnosticSeverity::Remark:
6046 os << "info: ";
6047 break;
6048 case mlir::DiagnosticSeverity::Warning:
6049 os << "warning: ";
6050 break;
6051 default:
6052 break;
6053 }
6054 if (!mlir::isa<mlir::UnknownLoc>(diag.getLocation()))
6055 os << diag.getLocation() << ": ";
6056 os << diag << '\n';
6057 os.flush();
6058 return mlir::success();
6059 });
6060
6061 auto getPathLocation = [&semanticsContext, &context]() -> mlir::Location {
6062 std::optional<std::string> path;
6063 const auto &allSources{semanticsContext.allCookedSources().allSources()};
6064 if (auto initial{allSources.GetFirstFileProvenance()};
6065 initial && !initial->empty()) {
6066 if (const auto *sourceFile{allSources.GetSourceFile(initial->start())}) {
6067 path = sourceFile->path();
6068 }
6069 }
6070
6071 if (path.has_value()) {
6072 llvm::SmallString<256> curPath(*path);
6073 llvm::sys::fs::make_absolute(curPath);
6074 llvm::sys::path::remove_dots(curPath);
6075 return mlir::FileLineColLoc::get(&context, curPath.str(), /*line=*/0,
6076 /*col=*/0);
6077 } else {
6078 return mlir::UnknownLoc::get(&context);
6079 }
6080 };
6081
6082 // Create the module and attach the attributes.
6083 module = std::make_unique<mlir::ModuleOp>(
6084 mlir::ModuleOp::create(getPathLocation()));
6085 assert(module.get() && "module was not created");
6086 fir::setTargetTriple(*module.get(), triple);
6087 fir::setKindMapping(*module.get(), kindMap);
6088 fir::setTargetCPU(*module.get(), targetMachine.getTargetCPU());
6089 fir::setTuneCPU(*module.get(), tuneCPU);
6090 fir::setTargetFeatures(*module.get(), targetMachine.getTargetFeatureString());
6091 fir::support::setMLIRDataLayout(*module.get(),
6092 targetMachine.createDataLayout());
6093 }
6094
6095 void Fortran::lower::genCleanUpInRegionIfAny(
6096 mlir::Location loc, fir::FirOpBuilder &builder, mlir::Region &region,
6097 Fortran::lower::StatementContext &context) {
6098 if (!context.hasCode())
6099 return;
6100 mlir::OpBuilder::InsertPoint insertPt = builder.saveInsertionPoint();
6101 if (region.empty())
6102 builder.createBlock(&region);
6103 else
6104 builder.setInsertionPointToEnd(&region.front());
6105 context.finalizeAndPop();
6106 hlfir::YieldOp::ensureTerminator(region, builder, loc);
6107 builder.restoreInsertionPoint(insertPt);
6108 }