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