xref: /llvm-project/flang/lib/Lower/PFTBuilder.cpp (revision 93129ca8d1cf618390a16e5d4315d0fd15170c51)
1 //===-- PFTBuilder.cpp ----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "flang/Lower/PFTBuilder.h"
10 #include "flang/Lower/IntervalSet.h"
11 #include "flang/Lower/Support/Utils.h"
12 #include "flang/Parser/dump-parse-tree.h"
13 #include "flang/Parser/parse-tree-visitor.h"
14 #include "flang/Semantics/semantics.h"
15 #include "flang/Semantics/tools.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/IntervalMap.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 
21 #define DEBUG_TYPE "flang-pft"
22 
23 static llvm::cl::opt<bool> clDisableStructuredFir(
24     "no-structured-fir", llvm::cl::desc("disable generation of structured FIR"),
25     llvm::cl::init(false), llvm::cl::Hidden);
26 
27 using namespace Fortran;
28 
29 namespace {
30 /// Helpers to unveil parser node inside Fortran::parser::Statement<>,
31 /// Fortran::parser::UnlabeledStatement, and Fortran::common::Indirection<>
32 template <typename A>
33 struct RemoveIndirectionHelper {
34   using Type = A;
35 };
36 template <typename A>
37 struct RemoveIndirectionHelper<common::Indirection<A>> {
38   using Type = A;
39 };
40 
41 template <typename A>
42 struct UnwrapStmt {
43   static constexpr bool isStmt{false};
44 };
45 template <typename A>
46 struct UnwrapStmt<parser::Statement<A>> {
47   static constexpr bool isStmt{true};
48   using Type = typename RemoveIndirectionHelper<A>::Type;
49   constexpr UnwrapStmt(const parser::Statement<A> &a)
50       : unwrapped{removeIndirection(a.statement)}, position{a.source},
51         label{a.label} {}
52   const Type &unwrapped;
53   parser::CharBlock position;
54   std::optional<parser::Label> label;
55 };
56 template <typename A>
57 struct UnwrapStmt<parser::UnlabeledStatement<A>> {
58   static constexpr bool isStmt{true};
59   using Type = typename RemoveIndirectionHelper<A>::Type;
60   constexpr UnwrapStmt(const parser::UnlabeledStatement<A> &a)
61       : unwrapped{removeIndirection(a.statement)}, position{a.source} {}
62   const Type &unwrapped;
63   parser::CharBlock position;
64   std::optional<parser::Label> label;
65 };
66 
67 #ifndef NDEBUG
68 void dumpScope(const semantics::Scope *scope, int depth = -1);
69 #endif
70 
71 /// The instantiation of a parse tree visitor (Pre and Post) is extremely
72 /// expensive in terms of compile and link time.  So one goal here is to
73 /// limit the bridge to one such instantiation.
74 class PFTBuilder {
75 public:
76   PFTBuilder(const semantics::SemanticsContext &semanticsContext)
77       : pgm{std::make_unique<lower::pft::Program>(
78             semanticsContext.GetCommonBlocks())},
79         semanticsContext{semanticsContext} {
80     lower::pft::PftNode pftRoot{*pgm.get()};
81     pftParentStack.push_back(pftRoot);
82   }
83 
84   /// Get the result
85   std::unique_ptr<lower::pft::Program> result() { return std::move(pgm); }
86 
87   template <typename A>
88   constexpr bool Pre(const A &a) {
89     if constexpr (lower::pft::isFunctionLike<A>) {
90       return enterFunction(a, semanticsContext);
91     } else if constexpr (lower::pft::isConstruct<A> ||
92                          lower::pft::isDirective<A>) {
93       return enterConstructOrDirective(a);
94     } else if constexpr (UnwrapStmt<A>::isStmt) {
95       using T = typename UnwrapStmt<A>::Type;
96       // Node "a" being visited has one of the following types:
97       // Statement<T>, Statement<Indirection<T>>, UnlabeledStatement<T>,
98       // or UnlabeledStatement<Indirection<T>>
99       auto stmt{UnwrapStmt<A>(a)};
100       if constexpr (lower::pft::isConstructStmt<T> ||
101                     lower::pft::isOtherStmt<T>) {
102         addEvaluation(lower::pft::Evaluation{
103             stmt.unwrapped, pftParentStack.back(), stmt.position, stmt.label});
104         return false;
105       } else if constexpr (std::is_same_v<T, parser::ActionStmt>) {
106         return std::visit(
107             common::visitors{
108                 [&](const common::Indirection<parser::IfStmt> &x) {
109                   convertIfStmt(x.value(), stmt.position, stmt.label);
110                   return false;
111                 },
112                 [&](const auto &x) {
113                   addEvaluation(lower::pft::Evaluation{
114                       removeIndirection(x), pftParentStack.back(),
115                       stmt.position, stmt.label});
116                   return true;
117                 },
118             },
119             stmt.unwrapped.u);
120       }
121     }
122     return true;
123   }
124 
125   /// Convert an IfStmt into an IfConstruct, retaining the IfStmt as the
126   /// first statement of the construct.
127   void convertIfStmt(const parser::IfStmt &ifStmt, parser::CharBlock position,
128                      std::optional<parser::Label> label) {
129     // Generate a skeleton IfConstruct parse node.  Its components are never
130     // referenced.  The actual components are available via the IfConstruct
131     // evaluation's nested evaluationList, with the ifStmt in the position of
132     // the otherwise normal IfThenStmt.  Caution: All other PFT nodes reference
133     // front end generated parse nodes; this is an exceptional case.
134     static const auto ifConstruct = parser::IfConstruct{
135         parser::Statement<parser::IfThenStmt>{
136             std::nullopt,
137             parser::IfThenStmt{
138                 std::optional<parser::Name>{},
139                 parser::ScalarLogicalExpr{parser::LogicalExpr{parser::Expr{
140                     parser::LiteralConstant{parser::LogicalLiteralConstant{
141                         false, std::optional<parser::KindParam>{}}}}}}}},
142         parser::Block{}, std::list<parser::IfConstruct::ElseIfBlock>{},
143         std::optional<parser::IfConstruct::ElseBlock>{},
144         parser::Statement<parser::EndIfStmt>{std::nullopt,
145                                              parser::EndIfStmt{std::nullopt}}};
146     enterConstructOrDirective(ifConstruct);
147     addEvaluation(
148         lower::pft::Evaluation{ifStmt, pftParentStack.back(), position, label});
149     Pre(std::get<parser::UnlabeledStatement<parser::ActionStmt>>(ifStmt.t));
150     static const auto endIfStmt = parser::EndIfStmt{std::nullopt};
151     addEvaluation(
152         lower::pft::Evaluation{endIfStmt, pftParentStack.back(), {}, {}});
153     exitConstructOrDirective();
154   }
155 
156   template <typename A>
157   constexpr void Post(const A &) {
158     if constexpr (lower::pft::isFunctionLike<A>) {
159       exitFunction();
160     } else if constexpr (lower::pft::isConstruct<A> ||
161                          lower::pft::isDirective<A>) {
162       exitConstructOrDirective();
163     }
164   }
165 
166   // Module like
167   bool Pre(const parser::Module &node) { return enterModule(node); }
168   bool Pre(const parser::Submodule &node) { return enterModule(node); }
169 
170   void Post(const parser::Module &) { exitModule(); }
171   void Post(const parser::Submodule &) { exitModule(); }
172 
173   // Block data
174   bool Pre(const parser::BlockData &node) {
175     addUnit(lower::pft::BlockDataUnit{node, pftParentStack.back(),
176                                       semanticsContext});
177     return false;
178   }
179 
180   // Get rid of production wrapper
181   bool Pre(const parser::Statement<parser::ForallAssignmentStmt> &statement) {
182     addEvaluation(std::visit(
183         [&](const auto &x) {
184           return lower::pft::Evaluation{x, pftParentStack.back(),
185                                         statement.source, statement.label};
186         },
187         statement.statement.u));
188     return false;
189   }
190   bool Pre(const parser::WhereBodyConstruct &whereBody) {
191     return std::visit(
192         common::visitors{
193             [&](const parser::Statement<parser::AssignmentStmt> &stmt) {
194               // Not caught as other AssignmentStmt because it is not
195               // wrapped in a parser::ActionStmt.
196               addEvaluation(lower::pft::Evaluation{stmt.statement,
197                                                    pftParentStack.back(),
198                                                    stmt.source, stmt.label});
199               return false;
200             },
201             [&](const auto &) { return true; },
202         },
203         whereBody.u);
204   }
205 
206   // CompilerDirective have special handling in case they are top level
207   // directives (i.e. they do not belong to a ProgramUnit).
208   bool Pre(const parser::CompilerDirective &directive) {
209     assert(pftParentStack.size() > 0 &&
210            "At least the Program must be a parent");
211     if (pftParentStack.back().isA<lower::pft::Program>()) {
212       addUnit(
213           lower::pft::CompilerDirectiveUnit(directive, pftParentStack.back()));
214       return false;
215     }
216     return enterConstructOrDirective(directive);
217   }
218 
219 private:
220   /// Initialize a new module-like unit and make it the builder's focus.
221   template <typename A>
222   bool enterModule(const A &mod) {
223     Fortran::lower::pft::ModuleLikeUnit &unit =
224         addUnit(lower::pft::ModuleLikeUnit{mod, pftParentStack.back()});
225     functionList = &unit.nestedFunctions;
226     pushEvaluationList(&unit.evaluationList);
227     pftParentStack.emplace_back(unit);
228     LLVM_DEBUG(dumpScope(&unit.getScope()));
229     return true;
230   }
231 
232   void exitModule() {
233     if (!evaluationListStack.empty())
234       popEvaluationList();
235     pftParentStack.pop_back();
236     resetFunctionState();
237   }
238 
239   /// Add the end statement Evaluation of a sub/program to the PFT.
240   /// There may be intervening internal subprogram definitions between
241   /// prior statements and this end statement.
242   void endFunctionBody() {
243     if (evaluationListStack.empty())
244       return;
245     auto evaluationList = evaluationListStack.back();
246     if (evaluationList->empty() || !evaluationList->back().isEndStmt()) {
247       const auto &endStmt =
248           pftParentStack.back().get<lower::pft::FunctionLikeUnit>().endStmt;
249       endStmt.visit(common::visitors{
250           [&](const parser::Statement<parser::EndProgramStmt> &s) {
251             addEvaluation(lower::pft::Evaluation{
252                 s.statement, pftParentStack.back(), s.source, s.label});
253           },
254           [&](const parser::Statement<parser::EndFunctionStmt> &s) {
255             addEvaluation(lower::pft::Evaluation{
256                 s.statement, pftParentStack.back(), s.source, s.label});
257           },
258           [&](const parser::Statement<parser::EndSubroutineStmt> &s) {
259             addEvaluation(lower::pft::Evaluation{
260                 s.statement, pftParentStack.back(), s.source, s.label});
261           },
262           [&](const parser::Statement<parser::EndMpSubprogramStmt> &s) {
263             addEvaluation(lower::pft::Evaluation{
264                 s.statement, pftParentStack.back(), s.source, s.label});
265           },
266           [&](const auto &s) {
267             llvm::report_fatal_error("missing end statement or unexpected "
268                                      "begin statement reference");
269           },
270       });
271     }
272     lastLexicalEvaluation = nullptr;
273   }
274 
275   /// Pop the ModuleLikeUnit evaluationList when entering the first module
276   /// procedure.
277   void cleanModuleEvaluationList() {
278     if (evaluationListStack.empty())
279       return;
280     if (pftParentStack.back().isA<lower::pft::ModuleLikeUnit>())
281       popEvaluationList();
282   }
283 
284   /// Initialize a new function-like unit and make it the builder's focus.
285   template <typename A>
286   bool enterFunction(const A &func,
287                      const semantics::SemanticsContext &semanticsContext) {
288     cleanModuleEvaluationList();
289     endFunctionBody(); // enclosing host subprogram body, if any
290     Fortran::lower::pft::FunctionLikeUnit &unit =
291         addFunction(lower::pft::FunctionLikeUnit{func, pftParentStack.back(),
292                                                  semanticsContext});
293     labelEvaluationMap = &unit.labelEvaluationMap;
294     assignSymbolLabelMap = &unit.assignSymbolLabelMap;
295     functionList = &unit.nestedFunctions;
296     pushEvaluationList(&unit.evaluationList);
297     pftParentStack.emplace_back(unit);
298     LLVM_DEBUG(dumpScope(&unit.getScope()));
299     return true;
300   }
301 
302   void exitFunction() {
303     rewriteIfGotos();
304     endFunctionBody();
305     analyzeBranches(nullptr, *evaluationListStack.back()); // add branch links
306     processEntryPoints();
307     popEvaluationList();
308     labelEvaluationMap = nullptr;
309     assignSymbolLabelMap = nullptr;
310     pftParentStack.pop_back();
311     resetFunctionState();
312   }
313 
314   /// Initialize a new construct or directive and make it the builder's focus.
315   template <typename A>
316   bool enterConstructOrDirective(const A &constructOrDirective) {
317     Fortran::lower::pft::Evaluation &eval = addEvaluation(
318         lower::pft::Evaluation{constructOrDirective, pftParentStack.back()});
319     eval.evaluationList.reset(new lower::pft::EvaluationList);
320     pushEvaluationList(eval.evaluationList.get());
321     pftParentStack.emplace_back(eval);
322     constructAndDirectiveStack.emplace_back(&eval);
323     return true;
324   }
325 
326   void exitConstructOrDirective() {
327     rewriteIfGotos();
328     auto *eval = constructAndDirectiveStack.back();
329     if (eval->isExecutableDirective()) {
330       // A construct at the end of an (unstructured) OpenACC or OpenMP
331       // construct region must have an exit target inside the region.
332       Fortran::lower::pft::EvaluationList &evaluationList =
333           *eval->evaluationList;
334       if (!evaluationList.empty() && evaluationList.back().isConstruct()) {
335         static const parser::ContinueStmt exitTarget{};
336         addEvaluation(
337             lower::pft::Evaluation{exitTarget, pftParentStack.back(), {}, {}});
338       }
339     }
340     popEvaluationList();
341     pftParentStack.pop_back();
342     constructAndDirectiveStack.pop_back();
343   }
344 
345   /// Reset function state to that of an enclosing host function.
346   void resetFunctionState() {
347     if (!pftParentStack.empty()) {
348       pftParentStack.back().visit(common::visitors{
349           [&](lower::pft::FunctionLikeUnit &p) {
350             functionList = &p.nestedFunctions;
351             labelEvaluationMap = &p.labelEvaluationMap;
352             assignSymbolLabelMap = &p.assignSymbolLabelMap;
353           },
354           [&](lower::pft::ModuleLikeUnit &p) {
355             functionList = &p.nestedFunctions;
356           },
357           [&](auto &) { functionList = nullptr; },
358       });
359     }
360   }
361 
362   template <typename A>
363   A &addUnit(A &&unit) {
364     pgm->getUnits().emplace_back(std::move(unit));
365     return std::get<A>(pgm->getUnits().back());
366   }
367 
368   template <typename A>
369   A &addFunction(A &&func) {
370     if (functionList) {
371       functionList->emplace_back(std::move(func));
372       return functionList->back();
373     }
374     return addUnit(std::move(func));
375   }
376 
377   // ActionStmt has a couple of non-conforming cases, explicitly handled here.
378   // The other cases use an Indirection, which are discarded in the PFT.
379   lower::pft::Evaluation
380   makeEvaluationAction(const parser::ActionStmt &statement,
381                        parser::CharBlock position,
382                        std::optional<parser::Label> label) {
383     return std::visit(
384         common::visitors{
385             [&](const auto &x) {
386               return lower::pft::Evaluation{
387                   removeIndirection(x), pftParentStack.back(), position, label};
388             },
389         },
390         statement.u);
391   }
392 
393   /// Append an Evaluation to the end of the current list.
394   lower::pft::Evaluation &addEvaluation(lower::pft::Evaluation &&eval) {
395     assert(functionList && "not in a function");
396     assert(!evaluationListStack.empty() && "empty evaluation list stack");
397     if (!constructAndDirectiveStack.empty())
398       eval.parentConstruct = constructAndDirectiveStack.back();
399     auto &entryPointList = eval.getOwningProcedure()->entryPointList;
400     evaluationListStack.back()->emplace_back(std::move(eval));
401     lower::pft::Evaluation *p = &evaluationListStack.back()->back();
402     if (p->isActionStmt() || p->isConstructStmt() || p->isEndStmt() ||
403         p->isExecutableDirective()) {
404       if (lastLexicalEvaluation) {
405         lastLexicalEvaluation->lexicalSuccessor = p;
406         p->printIndex = lastLexicalEvaluation->printIndex + 1;
407       } else {
408         p->printIndex = 1;
409       }
410       lastLexicalEvaluation = p;
411       for (std::size_t entryIndex = entryPointList.size() - 1;
412            entryIndex && !entryPointList[entryIndex].second->lexicalSuccessor;
413            --entryIndex)
414         // Link to the entry's first executable statement.
415         entryPointList[entryIndex].second->lexicalSuccessor = p;
416     } else if (const auto *entryStmt = p->getIf<parser::EntryStmt>()) {
417       const semantics::Symbol *sym =
418           std::get<parser::Name>(entryStmt->t).symbol;
419       if (auto *details = sym->detailsIf<semantics::GenericDetails>())
420         sym = details->specific();
421       assert(sym->has<semantics::SubprogramDetails>() &&
422              "entry must be a subprogram");
423       entryPointList.push_back(std::pair{sym, p});
424     }
425     if (p->label.has_value())
426       labelEvaluationMap->try_emplace(*p->label, p);
427     return evaluationListStack.back()->back();
428   }
429 
430   /// push a new list on the stack of Evaluation lists
431   void pushEvaluationList(lower::pft::EvaluationList *evaluationList) {
432     assert(functionList && "not in a function");
433     assert(evaluationList && evaluationList->empty() &&
434            "evaluation list isn't correct");
435     evaluationListStack.emplace_back(evaluationList);
436   }
437 
438   /// pop the current list and return to the last Evaluation list
439   void popEvaluationList() {
440     assert(functionList && "not in a function");
441     evaluationListStack.pop_back();
442   }
443 
444   /// Rewrite IfConstructs containing a GotoStmt or CycleStmt to eliminate an
445   /// unstructured branch and a trivial basic block.  The pre-branch-analysis
446   /// code:
447   ///
448   ///       <<IfConstruct>>
449   ///         1 If[Then]Stmt: if(cond) goto L
450   ///         2 GotoStmt: goto L
451   ///         3 EndIfStmt
452   ///       <<End IfConstruct>>
453   ///       4 Statement: ...
454   ///       5 Statement: ...
455   ///       6 Statement: L ...
456   ///
457   /// becomes:
458   ///
459   ///       <<IfConstruct>>
460   ///         1 If[Then]Stmt [negate]: if(cond) goto L
461   ///         4 Statement: ...
462   ///         5 Statement: ...
463   ///         3 EndIfStmt
464   ///       <<End IfConstruct>>
465   ///       6 Statement: L ...
466   ///
467   /// The If[Then]Stmt condition is implicitly negated.  It is not modified
468   /// in the PFT.  It must be negated when generating FIR.  The GotoStmt or
469   /// CycleStmt is deleted.
470   ///
471   /// The transformation is only valid for forward branch targets at the same
472   /// construct nesting level as the IfConstruct.  The result must not violate
473   /// construct nesting requirements or contain an EntryStmt.  The result
474   /// is subject to normal un/structured code classification analysis.  The
475   /// result is allowed to violate the F18 Clause 11.1.2.1 prohibition on
476   /// transfer of control into the interior of a construct block, as that does
477   /// not compromise correct code generation.  When two transformation
478   /// candidates overlap, at least one must be disallowed.  In such cases,
479   /// the current heuristic favors simple code generation, which happens to
480   /// favor later candidates over earlier candidates.  That choice is probably
481   /// not significant, but could be changed.
482   ///
483   void rewriteIfGotos() {
484     auto &evaluationList = *evaluationListStack.back();
485     if (!evaluationList.size())
486       return;
487     struct T {
488       lower::pft::EvaluationList::iterator ifConstructIt;
489       parser::Label ifTargetLabel;
490       bool isCycleStmt = false;
491     };
492     llvm::SmallVector<T> ifCandidateStack;
493     const auto *doStmt =
494         evaluationList.begin()->getIf<parser::NonLabelDoStmt>();
495     std::string doName = doStmt ? getConstructName(*doStmt) : std::string{};
496     for (auto it = evaluationList.begin(), end = evaluationList.end();
497          it != end; ++it) {
498       auto &eval = *it;
499       if (eval.isA<parser::EntryStmt>() || eval.isIntermediateConstructStmt()) {
500         ifCandidateStack.clear();
501         continue;
502       }
503       auto firstStmt = [](lower::pft::Evaluation *e) {
504         return e->isConstruct() ? &*e->evaluationList->begin() : e;
505       };
506       const Fortran::lower::pft::Evaluation &targetEval = *firstStmt(&eval);
507       bool targetEvalIsEndDoStmt = targetEval.isA<parser::EndDoStmt>();
508       auto branchTargetMatch = [&]() {
509         if (const parser::Label targetLabel =
510                 ifCandidateStack.back().ifTargetLabel)
511           if (targetLabel == *targetEval.label)
512             return true; // goto target match
513         if (targetEvalIsEndDoStmt && ifCandidateStack.back().isCycleStmt)
514           return true; // cycle target match
515         return false;
516       };
517       if (targetEval.label || targetEvalIsEndDoStmt) {
518         while (!ifCandidateStack.empty() && branchTargetMatch()) {
519           lower::pft::EvaluationList::iterator ifConstructIt =
520               ifCandidateStack.back().ifConstructIt;
521           lower::pft::EvaluationList::iterator successorIt =
522               std::next(ifConstructIt);
523           if (successorIt != it) {
524             Fortran::lower::pft::EvaluationList &ifBodyList =
525                 *ifConstructIt->evaluationList;
526             lower::pft::EvaluationList::iterator branchStmtIt =
527                 std::next(ifBodyList.begin());
528             assert((branchStmtIt->isA<parser::GotoStmt>() ||
529                     branchStmtIt->isA<parser::CycleStmt>()) &&
530                    "expected goto or cycle statement");
531             ifBodyList.erase(branchStmtIt);
532             lower::pft::Evaluation &ifStmt = *ifBodyList.begin();
533             ifStmt.negateCondition = true;
534             ifStmt.lexicalSuccessor = firstStmt(&*successorIt);
535             lower::pft::EvaluationList::iterator endIfStmtIt =
536                 std::prev(ifBodyList.end());
537             std::prev(it)->lexicalSuccessor = &*endIfStmtIt;
538             endIfStmtIt->lexicalSuccessor = firstStmt(&*it);
539             ifBodyList.splice(endIfStmtIt, evaluationList, successorIt, it);
540             for (; successorIt != endIfStmtIt; ++successorIt)
541               successorIt->parentConstruct = &*ifConstructIt;
542           }
543           ifCandidateStack.pop_back();
544         }
545       }
546       if (eval.isA<parser::IfConstruct>() && eval.evaluationList->size() == 3) {
547         const auto bodyEval = std::next(eval.evaluationList->begin());
548         if (const auto *gotoStmt = bodyEval->getIf<parser::GotoStmt>()) {
549           ifCandidateStack.push_back({it, gotoStmt->v});
550         } else if (doStmt) {
551           if (const auto *cycleStmt = bodyEval->getIf<parser::CycleStmt>()) {
552             std::string cycleName = getConstructName(*cycleStmt);
553             if (cycleName.empty() || cycleName == doName)
554               // This candidate will match doStmt's EndDoStmt.
555               ifCandidateStack.push_back({it, {}, true});
556           }
557         }
558       }
559     }
560   }
561 
562   /// Mark IO statement ERR, EOR, and END specifier branch targets.
563   /// Mark an IO statement with an assigned format as unstructured.
564   template <typename A>
565   void analyzeIoBranches(lower::pft::Evaluation &eval, const A &stmt) {
566     auto analyzeFormatSpec = [&](const parser::Format &format) {
567       if (const auto *expr = std::get_if<parser::Expr>(&format.u)) {
568         if (semantics::ExprHasTypeCategory(*semantics::GetExpr(*expr),
569                                            common::TypeCategory::Integer))
570           eval.isUnstructured = true;
571       }
572     };
573     auto analyzeSpecs{[&](const auto &specList) {
574       for (const auto &spec : specList) {
575         std::visit(
576             Fortran::common::visitors{
577                 [&](const Fortran::parser::Format &format) {
578                   analyzeFormatSpec(format);
579                 },
580                 [&](const auto &label) {
581                   using LabelNodes =
582                       std::tuple<parser::ErrLabel, parser::EorLabel,
583                                  parser::EndLabel>;
584                   if constexpr (common::HasMember<decltype(label), LabelNodes>)
585                     markBranchTarget(eval, label.v);
586                 }},
587             spec.u);
588       }
589     }};
590 
591     using OtherIOStmts =
592         std::tuple<parser::BackspaceStmt, parser::CloseStmt,
593                    parser::EndfileStmt, parser::FlushStmt, parser::OpenStmt,
594                    parser::RewindStmt, parser::WaitStmt>;
595 
596     if constexpr (std::is_same_v<A, parser::ReadStmt> ||
597                   std::is_same_v<A, parser::WriteStmt>) {
598       if (stmt.format)
599         analyzeFormatSpec(*stmt.format);
600       analyzeSpecs(stmt.controls);
601     } else if constexpr (std::is_same_v<A, parser::PrintStmt>) {
602       analyzeFormatSpec(std::get<parser::Format>(stmt.t));
603     } else if constexpr (std::is_same_v<A, parser::InquireStmt>) {
604       if (const auto *specList =
605               std::get_if<std::list<parser::InquireSpec>>(&stmt.u))
606         analyzeSpecs(*specList);
607     } else if constexpr (common::HasMember<A, OtherIOStmts>) {
608       analyzeSpecs(stmt.v);
609     } else {
610       // Always crash if this is instantiated
611       static_assert(!std::is_same_v<A, parser::ReadStmt>,
612                     "Unexpected IO statement");
613     }
614   }
615 
616   /// Set the exit of a construct, possibly from multiple enclosing constructs.
617   void setConstructExit(lower::pft::Evaluation &eval) {
618     eval.constructExit = &eval.evaluationList->back().nonNopSuccessor();
619   }
620 
621   /// Mark the target of a branch as a new block.
622   void markBranchTarget(lower::pft::Evaluation &sourceEvaluation,
623                         lower::pft::Evaluation &targetEvaluation) {
624     sourceEvaluation.isUnstructured = true;
625     if (!sourceEvaluation.controlSuccessor)
626       sourceEvaluation.controlSuccessor = &targetEvaluation;
627     targetEvaluation.isNewBlock = true;
628     // If this is a branch into the body of a construct (usually illegal,
629     // but allowed in some legacy cases), then the targetEvaluation and its
630     // ancestors must be marked as unstructured.
631     lower::pft::Evaluation *sourceConstruct = sourceEvaluation.parentConstruct;
632     lower::pft::Evaluation *targetConstruct = targetEvaluation.parentConstruct;
633     if (targetConstruct &&
634         &targetConstruct->getFirstNestedEvaluation() == &targetEvaluation)
635       // A branch to an initial constructStmt is a branch to the construct.
636       targetConstruct = targetConstruct->parentConstruct;
637     if (targetConstruct) {
638       while (sourceConstruct && sourceConstruct != targetConstruct)
639         sourceConstruct = sourceConstruct->parentConstruct;
640       if (sourceConstruct != targetConstruct) // branch into a construct body
641         for (lower::pft::Evaluation *eval = &targetEvaluation; eval;
642              eval = eval->parentConstruct) {
643           eval->isUnstructured = true;
644           // If the branch is a backward branch into an already analyzed
645           // DO or IF construct, mark the construct exit as a new block.
646           // For a forward branch, the isUnstructured flag will cause this
647           // to be done when the construct is analyzed.
648           if (eval->constructExit && (eval->isA<parser::DoConstruct>() ||
649                                       eval->isA<parser::IfConstruct>()))
650             eval->constructExit->isNewBlock = true;
651         }
652     }
653   }
654   void markBranchTarget(lower::pft::Evaluation &sourceEvaluation,
655                         parser::Label label) {
656     assert(label && "missing branch target label");
657     lower::pft::Evaluation *targetEvaluation{
658         labelEvaluationMap->find(label)->second};
659     assert(targetEvaluation && "missing branch target evaluation");
660     markBranchTarget(sourceEvaluation, *targetEvaluation);
661   }
662 
663   /// Mark the successor of an Evaluation as a new block.
664   void markSuccessorAsNewBlock(lower::pft::Evaluation &eval) {
665     eval.nonNopSuccessor().isNewBlock = true;
666   }
667 
668   template <typename A>
669   inline std::string getConstructName(const A &stmt) {
670     using MaybeConstructNameWrapper =
671         std::tuple<parser::BlockStmt, parser::CycleStmt, parser::ElseStmt,
672                    parser::ElsewhereStmt, parser::EndAssociateStmt,
673                    parser::EndBlockStmt, parser::EndCriticalStmt,
674                    parser::EndDoStmt, parser::EndForallStmt, parser::EndIfStmt,
675                    parser::EndSelectStmt, parser::EndWhereStmt,
676                    parser::ExitStmt>;
677     if constexpr (common::HasMember<A, MaybeConstructNameWrapper>) {
678       if (stmt.v)
679         return stmt.v->ToString();
680     }
681 
682     using MaybeConstructNameInTuple = std::tuple<
683         parser::AssociateStmt, parser::CaseStmt, parser::ChangeTeamStmt,
684         parser::CriticalStmt, parser::ElseIfStmt, parser::EndChangeTeamStmt,
685         parser::ForallConstructStmt, parser::IfThenStmt, parser::LabelDoStmt,
686         parser::MaskedElsewhereStmt, parser::NonLabelDoStmt,
687         parser::SelectCaseStmt, parser::SelectRankCaseStmt,
688         parser::TypeGuardStmt, parser::WhereConstructStmt>;
689     if constexpr (common::HasMember<A, MaybeConstructNameInTuple>) {
690       if (auto name = std::get<std::optional<parser::Name>>(stmt.t))
691         return name->ToString();
692     }
693 
694     // These statements have multiple std::optional<parser::Name> elements.
695     if constexpr (std::is_same_v<A, parser::SelectRankStmt> ||
696                   std::is_same_v<A, parser::SelectTypeStmt>) {
697       if (auto name = std::get<0>(stmt.t))
698         return name->ToString();
699     }
700 
701     return {};
702   }
703 
704   /// \p parentConstruct can be null if this statement is at the highest
705   /// level of a program.
706   template <typename A>
707   void insertConstructName(const A &stmt,
708                            lower::pft::Evaluation *parentConstruct) {
709     std::string name = getConstructName(stmt);
710     if (!name.empty())
711       constructNameMap[name] = parentConstruct;
712   }
713 
714   /// Insert branch links for a list of Evaluations.
715   /// \p parentConstruct can be null if the evaluationList contains the
716   /// top-level statements of a program.
717   void analyzeBranches(lower::pft::Evaluation *parentConstruct,
718                        std::list<lower::pft::Evaluation> &evaluationList) {
719     lower::pft::Evaluation *lastConstructStmtEvaluation{};
720     for (auto &eval : evaluationList) {
721       eval.visit(common::visitors{
722           // Action statements (except IO statements)
723           [&](const parser::CallStmt &s) {
724             // Look for alternate return specifiers.
725             const auto &args =
726                 std::get<std::list<parser::ActualArgSpec>>(s.v.t);
727             for (const auto &arg : args) {
728               const auto &actual = std::get<parser::ActualArg>(arg.t);
729               if (const auto *altReturn =
730                       std::get_if<parser::AltReturnSpec>(&actual.u))
731                 markBranchTarget(eval, altReturn->v);
732             }
733           },
734           [&](const parser::CycleStmt &s) {
735             std::string name = getConstructName(s);
736             lower::pft::Evaluation *construct{name.empty()
737                                                   ? doConstructStack.back()
738                                                   : constructNameMap[name]};
739             assert(construct && "missing CYCLE construct");
740             markBranchTarget(eval, construct->evaluationList->back());
741           },
742           [&](const parser::ExitStmt &s) {
743             std::string name = getConstructName(s);
744             lower::pft::Evaluation *construct{name.empty()
745                                                   ? doConstructStack.back()
746                                                   : constructNameMap[name]};
747             assert(construct && "missing EXIT construct");
748             markBranchTarget(eval, *construct->constructExit);
749           },
750           [&](const parser::FailImageStmt &) {
751             eval.isUnstructured = true;
752             if (eval.lexicalSuccessor->lexicalSuccessor)
753               markSuccessorAsNewBlock(eval);
754           },
755           [&](const parser::GotoStmt &s) { markBranchTarget(eval, s.v); },
756           [&](const parser::IfStmt &) {
757             eval.lexicalSuccessor->isNewBlock = true;
758             lastConstructStmtEvaluation = &eval;
759           },
760           [&](const parser::ReturnStmt &) {
761             eval.isUnstructured = true;
762             if (eval.lexicalSuccessor->lexicalSuccessor)
763               markSuccessorAsNewBlock(eval);
764           },
765           [&](const parser::StopStmt &) {
766             eval.isUnstructured = true;
767             if (eval.lexicalSuccessor->lexicalSuccessor)
768               markSuccessorAsNewBlock(eval);
769           },
770           [&](const parser::ComputedGotoStmt &s) {
771             for (auto &label : std::get<std::list<parser::Label>>(s.t))
772               markBranchTarget(eval, label);
773           },
774           [&](const parser::ArithmeticIfStmt &s) {
775             markBranchTarget(eval, std::get<1>(s.t));
776             markBranchTarget(eval, std::get<2>(s.t));
777             markBranchTarget(eval, std::get<3>(s.t));
778           },
779           [&](const parser::AssignStmt &s) { // legacy label assignment
780             auto &label = std::get<parser::Label>(s.t);
781             const auto *sym = std::get<parser::Name>(s.t).symbol;
782             assert(sym && "missing AssignStmt symbol");
783             lower::pft::Evaluation *target{
784                 labelEvaluationMap->find(label)->second};
785             assert(target && "missing branch target evaluation");
786             if (!target->isA<parser::FormatStmt>())
787               target->isNewBlock = true;
788             auto iter = assignSymbolLabelMap->find(*sym);
789             if (iter == assignSymbolLabelMap->end()) {
790               lower::pft::LabelSet labelSet{};
791               labelSet.insert(label);
792               assignSymbolLabelMap->try_emplace(*sym, labelSet);
793             } else {
794               iter->second.insert(label);
795             }
796           },
797           [&](const parser::AssignedGotoStmt &) {
798             // Although this statement is a branch, it doesn't have any
799             // explicit control successors.  So the code at the end of the
800             // loop won't mark the successor.  Do that here.
801             eval.isUnstructured = true;
802             markSuccessorAsNewBlock(eval);
803           },
804 
805           // The first executable statement after an EntryStmt is a new block.
806           [&](const parser::EntryStmt &) {
807             eval.lexicalSuccessor->isNewBlock = true;
808           },
809 
810           // Construct statements
811           [&](const parser::AssociateStmt &s) {
812             insertConstructName(s, parentConstruct);
813           },
814           [&](const parser::BlockStmt &s) {
815             insertConstructName(s, parentConstruct);
816           },
817           [&](const parser::SelectCaseStmt &s) {
818             insertConstructName(s, parentConstruct);
819             lastConstructStmtEvaluation = &eval;
820           },
821           [&](const parser::CaseStmt &) {
822             eval.isNewBlock = true;
823             lastConstructStmtEvaluation->controlSuccessor = &eval;
824             lastConstructStmtEvaluation = &eval;
825           },
826           [&](const parser::EndSelectStmt &) {
827             eval.nonNopSuccessor().isNewBlock = true;
828             lastConstructStmtEvaluation = nullptr;
829           },
830           [&](const parser::ChangeTeamStmt &s) {
831             insertConstructName(s, parentConstruct);
832           },
833           [&](const parser::CriticalStmt &s) {
834             insertConstructName(s, parentConstruct);
835           },
836           [&](const parser::NonLabelDoStmt &s) {
837             insertConstructName(s, parentConstruct);
838             doConstructStack.push_back(parentConstruct);
839             const auto &loopControl =
840                 std::get<std::optional<parser::LoopControl>>(s.t);
841             if (!loopControl.has_value()) {
842               eval.isUnstructured = true; // infinite loop
843               return;
844             }
845             eval.nonNopSuccessor().isNewBlock = true;
846             eval.controlSuccessor = &evaluationList.back();
847             if (const auto *bounds =
848                     std::get_if<parser::LoopControl::Bounds>(&loopControl->u)) {
849               if (bounds->name.thing.symbol->GetType()->IsNumeric(
850                       common::TypeCategory::Real))
851                 eval.isUnstructured = true; // real-valued loop control
852             } else if (std::get_if<parser::ScalarLogicalExpr>(
853                            &loopControl->u)) {
854               eval.isUnstructured = true; // while loop
855             }
856           },
857           [&](const parser::EndDoStmt &) {
858             lower::pft::Evaluation &doEval = evaluationList.front();
859             eval.controlSuccessor = &doEval;
860             doConstructStack.pop_back();
861             if (parentConstruct->lowerAsStructured())
862               return;
863             // The loop is unstructured, which wasn't known for all cases when
864             // visiting the NonLabelDoStmt.
865             parentConstruct->constructExit->isNewBlock = true;
866             const auto &doStmt = *doEval.getIf<parser::NonLabelDoStmt>();
867             const auto &loopControl =
868                 std::get<std::optional<parser::LoopControl>>(doStmt.t);
869             if (!loopControl.has_value())
870               return; // infinite loop
871             if (const auto *concurrent =
872                     std::get_if<parser::LoopControl::Concurrent>(
873                         &loopControl->u)) {
874               // If there is a mask, the EndDoStmt starts a new block.
875               const auto &header =
876                   std::get<parser::ConcurrentHeader>(concurrent->t);
877               eval.isNewBlock |=
878                   std::get<std::optional<parser::ScalarLogicalExpr>>(header.t)
879                       .has_value();
880             }
881           },
882           [&](const parser::IfThenStmt &s) {
883             insertConstructName(s, parentConstruct);
884             eval.lexicalSuccessor->isNewBlock = true;
885             lastConstructStmtEvaluation = &eval;
886           },
887           [&](const parser::ElseIfStmt &) {
888             eval.isNewBlock = true;
889             eval.lexicalSuccessor->isNewBlock = true;
890             lastConstructStmtEvaluation->controlSuccessor = &eval;
891             lastConstructStmtEvaluation = &eval;
892           },
893           [&](const parser::ElseStmt &) {
894             eval.isNewBlock = true;
895             lastConstructStmtEvaluation->controlSuccessor = &eval;
896             lastConstructStmtEvaluation = nullptr;
897           },
898           [&](const parser::EndIfStmt &) {
899             if (parentConstruct->lowerAsUnstructured())
900               parentConstruct->constructExit->isNewBlock = true;
901             if (lastConstructStmtEvaluation) {
902               lastConstructStmtEvaluation->controlSuccessor =
903                   parentConstruct->constructExit;
904               lastConstructStmtEvaluation = nullptr;
905             }
906           },
907           [&](const parser::SelectRankStmt &s) {
908             insertConstructName(s, parentConstruct);
909             lastConstructStmtEvaluation = &eval;
910           },
911           [&](const parser::SelectRankCaseStmt &) {
912             eval.isNewBlock = true;
913             lastConstructStmtEvaluation->controlSuccessor = &eval;
914             lastConstructStmtEvaluation = &eval;
915           },
916           [&](const parser::SelectTypeStmt &s) {
917             insertConstructName(s, parentConstruct);
918             lastConstructStmtEvaluation = &eval;
919           },
920           [&](const parser::TypeGuardStmt &) {
921             eval.isNewBlock = true;
922             lastConstructStmtEvaluation->controlSuccessor = &eval;
923             lastConstructStmtEvaluation = &eval;
924           },
925 
926           // Constructs - set (unstructured) construct exit targets
927           [&](const parser::AssociateConstruct &) { setConstructExit(eval); },
928           [&](const parser::BlockConstruct &) {
929             // EndBlockStmt may have code.
930             eval.constructExit = &eval.evaluationList->back();
931           },
932           [&](const parser::CaseConstruct &) {
933             setConstructExit(eval);
934             eval.isUnstructured = true;
935           },
936           [&](const parser::ChangeTeamConstruct &) {
937             // EndChangeTeamStmt may have code.
938             eval.constructExit = &eval.evaluationList->back();
939           },
940           [&](const parser::CriticalConstruct &) {
941             // EndCriticalStmt may have code.
942             eval.constructExit = &eval.evaluationList->back();
943           },
944           [&](const parser::DoConstruct &) { setConstructExit(eval); },
945           [&](const parser::ForallConstruct &) { setConstructExit(eval); },
946           [&](const parser::IfConstruct &) { setConstructExit(eval); },
947           [&](const parser::SelectRankConstruct &) {
948             setConstructExit(eval);
949             eval.isUnstructured = true;
950           },
951           [&](const parser::SelectTypeConstruct &) {
952             setConstructExit(eval);
953             eval.isUnstructured = true;
954           },
955           [&](const parser::WhereConstruct &) { setConstructExit(eval); },
956 
957           // Default - Common analysis for IO statements; otherwise nop.
958           [&](const auto &stmt) {
959             using A = std::decay_t<decltype(stmt)>;
960             using IoStmts = std::tuple<
961                 parser::BackspaceStmt, parser::CloseStmt, parser::EndfileStmt,
962                 parser::FlushStmt, parser::InquireStmt, parser::OpenStmt,
963                 parser::PrintStmt, parser::ReadStmt, parser::RewindStmt,
964                 parser::WaitStmt, parser::WriteStmt>;
965             if constexpr (common::HasMember<A, IoStmts>)
966               analyzeIoBranches(eval, stmt);
967           },
968       });
969 
970       // Analyze construct evaluations.
971       if (eval.evaluationList)
972         analyzeBranches(&eval, *eval.evaluationList);
973 
974       // Set the successor of the last statement in an IF or SELECT block.
975       if (!eval.controlSuccessor && eval.lexicalSuccessor &&
976           eval.lexicalSuccessor->isIntermediateConstructStmt()) {
977         eval.controlSuccessor = parentConstruct->constructExit;
978         eval.lexicalSuccessor->isNewBlock = true;
979       }
980 
981       // Propagate isUnstructured flag to enclosing construct.
982       if (parentConstruct && eval.isUnstructured)
983         parentConstruct->isUnstructured = true;
984 
985       // The successor of a branch starts a new block.
986       if (eval.controlSuccessor && eval.isActionStmt() &&
987           eval.lowerAsUnstructured())
988         markSuccessorAsNewBlock(eval);
989     }
990   }
991 
992   /// Do processing specific to subprograms with multiple entry points.
993   void processEntryPoints() {
994     lower::pft::Evaluation *initialEval = &evaluationListStack.back()->front();
995     lower::pft::FunctionLikeUnit *unit = initialEval->getOwningProcedure();
996     int entryCount = unit->entryPointList.size();
997     if (entryCount == 1)
998       return;
999 
1000     // The first executable statement in the subprogram is preceded by a
1001     // branch to the entry point, so it starts a new block.
1002     if (initialEval->hasNestedEvaluations())
1003       initialEval = &initialEval->getFirstNestedEvaluation();
1004     else if (initialEval->isA<Fortran::parser::EntryStmt>())
1005       initialEval = initialEval->lexicalSuccessor;
1006     initialEval->isNewBlock = true;
1007 
1008     // All function entry points share a single result container.
1009     // Find one of the largest results.
1010     for (int entryIndex = 0; entryIndex < entryCount; ++entryIndex) {
1011       unit->setActiveEntry(entryIndex);
1012       const auto &details =
1013           unit->getSubprogramSymbol().get<semantics::SubprogramDetails>();
1014       if (details.isFunction()) {
1015         const semantics::Symbol *resultSym = &details.result();
1016         assert(resultSym && "missing result symbol");
1017         if (!unit->primaryResult ||
1018             unit->primaryResult->size() < resultSym->size())
1019           unit->primaryResult = resultSym;
1020       }
1021     }
1022     unit->setActiveEntry(0);
1023   }
1024 
1025   std::unique_ptr<lower::pft::Program> pgm;
1026   std::vector<lower::pft::PftNode> pftParentStack;
1027   const semantics::SemanticsContext &semanticsContext;
1028 
1029   /// functionList points to the internal or module procedure function list
1030   /// of a FunctionLikeUnit or a ModuleLikeUnit.  It may be null.
1031   std::list<lower::pft::FunctionLikeUnit> *functionList{};
1032   std::vector<lower::pft::Evaluation *> constructAndDirectiveStack{};
1033   std::vector<lower::pft::Evaluation *> doConstructStack{};
1034   /// evaluationListStack is the current nested construct evaluationList state.
1035   std::vector<lower::pft::EvaluationList *> evaluationListStack{};
1036   llvm::DenseMap<parser::Label, lower::pft::Evaluation *> *labelEvaluationMap{};
1037   lower::pft::SymbolLabelMap *assignSymbolLabelMap{};
1038   std::map<std::string, lower::pft::Evaluation *> constructNameMap{};
1039   lower::pft::Evaluation *lastLexicalEvaluation{};
1040 };
1041 
1042 #ifndef NDEBUG
1043 /// Dump all program scopes and symbols with addresses to disambiguate names.
1044 /// This is static, unchanging front end information, so dump it only once.
1045 void dumpScope(const semantics::Scope *scope, int depth) {
1046   static int initialVisitCounter = 0;
1047   if (depth < 0) {
1048     if (++initialVisitCounter != 1)
1049       return;
1050     while (!scope->IsGlobal())
1051       scope = &scope->parent();
1052     LLVM_DEBUG(llvm::dbgs() << "Full program scope information.\n"
1053                                "Addresses in angle brackets are scopes. "
1054                                "Unbracketed addresses are symbols.\n");
1055   }
1056   static const std::string white{"                                      ++"};
1057   std::string w = white.substr(0, depth * 2);
1058   if (depth >= 0) {
1059     LLVM_DEBUG(llvm::dbgs() << w << "<" << scope << "> ");
1060     if (auto *sym{scope->symbol()}) {
1061       LLVM_DEBUG(llvm::dbgs() << sym << " " << *sym << "\n");
1062     } else {
1063       if (scope->IsIntrinsicModules()) {
1064         LLVM_DEBUG(llvm::dbgs() << "IntrinsicModules (no detail)\n");
1065         return;
1066       }
1067       LLVM_DEBUG(llvm::dbgs() << "[anonymous]\n");
1068     }
1069   }
1070   for (const auto &scp : scope->children())
1071     if (!scp.symbol())
1072       dumpScope(&scp, depth + 1);
1073   for (auto iter = scope->begin(); iter != scope->end(); ++iter) {
1074     common::Reference<semantics::Symbol> sym = iter->second;
1075     if (auto scp = sym->scope())
1076       dumpScope(scp, depth + 1);
1077     else
1078       LLVM_DEBUG(llvm::dbgs() << w + "  " << &*sym << "   " << *sym << "\n");
1079   }
1080 }
1081 #endif // NDEBUG
1082 
1083 class PFTDumper {
1084 public:
1085   void dumpPFT(llvm::raw_ostream &outputStream,
1086                const lower::pft::Program &pft) {
1087     for (auto &unit : pft.getUnits()) {
1088       std::visit(common::visitors{
1089                      [&](const lower::pft::BlockDataUnit &unit) {
1090                        outputStream << getNodeIndex(unit) << " ";
1091                        outputStream << "BlockData: ";
1092                        outputStream << "\nEnd BlockData\n\n";
1093                      },
1094                      [&](const lower::pft::FunctionLikeUnit &func) {
1095                        dumpFunctionLikeUnit(outputStream, func);
1096                      },
1097                      [&](const lower::pft::ModuleLikeUnit &unit) {
1098                        dumpModuleLikeUnit(outputStream, unit);
1099                      },
1100                      [&](const lower::pft::CompilerDirectiveUnit &unit) {
1101                        dumpCompilerDirectiveUnit(outputStream, unit);
1102                      },
1103                  },
1104                  unit);
1105     }
1106   }
1107 
1108   llvm::StringRef evaluationName(const lower::pft::Evaluation &eval) {
1109     return eval.visit([](const auto &parseTreeNode) {
1110       return parser::ParseTreeDumper::GetNodeName(parseTreeNode);
1111     });
1112   }
1113 
1114   void dumpEvaluation(llvm::raw_ostream &outputStream,
1115                       const lower::pft::Evaluation &eval,
1116                       const std::string &indentString, int indent = 1) {
1117     llvm::StringRef name = evaluationName(eval);
1118     llvm::StringRef newBlock = eval.isNewBlock ? "^" : "";
1119     llvm::StringRef bang = eval.isUnstructured ? "!" : "";
1120     outputStream << indentString;
1121     if (eval.printIndex)
1122       outputStream << eval.printIndex << ' ';
1123     if (eval.hasNestedEvaluations())
1124       outputStream << "<<" << newBlock << name << bang << ">>";
1125     else
1126       outputStream << newBlock << name << bang;
1127     if (eval.negateCondition)
1128       outputStream << " [negate]";
1129     if (eval.constructExit)
1130       outputStream << " -> " << eval.constructExit->printIndex;
1131     else if (eval.controlSuccessor)
1132       outputStream << " -> " << eval.controlSuccessor->printIndex;
1133     else if (eval.isA<parser::EntryStmt>() && eval.lexicalSuccessor)
1134       outputStream << " -> " << eval.lexicalSuccessor->printIndex;
1135     if (!eval.position.empty())
1136       outputStream << ": " << eval.position.ToString();
1137     else if (auto *dir = eval.getIf<Fortran::parser::CompilerDirective>())
1138       outputStream << ": !" << dir->source.ToString();
1139     outputStream << '\n';
1140     if (eval.hasNestedEvaluations()) {
1141       dumpEvaluationList(outputStream, *eval.evaluationList, indent + 1);
1142       outputStream << indentString << "<<End " << name << bang << ">>\n";
1143     }
1144   }
1145 
1146   void dumpEvaluation(llvm::raw_ostream &ostream,
1147                       const lower::pft::Evaluation &eval) {
1148     dumpEvaluation(ostream, eval, "");
1149   }
1150 
1151   void dumpEvaluationList(llvm::raw_ostream &outputStream,
1152                           const lower::pft::EvaluationList &evaluationList,
1153                           int indent = 1) {
1154     static const auto white = "                                      ++"s;
1155     auto indentString = white.substr(0, indent * 2);
1156     for (const lower::pft::Evaluation &eval : evaluationList)
1157       dumpEvaluation(outputStream, eval, indentString, indent);
1158   }
1159 
1160   void
1161   dumpFunctionLikeUnit(llvm::raw_ostream &outputStream,
1162                        const lower::pft::FunctionLikeUnit &functionLikeUnit) {
1163     outputStream << getNodeIndex(functionLikeUnit) << " ";
1164     llvm::StringRef unitKind;
1165     llvm::StringRef name;
1166     llvm::StringRef header;
1167     if (functionLikeUnit.beginStmt) {
1168       functionLikeUnit.beginStmt->visit(common::visitors{
1169           [&](const parser::Statement<parser::ProgramStmt> &stmt) {
1170             unitKind = "Program";
1171             name = toStringRef(stmt.statement.v.source);
1172           },
1173           [&](const parser::Statement<parser::FunctionStmt> &stmt) {
1174             unitKind = "Function";
1175             name = toStringRef(std::get<parser::Name>(stmt.statement.t).source);
1176             header = toStringRef(stmt.source);
1177           },
1178           [&](const parser::Statement<parser::SubroutineStmt> &stmt) {
1179             unitKind = "Subroutine";
1180             name = toStringRef(std::get<parser::Name>(stmt.statement.t).source);
1181             header = toStringRef(stmt.source);
1182           },
1183           [&](const parser::Statement<parser::MpSubprogramStmt> &stmt) {
1184             unitKind = "MpSubprogram";
1185             name = toStringRef(stmt.statement.v.source);
1186             header = toStringRef(stmt.source);
1187           },
1188           [&](const auto &) { llvm_unreachable("not a valid begin stmt"); },
1189       });
1190     } else {
1191       unitKind = "Program";
1192       name = "<anonymous>";
1193     }
1194     outputStream << unitKind << ' ' << name;
1195     if (!header.empty())
1196       outputStream << ": " << header;
1197     outputStream << '\n';
1198     dumpEvaluationList(outputStream, functionLikeUnit.evaluationList);
1199     if (!functionLikeUnit.nestedFunctions.empty()) {
1200       outputStream << "\nContains\n";
1201       for (const lower::pft::FunctionLikeUnit &func :
1202            functionLikeUnit.nestedFunctions)
1203         dumpFunctionLikeUnit(outputStream, func);
1204       outputStream << "End Contains\n";
1205     }
1206     outputStream << "End " << unitKind << ' ' << name << "\n\n";
1207   }
1208 
1209   void dumpModuleLikeUnit(llvm::raw_ostream &outputStream,
1210                           const lower::pft::ModuleLikeUnit &moduleLikeUnit) {
1211     outputStream << getNodeIndex(moduleLikeUnit) << " ";
1212     llvm::StringRef unitKind;
1213     llvm::StringRef name;
1214     llvm::StringRef header;
1215     moduleLikeUnit.beginStmt.visit(common::visitors{
1216         [&](const parser::Statement<parser::ModuleStmt> &stmt) {
1217           unitKind = "Module";
1218           name = toStringRef(stmt.statement.v.source);
1219           header = toStringRef(stmt.source);
1220         },
1221         [&](const parser::Statement<parser::SubmoduleStmt> &stmt) {
1222           unitKind = "Submodule";
1223           name = toStringRef(std::get<parser::Name>(stmt.statement.t).source);
1224           header = toStringRef(stmt.source);
1225         },
1226         [&](const auto &) {
1227           llvm_unreachable("not a valid module begin stmt");
1228         },
1229     });
1230     outputStream << unitKind << ' ' << name << ": " << header << '\n';
1231     dumpEvaluationList(outputStream, moduleLikeUnit.evaluationList);
1232     outputStream << "Contains\n";
1233     for (const lower::pft::FunctionLikeUnit &func :
1234          moduleLikeUnit.nestedFunctions)
1235       dumpFunctionLikeUnit(outputStream, func);
1236     outputStream << "End Contains\nEnd " << unitKind << ' ' << name << "\n\n";
1237   }
1238 
1239   // Top level directives
1240   void dumpCompilerDirectiveUnit(
1241       llvm::raw_ostream &outputStream,
1242       const lower::pft::CompilerDirectiveUnit &directive) {
1243     outputStream << getNodeIndex(directive) << " ";
1244     outputStream << "CompilerDirective: !";
1245     outputStream << directive.get<Fortran::parser::CompilerDirective>()
1246                         .source.ToString();
1247     outputStream << "\nEnd CompilerDirective\n\n";
1248   }
1249 
1250   template <typename T>
1251   std::size_t getNodeIndex(const T &node) {
1252     auto addr = static_cast<const void *>(&node);
1253     auto it = nodeIndexes.find(addr);
1254     if (it != nodeIndexes.end())
1255       return it->second;
1256     nodeIndexes.try_emplace(addr, nextIndex);
1257     return nextIndex++;
1258   }
1259   std::size_t getNodeIndex(const lower::pft::Program &) { return 0; }
1260 
1261 private:
1262   llvm::DenseMap<const void *, std::size_t> nodeIndexes;
1263   std::size_t nextIndex{1}; // 0 is the root
1264 };
1265 
1266 } // namespace
1267 
1268 template <typename A, typename T>
1269 static lower::pft::FunctionLikeUnit::FunctionStatement
1270 getFunctionStmt(const T &func) {
1271   lower::pft::FunctionLikeUnit::FunctionStatement result{
1272       std::get<parser::Statement<A>>(func.t)};
1273   return result;
1274 }
1275 
1276 template <typename A, typename T>
1277 static lower::pft::ModuleLikeUnit::ModuleStatement getModuleStmt(const T &mod) {
1278   lower::pft::ModuleLikeUnit::ModuleStatement result{
1279       std::get<parser::Statement<A>>(mod.t)};
1280   return result;
1281 }
1282 
1283 template <typename A>
1284 static const semantics::Symbol *getSymbol(A &beginStmt) {
1285   const auto *symbol = beginStmt.visit(common::visitors{
1286       [](const parser::Statement<parser::ProgramStmt> &stmt)
1287           -> const semantics::Symbol * { return stmt.statement.v.symbol; },
1288       [](const parser::Statement<parser::FunctionStmt> &stmt)
1289           -> const semantics::Symbol * {
1290         return std::get<parser::Name>(stmt.statement.t).symbol;
1291       },
1292       [](const parser::Statement<parser::SubroutineStmt> &stmt)
1293           -> const semantics::Symbol * {
1294         return std::get<parser::Name>(stmt.statement.t).symbol;
1295       },
1296       [](const parser::Statement<parser::MpSubprogramStmt> &stmt)
1297           -> const semantics::Symbol * { return stmt.statement.v.symbol; },
1298       [](const parser::Statement<parser::ModuleStmt> &stmt)
1299           -> const semantics::Symbol * { return stmt.statement.v.symbol; },
1300       [](const parser::Statement<parser::SubmoduleStmt> &stmt)
1301           -> const semantics::Symbol * {
1302         return std::get<parser::Name>(stmt.statement.t).symbol;
1303       },
1304       [](const auto &) -> const semantics::Symbol * {
1305         llvm_unreachable("unknown FunctionLike or ModuleLike beginStmt");
1306         return nullptr;
1307       }});
1308   assert(symbol && "parser::Name must have resolved symbol");
1309   return symbol;
1310 }
1311 
1312 bool Fortran::lower::pft::Evaluation::lowerAsStructured() const {
1313   return !lowerAsUnstructured();
1314 }
1315 
1316 bool Fortran::lower::pft::Evaluation::lowerAsUnstructured() const {
1317   return isUnstructured || clDisableStructuredFir;
1318 }
1319 
1320 lower::pft::FunctionLikeUnit *
1321 Fortran::lower::pft::Evaluation::getOwningProcedure() const {
1322   return parent.visit(common::visitors{
1323       [](lower::pft::FunctionLikeUnit &c) { return &c; },
1324       [&](lower::pft::Evaluation &c) { return c.getOwningProcedure(); },
1325       [](auto &) -> lower::pft::FunctionLikeUnit * { return nullptr; },
1326   });
1327 }
1328 
1329 bool Fortran::lower::definedInCommonBlock(const semantics::Symbol &sym) {
1330   return semantics::FindCommonBlockContaining(sym);
1331 }
1332 
1333 /// Is the symbol `sym` a global?
1334 bool Fortran::lower::symbolIsGlobal(const semantics::Symbol &sym) {
1335   return semantics::IsSaved(sym) || lower::definedInCommonBlock(sym) ||
1336          semantics::IsNamedConstant(sym);
1337 }
1338 
1339 namespace {
1340 /// This helper class sorts the symbols in a scope such that a symbol will
1341 /// be placed after those it depends upon. Otherwise the sort is stable and
1342 /// preserves the order of the symbol table, which is sorted by name. This
1343 /// analysis may also be done for an individual symbol.
1344 struct SymbolDependenceAnalysis {
1345   explicit SymbolDependenceAnalysis(const semantics::Scope &scope) {
1346     analyzeEquivalenceSets(scope);
1347     for (const auto &iter : scope)
1348       analyze(iter.second.get());
1349     finalize();
1350   }
1351   explicit SymbolDependenceAnalysis(const semantics::Symbol &symbol) {
1352     analyzeEquivalenceSets(symbol.owner());
1353     analyze(symbol);
1354     finalize();
1355   }
1356   Fortran::lower::pft::VariableList getVariableList() {
1357     return std::move(layeredVarList[0]);
1358   }
1359 
1360 private:
1361   /// Analyze the equivalence sets defined in \p scope, plus the equivalence
1362   /// sets in host module, submodule, and procedure scopes that may define
1363   /// symbols referenced in \p scope. This analysis excludes equivalence sets
1364   /// involving common blocks, which are handled elsewhere.
1365   void analyzeEquivalenceSets(const semantics::Scope &scope) {
1366     // FIXME: When this function is called on the scope of an internal
1367     // procedure whose parent contains an EQUIVALENCE set and the internal
1368     // procedure uses variables from that EQUIVALENCE set, we end up creating
1369     // an AggregateStore for those variables unnecessarily.
1370 
1371     // A function defined in a [sub]module has no explicit USE of its ancestor
1372     // [sub]modules. Analyze those scopes here to accommodate references to
1373     // symbols in them.
1374     for (auto *scp = &scope.parent(); !scp->IsGlobal(); scp = &scp->parent())
1375       if (scp->kind() == Fortran::semantics::Scope::Kind::Module)
1376         analyzeLocalEquivalenceSets(*scp);
1377     // Analyze local, USEd, and host procedure scope equivalences.
1378     for (const auto &iter : scope) {
1379       const semantics::Symbol &ultimate = iter.second.get().GetUltimate();
1380       if (!skipSymbol(ultimate))
1381         analyzeLocalEquivalenceSets(ultimate.owner());
1382     }
1383     // Add all aggregate stores to the front of the variable list.
1384     adjustSize(1);
1385     // The copy in the loop matters, 'stores' will still be used.
1386     for (auto st : stores)
1387       layeredVarList[0].emplace_back(std::move(st));
1388   }
1389 
1390   /// Analyze the equivalence sets defined locally in \p scope that don't
1391   /// involve common blocks.
1392   void analyzeLocalEquivalenceSets(const semantics::Scope &scope) {
1393     if (scope.equivalenceSets().empty())
1394       return; // no equivalence sets to analyze
1395     if (analyzedScopes.find(&scope) != analyzedScopes.end())
1396       return; // equivalence sets already analyzed
1397 
1398     analyzedScopes.insert(&scope);
1399     std::list<std::list<semantics::SymbolRef>> aggregates =
1400         Fortran::semantics::GetStorageAssociations(scope);
1401     for (std::list<semantics::SymbolRef> aggregate : aggregates) {
1402       const Fortran::semantics::Symbol *aggregateSym = nullptr;
1403       bool isGlobal = false;
1404       const semantics::Symbol &first = *aggregate.front();
1405       // Exclude equivalence sets involving common blocks.
1406       // Those are handled in instantiateCommon.
1407       if (lower::definedInCommonBlock(first))
1408         continue;
1409       std::size_t start = first.offset();
1410       std::size_t end = first.offset() + first.size();
1411       const Fortran::semantics::Symbol *namingSym = nullptr;
1412       for (semantics::SymbolRef symRef : aggregate) {
1413         const semantics::Symbol &sym = *symRef;
1414         aliasSyms.insert(&sym);
1415         if (sym.test(Fortran::semantics::Symbol::Flag::CompilerCreated)) {
1416           aggregateSym = &sym;
1417         } else {
1418           isGlobal |= lower::symbolIsGlobal(sym);
1419           start = std::min(sym.offset(), start);
1420           end = std::max(sym.offset() + sym.size(), end);
1421           if (!namingSym || (sym.name() < namingSym->name()))
1422             namingSym = &sym;
1423         }
1424       }
1425       assert(namingSym && "must contain at least one user symbol");
1426       if (!aggregateSym) {
1427         stores.emplace_back(
1428             Fortran::lower::pft::Variable::Interval{start, end - start},
1429             *namingSym, isGlobal);
1430       } else {
1431         stores.emplace_back(*aggregateSym, *namingSym, isGlobal);
1432       }
1433     }
1434   }
1435 
1436   // Recursively visit each symbol to determine the height of its dependence on
1437   // other symbols.
1438   int analyze(const semantics::Symbol &sym) {
1439     auto done = seen.insert(&sym);
1440     if (!done.second)
1441       return 0;
1442     LLVM_DEBUG(llvm::dbgs() << "analyze symbol " << &sym << " in <"
1443                             << &sym.owner() << ">: " << sym << '\n');
1444     const bool isProcedurePointerOrDummy =
1445         semantics::IsProcedurePointer(sym) ||
1446         (semantics::IsProcedure(sym) && IsDummy(sym));
1447     // A procedure argument in a subprogram with multiple entry points might
1448     // need a layeredVarList entry to trigger creation of a symbol map entry
1449     // in some cases.  Non-dummy procedures don't.
1450     if (semantics::IsProcedure(sym) && !isProcedurePointerOrDummy)
1451       return 0;
1452     semantics::Symbol ultimate = sym.GetUltimate();
1453     if (const auto *details =
1454             ultimate.detailsIf<semantics::NamelistDetails>()) {
1455       // handle namelist group symbols
1456       for (const semantics::SymbolRef &s : details->objects())
1457         analyze(s);
1458       return 0;
1459     }
1460     if (!ultimate.has<semantics::ObjectEntityDetails>() &&
1461         !isProcedurePointerOrDummy)
1462       return 0;
1463 
1464     if (sym.has<semantics::DerivedTypeDetails>())
1465       llvm_unreachable("not yet implemented - derived type analysis");
1466 
1467     // Symbol must be something lowering will have to allocate.
1468     int depth = 0;
1469     // Analyze symbols appearing in object entity specification expressions.
1470     // This ensures these symbols will be instantiated before the current one.
1471     // This is not done for object entities that are host associated because
1472     // they must be instantiated from the value of the host symbols.
1473     // (The specification expressions should not be re-evaluated.)
1474     if (const auto *details = sym.detailsIf<semantics::ObjectEntityDetails>()) {
1475       const semantics::DeclTypeSpec *symTy = sym.GetType();
1476       assert(symTy && "symbol must have a type");
1477       // check CHARACTER's length
1478       if (symTy->category() == semantics::DeclTypeSpec::Character)
1479         if (auto e = symTy->characterTypeSpec().length().GetExplicit())
1480           for (const auto &s : evaluate::CollectSymbols(*e))
1481             depth = std::max(analyze(s) + 1, depth);
1482 
1483       auto doExplicit = [&](const auto &bound) {
1484         if (bound.isExplicit()) {
1485           semantics::SomeExpr e{*bound.GetExplicit()};
1486           for (const auto &s : evaluate::CollectSymbols(e))
1487             depth = std::max(analyze(s) + 1, depth);
1488         }
1489       };
1490       // Handle any symbols in array bound declarations.
1491       for (const semantics::ShapeSpec &subs : details->shape()) {
1492         doExplicit(subs.lbound());
1493         doExplicit(subs.ubound());
1494       }
1495       // Handle any symbols in coarray bound declarations.
1496       for (const semantics::ShapeSpec &subs : details->coshape()) {
1497         doExplicit(subs.lbound());
1498         doExplicit(subs.ubound());
1499       }
1500       // Handle any symbols in initialization expressions.
1501       if (auto e = details->init())
1502         for (const auto &s : evaluate::CollectSymbols(*e))
1503           depth = std::max(analyze(s) + 1, depth);
1504     }
1505     adjustSize(depth + 1);
1506     bool global = lower::symbolIsGlobal(sym);
1507     layeredVarList[depth].emplace_back(sym, global, depth);
1508     if (semantics::IsAllocatable(sym))
1509       layeredVarList[depth].back().setHeapAlloc();
1510     if (semantics::IsPointer(sym))
1511       layeredVarList[depth].back().setPointer();
1512     if (ultimate.attrs().test(semantics::Attr::TARGET))
1513       layeredVarList[depth].back().setTarget();
1514 
1515     // If there are alias sets, then link the participating variables to their
1516     // aggregate stores when constructing the new variable on the list.
1517     if (lower::pft::Variable::AggregateStore *store = findStoreIfAlias(sym))
1518       layeredVarList[depth].back().setAlias(store->getOffset());
1519     return depth;
1520   }
1521 
1522   /// Skip symbol in alias analysis.
1523   bool skipSymbol(const semantics::Symbol &sym) {
1524     // Common block equivalences are largely managed by the front end.
1525     // Compiler generated symbols ('.' names) cannot be equivalenced.
1526     // FIXME: Equivalence code generation may need to be revisited.
1527     return !sym.has<semantics::ObjectEntityDetails>() ||
1528            lower::definedInCommonBlock(sym) || sym.name()[0] == '.';
1529   }
1530 
1531   // Make sure the table is of appropriate size.
1532   void adjustSize(std::size_t size) {
1533     if (layeredVarList.size() < size)
1534       layeredVarList.resize(size);
1535   }
1536 
1537   Fortran::lower::pft::Variable::AggregateStore *
1538   findStoreIfAlias(const Fortran::evaluate::Symbol &sym) {
1539     const semantics::Symbol &ultimate = sym.GetUltimate();
1540     const semantics::Scope &scope = ultimate.owner();
1541     // Expect the total number of EQUIVALENCE sets to be small for a typical
1542     // Fortran program.
1543     if (aliasSyms.find(&ultimate) != aliasSyms.end()) {
1544       LLVM_DEBUG(llvm::dbgs() << "found aggregate containing " << &ultimate
1545                               << " " << ultimate.name() << " in <" << &scope
1546                               << "> " << scope.GetName() << '\n');
1547       std::size_t off = ultimate.offset();
1548       std::size_t symSize = ultimate.size();
1549       for (lower::pft::Variable::AggregateStore &v : stores) {
1550         if (&v.getOwningScope() == &scope) {
1551           auto intervalOff = std::get<0>(v.interval);
1552           auto intervalSize = std::get<1>(v.interval);
1553           if (off >= intervalOff && off < intervalOff + intervalSize)
1554             return &v;
1555           // Zero sized symbol in zero sized equivalence.
1556           if (off == intervalOff && symSize == 0)
1557             return &v;
1558         }
1559       }
1560       // clang-format off
1561       LLVM_DEBUG(
1562           llvm::dbgs() << "looking for " << off << "\n{\n";
1563           for (lower::pft::Variable::AggregateStore &v : stores) {
1564             llvm::dbgs() << " in scope: " << &v.getOwningScope() << "\n";
1565             llvm::dbgs() << "  i = [" << std::get<0>(v.interval) << ".."
1566                 << std::get<0>(v.interval) + std::get<1>(v.interval)
1567                 << "]\n";
1568           }
1569           llvm::dbgs() << "}\n");
1570       // clang-format on
1571       llvm_unreachable("the store must be present");
1572     }
1573     return nullptr;
1574   }
1575 
1576   /// Flatten the result VariableList.
1577   void finalize() {
1578     for (int i = 1, end = layeredVarList.size(); i < end; ++i)
1579       layeredVarList[0].insert(layeredVarList[0].end(),
1580                                layeredVarList[i].begin(),
1581                                layeredVarList[i].end());
1582   }
1583 
1584   llvm::SmallSet<const semantics::Symbol *, 32> seen;
1585   std::vector<Fortran::lower::pft::VariableList> layeredVarList;
1586   llvm::SmallSet<const semantics::Symbol *, 32> aliasSyms;
1587   /// Set of scopes that have been analyzed for aliases.
1588   llvm::SmallSet<const semantics::Scope *, 4> analyzedScopes;
1589   std::vector<Fortran::lower::pft::Variable::AggregateStore> stores;
1590 };
1591 } // namespace
1592 
1593 //===----------------------------------------------------------------------===//
1594 // FunctionLikeUnit implementation
1595 //===----------------------------------------------------------------------===//
1596 
1597 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1598     const parser::MainProgram &func, const lower::pft::PftNode &parent,
1599     const semantics::SemanticsContext &semanticsContext)
1600     : ProgramUnit{func, parent}, endStmt{
1601                                      getFunctionStmt<parser::EndProgramStmt>(
1602                                          func)} {
1603   const auto &programStmt =
1604       std::get<std::optional<parser::Statement<parser::ProgramStmt>>>(func.t);
1605   if (programStmt.has_value()) {
1606     beginStmt = FunctionStatement(programStmt.value());
1607     const semantics::Symbol *symbol = getSymbol(*beginStmt);
1608     entryPointList[0].first = symbol;
1609     scope = symbol->scope();
1610   } else {
1611     scope = &semanticsContext.FindScope(
1612         std::get<parser::Statement<parser::EndProgramStmt>>(func.t).source);
1613   }
1614 }
1615 
1616 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1617     const parser::FunctionSubprogram &func, const lower::pft::PftNode &parent,
1618     const semantics::SemanticsContext &)
1619     : ProgramUnit{func, parent},
1620       beginStmt{getFunctionStmt<parser::FunctionStmt>(func)},
1621       endStmt{getFunctionStmt<parser::EndFunctionStmt>(func)} {
1622   const semantics::Symbol *symbol = getSymbol(*beginStmt);
1623   entryPointList[0].first = symbol;
1624   scope = symbol->scope();
1625 }
1626 
1627 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1628     const parser::SubroutineSubprogram &func, const lower::pft::PftNode &parent,
1629     const semantics::SemanticsContext &)
1630     : ProgramUnit{func, parent},
1631       beginStmt{getFunctionStmt<parser::SubroutineStmt>(func)},
1632       endStmt{getFunctionStmt<parser::EndSubroutineStmt>(func)} {
1633   const semantics::Symbol *symbol = getSymbol(*beginStmt);
1634   entryPointList[0].first = symbol;
1635   scope = symbol->scope();
1636 }
1637 
1638 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1639     const parser::SeparateModuleSubprogram &func,
1640     const lower::pft::PftNode &parent, const semantics::SemanticsContext &)
1641     : ProgramUnit{func, parent},
1642       beginStmt{getFunctionStmt<parser::MpSubprogramStmt>(func)},
1643       endStmt{getFunctionStmt<parser::EndMpSubprogramStmt>(func)} {
1644   const semantics::Symbol *symbol = getSymbol(*beginStmt);
1645   entryPointList[0].first = symbol;
1646   scope = symbol->scope();
1647 }
1648 
1649 Fortran::lower::HostAssociations &
1650 Fortran::lower::pft::FunctionLikeUnit::parentHostAssoc() {
1651   if (auto *par = parent.getIf<FunctionLikeUnit>())
1652     return par->hostAssociations;
1653   llvm::report_fatal_error("parent is not a function");
1654 }
1655 
1656 bool Fortran::lower::pft::FunctionLikeUnit::parentHasTupleHostAssoc() {
1657   if (auto *par = parent.getIf<FunctionLikeUnit>())
1658     return par->hostAssociations.hasTupleAssociations();
1659   return false;
1660 }
1661 
1662 bool Fortran::lower::pft::FunctionLikeUnit::parentHasHostAssoc() {
1663   if (auto *par = parent.getIf<FunctionLikeUnit>())
1664     return !par->hostAssociations.empty();
1665   return false;
1666 }
1667 
1668 parser::CharBlock
1669 Fortran::lower::pft::FunctionLikeUnit::getStartingSourceLoc() const {
1670   if (beginStmt)
1671     return stmtSourceLoc(*beginStmt);
1672   if (!evaluationList.empty())
1673     return evaluationList.front().position;
1674   return stmtSourceLoc(endStmt);
1675 }
1676 
1677 //===----------------------------------------------------------------------===//
1678 // ModuleLikeUnit implementation
1679 //===----------------------------------------------------------------------===//
1680 
1681 Fortran::lower::pft::ModuleLikeUnit::ModuleLikeUnit(
1682     const parser::Module &m, const lower::pft::PftNode &parent)
1683     : ProgramUnit{m, parent}, beginStmt{getModuleStmt<parser::ModuleStmt>(m)},
1684       endStmt{getModuleStmt<parser::EndModuleStmt>(m)} {}
1685 
1686 Fortran::lower::pft::ModuleLikeUnit::ModuleLikeUnit(
1687     const parser::Submodule &m, const lower::pft::PftNode &parent)
1688     : ProgramUnit{m, parent}, beginStmt{getModuleStmt<parser::SubmoduleStmt>(
1689                                   m)},
1690       endStmt{getModuleStmt<parser::EndSubmoduleStmt>(m)} {}
1691 
1692 parser::CharBlock
1693 Fortran::lower::pft::ModuleLikeUnit::getStartingSourceLoc() const {
1694   return stmtSourceLoc(beginStmt);
1695 }
1696 const Fortran::semantics::Scope &
1697 Fortran::lower::pft::ModuleLikeUnit::getScope() const {
1698   const Fortran::semantics::Symbol *symbol = getSymbol(beginStmt);
1699   assert(symbol && symbol->scope() &&
1700          "Module statement must have a symbol with a scope");
1701   return *symbol->scope();
1702 }
1703 
1704 //===----------------------------------------------------------------------===//
1705 // BlockDataUnit implementation
1706 //===----------------------------------------------------------------------===//
1707 
1708 Fortran::lower::pft::BlockDataUnit::BlockDataUnit(
1709     const parser::BlockData &bd, const lower::pft::PftNode &parent,
1710     const semantics::SemanticsContext &semanticsContext)
1711     : ProgramUnit{bd, parent},
1712       symTab{semanticsContext.FindScope(
1713           std::get<parser::Statement<parser::EndBlockDataStmt>>(bd.t).source)} {
1714 }
1715 
1716 std::unique_ptr<lower::pft::Program>
1717 Fortran::lower::createPFT(const parser::Program &root,
1718                           const semantics::SemanticsContext &semanticsContext) {
1719   PFTBuilder walker(semanticsContext);
1720   Walk(root, walker);
1721   return walker.result();
1722 }
1723 
1724 void Fortran::lower::dumpPFT(llvm::raw_ostream &outputStream,
1725                              const lower::pft::Program &pft) {
1726   PFTDumper{}.dumpPFT(outputStream, pft);
1727 }
1728 
1729 void Fortran::lower::pft::Program::dump() const {
1730   dumpPFT(llvm::errs(), *this);
1731 }
1732 
1733 void Fortran::lower::pft::Evaluation::dump() const {
1734   PFTDumper{}.dumpEvaluation(llvm::errs(), *this);
1735 }
1736 
1737 void Fortran::lower::pft::Variable::dump() const {
1738   if (auto *s = std::get_if<Nominal>(&var)) {
1739     llvm::errs() << s->symbol << " " << *s->symbol;
1740     llvm::errs() << " (depth: " << s->depth << ')';
1741     if (s->global)
1742       llvm::errs() << ", global";
1743     if (s->heapAlloc)
1744       llvm::errs() << ", allocatable";
1745     if (s->pointer)
1746       llvm::errs() << ", pointer";
1747     if (s->target)
1748       llvm::errs() << ", target";
1749     if (s->aliaser)
1750       llvm::errs() << ", equivalence(" << s->aliasOffset << ')';
1751   } else if (auto *s = std::get_if<AggregateStore>(&var)) {
1752     llvm::errs() << "interval[" << std::get<0>(s->interval) << ", "
1753                  << std::get<1>(s->interval) << "]:";
1754     llvm::errs() << " name: " << toStringRef(s->getNamingSymbol().name());
1755     if (s->isGlobal())
1756       llvm::errs() << ", global";
1757     if (s->initialValueSymbol)
1758       llvm::errs() << ", initial value: {" << *s->initialValueSymbol << "}";
1759   } else {
1760     llvm_unreachable("not a Variable");
1761   }
1762   llvm::errs() << '\n';
1763 }
1764 
1765 void Fortran::lower::pft::dump(Fortran::lower::pft::VariableList &variableList,
1766                                std::string s) {
1767   llvm::errs() << (s.empty() ? "VariableList" : s) << " " << &variableList
1768                << " size=" << variableList.size() << "\n";
1769   for (auto var : variableList) {
1770     llvm::errs() << "  ";
1771     var.dump();
1772   }
1773 }
1774 
1775 void Fortran::lower::pft::FunctionLikeUnit::dump() const {
1776   PFTDumper{}.dumpFunctionLikeUnit(llvm::errs(), *this);
1777 }
1778 
1779 void Fortran::lower::pft::ModuleLikeUnit::dump() const {
1780   PFTDumper{}.dumpModuleLikeUnit(llvm::errs(), *this);
1781 }
1782 
1783 /// The BlockDataUnit dump is just the associated symbol table.
1784 void Fortran::lower::pft::BlockDataUnit::dump() const {
1785   llvm::errs() << "block data {\n" << symTab << "\n}\n";
1786 }
1787 
1788 /// Find or create an ordered list of equivalences and variables in \p scope.
1789 /// The result is cached in \p map.
1790 const lower::pft::VariableList &
1791 lower::pft::getScopeVariableList(const semantics::Scope &scope,
1792                                  ScopeVariableListMap &map) {
1793   LLVM_DEBUG(llvm::dbgs() << "\ngetScopeVariableList of [sub]module scope <"
1794                           << &scope << "> " << scope.GetName() << "\n");
1795   auto iter = map.find(&scope);
1796   if (iter == map.end()) {
1797     SymbolDependenceAnalysis sda(scope);
1798     map.emplace(&scope, sda.getVariableList());
1799     iter = map.find(&scope);
1800   }
1801   return iter->second;
1802 }
1803 
1804 /// Create an ordered list of equivalences and variables in \p scope.
1805 /// The result is not cached.
1806 lower::pft::VariableList
1807 lower::pft::getScopeVariableList(const semantics::Scope &scope) {
1808   LLVM_DEBUG(
1809       llvm::dbgs() << "\ngetScopeVariableList of [sub]program|block scope <"
1810                    << &scope << "> " << scope.GetName() << "\n");
1811   SymbolDependenceAnalysis sda(scope);
1812   return sda.getVariableList();
1813 }
1814 
1815 /// Create an ordered list of equivalences and variables that \p symbol
1816 /// depends on (no caching). Include \p symbol at the end of the list.
1817 lower::pft::VariableList
1818 lower::pft::getDependentVariableList(const semantics::Symbol &symbol) {
1819   LLVM_DEBUG(llvm::dbgs() << "\ngetDependentVariableList of " << &symbol
1820                           << " - " << symbol << "\n");
1821   SymbolDependenceAnalysis sda(symbol);
1822   return sda.getVariableList();
1823 }
1824 
1825 namespace {
1826 /// Helper class to find all the symbols referenced in a FunctionLikeUnit.
1827 /// It defines a parse tree visitor doing a deep visit in all nodes with
1828 /// symbols (including evaluate::Expr).
1829 struct SymbolVisitor {
1830   template <typename A>
1831   bool Pre(const A &x) {
1832     if constexpr (Fortran::parser::HasTypedExpr<A>::value)
1833       // Some parse tree Expr may legitimately be un-analyzed after semantics
1834       // (for instance PDT component initial value in the PDT definition body).
1835       if (const auto *expr = Fortran::semantics::GetExpr(nullptr, x))
1836         visitExpr(*expr);
1837     return true;
1838   }
1839 
1840   bool Pre(const Fortran::parser::Name &name) {
1841     if (const semantics::Symbol *symbol = name.symbol)
1842       visitSymbol(*symbol);
1843     return false;
1844   }
1845 
1846   template <typename T>
1847   void visitExpr(const Fortran::evaluate::Expr<T> &expr) {
1848     for (const semantics::Symbol &symbol :
1849          Fortran::evaluate::CollectSymbols(expr))
1850       visitSymbol(symbol);
1851   }
1852 
1853   void visitSymbol(const Fortran::semantics::Symbol &symbol) {
1854     callBack(symbol);
1855     // - Visit statement function body since it will be inlined in lowering.
1856     // - Visit function results specification expressions because allocations
1857     //   happens on the caller side.
1858     if (const auto *subprogramDetails =
1859             symbol.detailsIf<Fortran::semantics::SubprogramDetails>()) {
1860       if (const auto &maybeExpr = subprogramDetails->stmtFunction()) {
1861         visitExpr(*maybeExpr);
1862       } else {
1863         if (subprogramDetails->isFunction()) {
1864           // Visit result extents expressions that are explicit.
1865           const Fortran::semantics::Symbol &result =
1866               subprogramDetails->result();
1867           if (const auto *objectDetails =
1868                   result.detailsIf<Fortran::semantics::ObjectEntityDetails>())
1869             if (objectDetails->shape().IsExplicitShape())
1870               for (const Fortran::semantics::ShapeSpec &shapeSpec :
1871                    objectDetails->shape()) {
1872                 visitExpr(shapeSpec.lbound().GetExplicit().value());
1873                 visitExpr(shapeSpec.ubound().GetExplicit().value());
1874               }
1875         }
1876       }
1877     }
1878     if (Fortran::semantics::IsProcedure(symbol)) {
1879       if (auto dynamicType = Fortran::evaluate::DynamicType::From(symbol)) {
1880         // Visit result length specification expressions that are explicit.
1881         if (dynamicType->category() ==
1882             Fortran::common::TypeCategory::Character) {
1883           if (std::optional<Fortran::evaluate::ExtentExpr> length =
1884                   dynamicType->GetCharLength())
1885             visitExpr(*length);
1886         } else if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec =
1887                        Fortran::evaluate::GetDerivedTypeSpec(dynamicType)) {
1888           for (const auto &[_, param] : derivedTypeSpec->parameters())
1889             if (const Fortran::semantics::MaybeIntExpr &expr =
1890                     param.GetExplicit())
1891               visitExpr(expr.value());
1892         }
1893       }
1894     }
1895   }
1896 
1897   template <typename A>
1898   constexpr void Post(const A &) {}
1899 
1900   const std::function<void(const Fortran::semantics::Symbol &)> &callBack;
1901 };
1902 } // namespace
1903 
1904 void Fortran::lower::pft::visitAllSymbols(
1905     const Fortran::lower::pft::FunctionLikeUnit &funit,
1906     const std::function<void(const Fortran::semantics::Symbol &)> callBack) {
1907   SymbolVisitor visitor{callBack};
1908   funit.visit([&](const auto &functionParserNode) {
1909     parser::Walk(functionParserNode, visitor);
1910   });
1911 }
1912 
1913 void Fortran::lower::pft::visitAllSymbols(
1914     const Fortran::lower::pft::Evaluation &eval,
1915     const std::function<void(const Fortran::semantics::Symbol &)> callBack) {
1916   SymbolVisitor visitor{callBack};
1917   eval.visit([&](const auto &functionParserNode) {
1918     parser::Walk(functionParserNode, visitor);
1919   });
1920 }
1921