• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- PFTBuilder.cc -----------------------------------------------------===//
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/Utils.h"
11 #include "flang/Parser/dump-parse-tree.h"
12 #include "flang/Parser/parse-tree-visitor.h"
13 #include "flang/Semantics/semantics.h"
14 #include "flang/Semantics/tools.h"
15 #include "llvm/Support/CommandLine.h"
16 
17 static llvm::cl::opt<bool> clDisableStructuredFir(
18     "no-structured-fir", llvm::cl::desc("disable generation of structured FIR"),
19     llvm::cl::init(false), llvm::cl::Hidden);
20 
21 using namespace Fortran;
22 
23 namespace {
24 /// Helpers to unveil parser node inside Fortran::parser::Statement<>,
25 /// Fortran::parser::UnlabeledStatement, and Fortran::common::Indirection<>
26 template <typename A>
27 struct RemoveIndirectionHelper {
28   using Type = A;
29 };
30 template <typename A>
31 struct RemoveIndirectionHelper<common::Indirection<A>> {
32   using Type = A;
33 };
34 
35 template <typename A>
36 struct UnwrapStmt {
37   static constexpr bool isStmt{false};
38 };
39 template <typename A>
40 struct UnwrapStmt<parser::Statement<A>> {
41   static constexpr bool isStmt{true};
42   using Type = typename RemoveIndirectionHelper<A>::Type;
UnwrapStmt__anon6f56359d0111::UnwrapStmt43   constexpr UnwrapStmt(const parser::Statement<A> &a)
44       : unwrapped{removeIndirection(a.statement)}, position{a.source},
45         label{a.label} {}
46   const Type &unwrapped;
47   parser::CharBlock position;
48   std::optional<parser::Label> label;
49 };
50 template <typename A>
51 struct UnwrapStmt<parser::UnlabeledStatement<A>> {
52   static constexpr bool isStmt{true};
53   using Type = typename RemoveIndirectionHelper<A>::Type;
UnwrapStmt__anon6f56359d0111::UnwrapStmt54   constexpr UnwrapStmt(const parser::UnlabeledStatement<A> &a)
55       : unwrapped{removeIndirection(a.statement)}, position{a.source} {}
56   const Type &unwrapped;
57   parser::CharBlock position;
58   std::optional<parser::Label> label;
59 };
60 
61 /// The instantiation of a parse tree visitor (Pre and Post) is extremely
62 /// expensive in terms of compile and link time.  So one goal here is to
63 /// limit the bridge to one such instantiation.
64 class PFTBuilder {
65 public:
PFTBuilder(const semantics::SemanticsContext & semanticsContext)66   PFTBuilder(const semantics::SemanticsContext &semanticsContext)
67       : pgm{std::make_unique<lower::pft::Program>()}, semanticsContext{
68                                                           semanticsContext} {
69     lower::pft::ParentVariant parent{*pgm.get()};
70     parentVariantStack.push_back(parent);
71   }
72 
73   /// Get the result
result()74   std::unique_ptr<lower::pft::Program> result() { return std::move(pgm); }
75 
76   template <typename A>
Pre(const A & a)77   constexpr bool Pre(const A &a) {
78     if constexpr (lower::pft::isFunctionLike<A>) {
79       return enterFunction(a, semanticsContext);
80     } else if constexpr (lower::pft::isConstruct<A> ||
81                          lower::pft::isDirective<A>) {
82       return enterConstructOrDirective(a);
83     } else if constexpr (UnwrapStmt<A>::isStmt) {
84       using T = typename UnwrapStmt<A>::Type;
85       // Node "a" being visited has one of the following types:
86       // Statement<T>, Statement<Indirection<T>, UnlabeledStatement<T>,
87       // or UnlabeledStatement<Indirection<T>>
88       auto stmt{UnwrapStmt<A>(a)};
89       if constexpr (lower::pft::isConstructStmt<T> ||
90                     lower::pft::isOtherStmt<T>) {
91         addEvaluation(lower::pft::Evaluation{stmt.unwrapped,
92                                              parentVariantStack.back(),
93                                              stmt.position, stmt.label});
94         return false;
95       } else if constexpr (std::is_same_v<T, parser::ActionStmt>) {
96         addEvaluation(
97             makeEvaluationAction(stmt.unwrapped, stmt.position, stmt.label));
98         return true;
99       }
100     }
101     return true;
102   }
103 
104   template <typename A>
Post(const A &)105   constexpr void Post(const A &) {
106     if constexpr (lower::pft::isFunctionLike<A>) {
107       exitFunction();
108     } else if constexpr (lower::pft::isConstruct<A> ||
109                          lower::pft::isDirective<A>) {
110       exitConstructOrDirective();
111     }
112   }
113 
114   // Module like
Pre(const parser::Module & node)115   bool Pre(const parser::Module &node) { return enterModule(node); }
Pre(const parser::Submodule & node)116   bool Pre(const parser::Submodule &node) { return enterModule(node); }
117 
Post(const parser::Module &)118   void Post(const parser::Module &) { exitModule(); }
Post(const parser::Submodule &)119   void Post(const parser::Submodule &) { exitModule(); }
120 
121   // Block data
Pre(const parser::BlockData & node)122   bool Pre(const parser::BlockData &node) {
123     addUnit(lower::pft::BlockDataUnit{node, parentVariantStack.back()});
124     return false;
125   }
126 
127   // Get rid of production wrapper
Pre(const parser::UnlabeledStatement<parser::ForallAssignmentStmt> & statement)128   bool Pre(const parser::UnlabeledStatement<parser::ForallAssignmentStmt>
129                &statement) {
130     addEvaluation(std::visit(
131         [&](const auto &x) {
132           return lower::pft::Evaluation{
133               x, parentVariantStack.back(), statement.source, {}};
134         },
135         statement.statement.u));
136     return false;
137   }
Pre(const parser::Statement<parser::ForallAssignmentStmt> & statement)138   bool Pre(const parser::Statement<parser::ForallAssignmentStmt> &statement) {
139     addEvaluation(std::visit(
140         [&](const auto &x) {
141           return lower::pft::Evaluation{x, parentVariantStack.back(),
142                                         statement.source, statement.label};
143         },
144         statement.statement.u));
145     return false;
146   }
Pre(const parser::WhereBodyConstruct & whereBody)147   bool Pre(const parser::WhereBodyConstruct &whereBody) {
148     return std::visit(
149         common::visitors{
150             [&](const parser::Statement<parser::AssignmentStmt> &stmt) {
151               // Not caught as other AssignmentStmt because it is not
152               // wrapped in a parser::ActionStmt.
153               addEvaluation(lower::pft::Evaluation{stmt.statement,
154                                                    parentVariantStack.back(),
155                                                    stmt.source, stmt.label});
156               return false;
157             },
158             [&](const auto &) { return true; },
159         },
160         whereBody.u);
161   }
162 
163 private:
164   /// Initialize a new module-like unit and make it the builder's focus.
165   template <typename A>
enterModule(const A & func)166   bool enterModule(const A &func) {
167     auto &unit =
168         addUnit(lower::pft::ModuleLikeUnit{func, parentVariantStack.back()});
169     functionList = &unit.nestedFunctions;
170     parentVariantStack.emplace_back(unit);
171     return true;
172   }
173 
exitModule()174   void exitModule() {
175     parentVariantStack.pop_back();
176     resetFunctionState();
177   }
178 
179   /// Ensure that a function has a branch target after the last user statement.
endFunctionBody()180   void endFunctionBody() {
181     if (lastLexicalEvaluation) {
182       static const parser::ContinueStmt endTarget{};
183       addEvaluation(
184           lower::pft::Evaluation{endTarget, parentVariantStack.back(), {}, {}});
185       lastLexicalEvaluation = nullptr;
186     }
187   }
188 
189   /// Initialize a new function-like unit and make it the builder's focus.
190   template <typename A>
enterFunction(const A & func,const semantics::SemanticsContext & semanticsContext)191   bool enterFunction(const A &func,
192                      const semantics::SemanticsContext &semanticsContext) {
193     endFunctionBody(); // enclosing host subprogram body, if any
194     auto &unit = addFunction(lower::pft::FunctionLikeUnit{
195         func, parentVariantStack.back(), semanticsContext});
196     labelEvaluationMap = &unit.labelEvaluationMap;
197     assignSymbolLabelMap = &unit.assignSymbolLabelMap;
198     functionList = &unit.nestedFunctions;
199     pushEvaluationList(&unit.evaluationList);
200     parentVariantStack.emplace_back(unit);
201     return true;
202   }
203 
exitFunction()204   void exitFunction() {
205     endFunctionBody();
206     analyzeBranches(nullptr, *evaluationListStack.back()); // add branch links
207     popEvaluationList();
208     labelEvaluationMap = nullptr;
209     assignSymbolLabelMap = nullptr;
210     parentVariantStack.pop_back();
211     resetFunctionState();
212   }
213 
214   /// Initialize a new construct and make it the builder's focus.
215   template <typename A>
enterConstructOrDirective(const A & construct)216   bool enterConstructOrDirective(const A &construct) {
217     auto &eval = addEvaluation(
218         lower::pft::Evaluation{construct, parentVariantStack.back()});
219     eval.evaluationList.reset(new lower::pft::EvaluationList);
220     pushEvaluationList(eval.evaluationList.get());
221     parentVariantStack.emplace_back(eval);
222     constructAndDirectiveStack.emplace_back(&eval);
223     return true;
224   }
225 
exitConstructOrDirective()226   void exitConstructOrDirective() {
227     popEvaluationList();
228     parentVariantStack.pop_back();
229     constructAndDirectiveStack.pop_back();
230   }
231 
232   /// Reset function state to that of an enclosing host function.
resetFunctionState()233   void resetFunctionState() {
234     if (!parentVariantStack.empty()) {
235       parentVariantStack.back().visit(common::visitors{
236           [&](lower::pft::FunctionLikeUnit &p) {
237             functionList = &p.nestedFunctions;
238             labelEvaluationMap = &p.labelEvaluationMap;
239             assignSymbolLabelMap = &p.assignSymbolLabelMap;
240           },
241           [&](lower::pft::ModuleLikeUnit &p) {
242             functionList = &p.nestedFunctions;
243           },
244           [&](auto &) { functionList = nullptr; },
245       });
246     }
247   }
248 
249   template <typename A>
addUnit(A && unit)250   A &addUnit(A &&unit) {
251     pgm->getUnits().emplace_back(std::move(unit));
252     return std::get<A>(pgm->getUnits().back());
253   }
254 
255   template <typename A>
addFunction(A && func)256   A &addFunction(A &&func) {
257     if (functionList) {
258       functionList->emplace_back(std::move(func));
259       return functionList->back();
260     }
261     return addUnit(std::move(func));
262   }
263 
264   // ActionStmt has a couple of non-conforming cases, explicitly handled here.
265   // The other cases use an Indirection, which are discarded in the PFT.
266   lower::pft::Evaluation
makeEvaluationAction(const parser::ActionStmt & statement,parser::CharBlock position,std::optional<parser::Label> label)267   makeEvaluationAction(const parser::ActionStmt &statement,
268                        parser::CharBlock position,
269                        std::optional<parser::Label> label) {
270     return std::visit(
271         common::visitors{
272             [&](const auto &x) {
273               return lower::pft::Evaluation{removeIndirection(x),
274                                             parentVariantStack.back(), position,
275                                             label};
276             },
277         },
278         statement.u);
279   }
280 
281   /// Append an Evaluation to the end of the current list.
addEvaluation(lower::pft::Evaluation && eval)282   lower::pft::Evaluation &addEvaluation(lower::pft::Evaluation &&eval) {
283     assert(functionList && "not in a function");
284     assert(evaluationListStack.size() > 0);
285     if (constructAndDirectiveStack.size() > 0) {
286       eval.parentConstruct = constructAndDirectiveStack.back();
287     }
288     evaluationListStack.back()->emplace_back(std::move(eval));
289     lower::pft::Evaluation *p = &evaluationListStack.back()->back();
290     if (p->isActionStmt() || p->isConstructStmt()) {
291       if (lastLexicalEvaluation) {
292         lastLexicalEvaluation->lexicalSuccessor = p;
293         p->printIndex = lastLexicalEvaluation->printIndex + 1;
294       } else {
295         p->printIndex = 1;
296       }
297       lastLexicalEvaluation = p;
298     }
299     if (p->label.has_value()) {
300       labelEvaluationMap->try_emplace(*p->label, p);
301     }
302     return evaluationListStack.back()->back();
303   }
304 
305   /// push a new list on the stack of Evaluation lists
pushEvaluationList(lower::pft::EvaluationList * eval)306   void pushEvaluationList(lower::pft::EvaluationList *eval) {
307     assert(functionList && "not in a function");
308     assert(eval && eval->empty() && "evaluation list isn't correct");
309     evaluationListStack.emplace_back(eval);
310   }
311 
312   /// pop the current list and return to the last Evaluation list
popEvaluationList()313   void popEvaluationList() {
314     assert(functionList && "not in a function");
315     evaluationListStack.pop_back();
316   }
317 
318   /// Mark I/O statement ERR, EOR, and END specifier branch targets.
319   template <typename A>
analyzeIoBranches(lower::pft::Evaluation & eval,const A & stmt)320   void analyzeIoBranches(lower::pft::Evaluation &eval, const A &stmt) {
321     auto processIfLabel{[&](const auto &specs) {
322       using LabelNodes =
323           std::tuple<parser::ErrLabel, parser::EorLabel, parser::EndLabel>;
324       for (const auto &spec : specs) {
325         const auto *label = std::visit(
326             [](const auto &label) -> const parser::Label * {
327               using B = std::decay_t<decltype(label)>;
328               if constexpr (common::HasMember<B, LabelNodes>) {
329                 return &label.v;
330               }
331               return nullptr;
332             },
333             spec.u);
334 
335         if (label)
336           markBranchTarget(eval, *label);
337       }
338     }};
339 
340     using OtherIOStmts =
341         std::tuple<parser::BackspaceStmt, parser::CloseStmt,
342                    parser::EndfileStmt, parser::FlushStmt, parser::OpenStmt,
343                    parser::RewindStmt, parser::WaitStmt>;
344 
345     if constexpr (std::is_same_v<A, parser::ReadStmt> ||
346                   std::is_same_v<A, parser::WriteStmt>) {
347       processIfLabel(stmt.controls);
348     } else if constexpr (std::is_same_v<A, parser::InquireStmt>) {
349       processIfLabel(std::get<std::list<parser::InquireSpec>>(stmt.u));
350     } else if constexpr (common::HasMember<A, OtherIOStmts>) {
351       processIfLabel(stmt.v);
352     } else {
353       // Always crash if this is instantiated
354       static_assert(!std::is_same_v<A, parser::ReadStmt>,
355                     "Unexpected IO statement");
356     }
357   }
358 
359   /// Set the exit of a construct, possibly from multiple enclosing constructs.
setConstructExit(lower::pft::Evaluation & eval)360   void setConstructExit(lower::pft::Evaluation &eval) {
361     eval.constructExit = &eval.evaluationList->back().nonNopSuccessor();
362   }
363 
364   /// Mark the target of a branch as a new block.
markBranchTarget(lower::pft::Evaluation & sourceEvaluation,lower::pft::Evaluation & targetEvaluation)365   void markBranchTarget(lower::pft::Evaluation &sourceEvaluation,
366                         lower::pft::Evaluation &targetEvaluation) {
367     sourceEvaluation.isUnstructured = true;
368     if (!sourceEvaluation.controlSuccessor) {
369       sourceEvaluation.controlSuccessor = &targetEvaluation;
370     }
371     targetEvaluation.isNewBlock = true;
372     // If this is a branch into the body of a construct (usually illegal,
373     // but allowed in some legacy cases), then the targetEvaluation and its
374     // ancestors must be marked as unstructured.
375     auto *sourceConstruct = sourceEvaluation.parentConstruct;
376     auto *targetConstruct = targetEvaluation.parentConstruct;
377     if (targetEvaluation.isConstructStmt() &&
378         &targetConstruct->getFirstNestedEvaluation() == &targetEvaluation)
379       // A branch to an initial constructStmt is a branch to the construct.
380       targetConstruct = targetConstruct->parentConstruct;
381     if (targetConstruct) {
382       while (sourceConstruct && sourceConstruct != targetConstruct)
383         sourceConstruct = sourceConstruct->parentConstruct;
384       if (sourceConstruct != targetConstruct)
385         for (auto *eval = &targetEvaluation; eval; eval = eval->parentConstruct)
386           eval->isUnstructured = true;
387     }
388   }
markBranchTarget(lower::pft::Evaluation & sourceEvaluation,parser::Label label)389   void markBranchTarget(lower::pft::Evaluation &sourceEvaluation,
390                         parser::Label label) {
391     assert(label && "missing branch target label");
392     lower::pft::Evaluation *targetEvaluation{
393         labelEvaluationMap->find(label)->second};
394     assert(targetEvaluation && "missing branch target evaluation");
395     markBranchTarget(sourceEvaluation, *targetEvaluation);
396   }
397 
398   /// Mark the successor of an Evaluation as a new block.
markSuccessorAsNewBlock(lower::pft::Evaluation & eval)399   void markSuccessorAsNewBlock(lower::pft::Evaluation &eval) {
400     eval.nonNopSuccessor().isNewBlock = true;
401   }
402 
403   template <typename A>
getConstructName(const A & stmt)404   inline std::string getConstructName(const A &stmt) {
405     using MaybeConstructNameWrapper =
406         std::tuple<parser::BlockStmt, parser::CycleStmt, parser::ElseStmt,
407                    parser::ElsewhereStmt, parser::EndAssociateStmt,
408                    parser::EndBlockStmt, parser::EndCriticalStmt,
409                    parser::EndDoStmt, parser::EndForallStmt, parser::EndIfStmt,
410                    parser::EndSelectStmt, parser::EndWhereStmt,
411                    parser::ExitStmt>;
412     if constexpr (common::HasMember<A, MaybeConstructNameWrapper>) {
413       if (stmt.v)
414         return stmt.v->ToString();
415     }
416 
417     using MaybeConstructNameInTuple = std::tuple<
418         parser::AssociateStmt, parser::CaseStmt, parser::ChangeTeamStmt,
419         parser::CriticalStmt, parser::ElseIfStmt, parser::EndChangeTeamStmt,
420         parser::ForallConstructStmt, parser::IfThenStmt, parser::LabelDoStmt,
421         parser::MaskedElsewhereStmt, parser::NonLabelDoStmt,
422         parser::SelectCaseStmt, parser::SelectRankCaseStmt,
423         parser::TypeGuardStmt, parser::WhereConstructStmt>;
424 
425     if constexpr (common::HasMember<A, MaybeConstructNameInTuple>) {
426       if (auto name{std::get<std::optional<parser::Name>>(stmt.t)})
427         return name->ToString();
428     }
429 
430     // These statements have several std::optional<parser::Name>
431     if constexpr (std::is_same_v<A, parser::SelectRankStmt> ||
432                   std::is_same_v<A, parser::SelectTypeStmt>) {
433       if (auto name{std::get<0>(stmt.t)}) {
434         return name->ToString();
435       }
436     }
437     return {};
438   }
439 
440   /// \p parentConstruct can be null if this statement is at the highest
441   /// level of a program.
442   template <typename A>
insertConstructName(const A & stmt,lower::pft::Evaluation * parentConstruct)443   void insertConstructName(const A &stmt,
444                            lower::pft::Evaluation *parentConstruct) {
445     std::string name{getConstructName(stmt)};
446     if (!name.empty()) {
447       constructNameMap[name] = parentConstruct;
448     }
449   }
450 
451   /// Insert branch links for a list of Evaluations.
452   /// \p parentConstruct can be null if the evaluationList contains the
453   /// top-level statements of a program.
analyzeBranches(lower::pft::Evaluation * parentConstruct,std::list<lower::pft::Evaluation> & evaluationList)454   void analyzeBranches(lower::pft::Evaluation *parentConstruct,
455                        std::list<lower::pft::Evaluation> &evaluationList) {
456     lower::pft::Evaluation *lastConstructStmtEvaluation{nullptr};
457     lower::pft::Evaluation *lastIfStmtEvaluation{nullptr};
458     for (auto &eval : evaluationList) {
459       eval.visit(common::visitors{
460           // Action statements
461           [&](const parser::CallStmt &s) {
462             // Look for alternate return specifiers.
463             const auto &args{std::get<std::list<parser::ActualArgSpec>>(s.v.t)};
464             for (const auto &arg : args) {
465               const auto &actual{std::get<parser::ActualArg>(arg.t)};
466               if (const auto *altReturn{
467                       std::get_if<parser::AltReturnSpec>(&actual.u)}) {
468                 markBranchTarget(eval, altReturn->v);
469               }
470             }
471           },
472           [&](const parser::CycleStmt &s) {
473             std::string name{getConstructName(s)};
474             lower::pft::Evaluation *construct{name.empty()
475                                                   ? doConstructStack.back()
476                                                   : constructNameMap[name]};
477             assert(construct && "missing CYCLE construct");
478             markBranchTarget(eval, construct->evaluationList->back());
479           },
480           [&](const parser::ExitStmt &s) {
481             std::string name{getConstructName(s)};
482             lower::pft::Evaluation *construct{name.empty()
483                                                   ? doConstructStack.back()
484                                                   : constructNameMap[name]};
485             assert(construct && "missing EXIT construct");
486             markBranchTarget(eval, *construct->constructExit);
487           },
488           [&](const parser::GotoStmt &s) { markBranchTarget(eval, s.v); },
489           [&](const parser::IfStmt &) { lastIfStmtEvaluation = &eval; },
490           [&](const parser::ReturnStmt &) {
491             eval.isUnstructured = true;
492             if (eval.lexicalSuccessor->lexicalSuccessor)
493               markSuccessorAsNewBlock(eval);
494           },
495           [&](const parser::StopStmt &) {
496             eval.isUnstructured = true;
497             if (eval.lexicalSuccessor->lexicalSuccessor)
498               markSuccessorAsNewBlock(eval);
499           },
500           [&](const parser::ComputedGotoStmt &s) {
501             for (auto &label : std::get<std::list<parser::Label>>(s.t)) {
502               markBranchTarget(eval, label);
503             }
504           },
505           [&](const parser::ArithmeticIfStmt &s) {
506             markBranchTarget(eval, std::get<1>(s.t));
507             markBranchTarget(eval, std::get<2>(s.t));
508             markBranchTarget(eval, std::get<3>(s.t));
509             if (semantics::ExprHasTypeCategory(
510                     *semantics::GetExpr(std::get<parser::Expr>(s.t)),
511                     common::TypeCategory::Real)) {
512               // Real expression evaluation uses an additional local block.
513               eval.localBlocks.emplace_back(nullptr);
514             }
515           },
516           [&](const parser::AssignStmt &s) { // legacy label assignment
517             auto &label = std::get<parser::Label>(s.t);
518             const auto *sym = std::get<parser::Name>(s.t).symbol;
519             assert(sym && "missing AssignStmt symbol");
520             lower::pft::Evaluation *target{
521                 labelEvaluationMap->find(label)->second};
522             assert(target && "missing branch target evaluation");
523             if (!target->isA<parser::FormatStmt>()) {
524               target->isNewBlock = true;
525             }
526             auto iter = assignSymbolLabelMap->find(*sym);
527             if (iter == assignSymbolLabelMap->end()) {
528               lower::pft::LabelSet labelSet{};
529               labelSet.insert(label);
530               assignSymbolLabelMap->try_emplace(*sym, labelSet);
531             } else {
532               iter->second.insert(label);
533             }
534           },
535           [&](const parser::AssignedGotoStmt &) {
536             // Although this statement is a branch, it doesn't have any
537             // explicit control successors.  So the code at the end of the
538             // loop won't mark the successor.  Do that here.
539             eval.isUnstructured = true;
540             markSuccessorAsNewBlock(eval);
541           },
542 
543           // Construct statements
544           [&](const parser::AssociateStmt &s) {
545             insertConstructName(s, parentConstruct);
546           },
547           [&](const parser::BlockStmt &s) {
548             insertConstructName(s, parentConstruct);
549           },
550           [&](const parser::SelectCaseStmt &s) {
551             insertConstructName(s, parentConstruct);
552             lastConstructStmtEvaluation = &eval;
553           },
554           [&](const parser::CaseStmt &) {
555             eval.isNewBlock = true;
556             lastConstructStmtEvaluation->controlSuccessor = &eval;
557             lastConstructStmtEvaluation = &eval;
558           },
559           [&](const parser::EndSelectStmt &) {
560             eval.nonNopSuccessor().isNewBlock = true;
561             lastConstructStmtEvaluation = nullptr;
562           },
563           [&](const parser::ChangeTeamStmt &s) {
564             insertConstructName(s, parentConstruct);
565           },
566           [&](const parser::CriticalStmt &s) {
567             insertConstructName(s, parentConstruct);
568           },
569           [&](const parser::NonLabelDoStmt &s) {
570             insertConstructName(s, parentConstruct);
571             doConstructStack.push_back(parentConstruct);
572             auto &control{std::get<std::optional<parser::LoopControl>>(s.t)};
573             // eval.block is the loop preheader block, which will be set
574             // elsewhere if the NonLabelDoStmt is itself a target.
575             // eval.localBlocks[0] is the loop header block.
576             eval.localBlocks.emplace_back(nullptr);
577             if (!control.has_value()) {
578               eval.isUnstructured = true; // infinite loop
579               return;
580             }
581             eval.nonNopSuccessor().isNewBlock = true;
582             eval.controlSuccessor = &evaluationList.back();
583             if (std::holds_alternative<parser::ScalarLogicalExpr>(control->u)) {
584               eval.isUnstructured = true; // while loop
585             }
586             // Defer additional processing for an unstructured concurrent loop
587             // to the EndDoStmt, when the loop is known to be unstructured.
588           },
589           [&](const parser::EndDoStmt &) {
590             lower::pft::Evaluation &doEval{evaluationList.front()};
591             eval.controlSuccessor = &doEval;
592             doConstructStack.pop_back();
593             if (parentConstruct->lowerAsStructured()) {
594               return;
595             }
596             // Now that the loop is known to be unstructured, finish concurrent
597             // loop processing, using NonLabelDoStmt information.
598             parentConstruct->constructExit->isNewBlock = true;
599             const auto &doStmt{doEval.getIf<parser::NonLabelDoStmt>()};
600             assert(doStmt && "missing NonLabelDoStmt");
601             auto &control{
602                 std::get<std::optional<parser::LoopControl>>(doStmt->t)};
603             if (!control.has_value()) {
604               return; // infinite loop
605             }
606             const auto *concurrent{
607                 std::get_if<parser::LoopControl::Concurrent>(&control->u)};
608             if (!concurrent) {
609               return;
610             }
611             // Unstructured concurrent loop.  NonLabelDoStmt code accounts
612             // for one concurrent loop dimension.  Reserve preheader,
613             // header, and latch blocks for the remaining dimensions, and
614             // one block for a mask expression.
615             const auto &header{
616                 std::get<parser::ConcurrentHeader>(concurrent->t)};
617             auto dims{std::get<std::list<parser::ConcurrentControl>>(header.t)
618                           .size()};
619             for (; dims > 1; --dims) {
620               doEval.localBlocks.emplace_back(nullptr); // preheader
621               doEval.localBlocks.emplace_back(nullptr); // header
622               eval.localBlocks.emplace_back(nullptr);   // latch
623             }
624             if (std::get<std::optional<parser::ScalarLogicalExpr>>(header.t)) {
625               doEval.localBlocks.emplace_back(nullptr); // mask
626             }
627           },
628           [&](const parser::IfThenStmt &s) {
629             insertConstructName(s, parentConstruct);
630             eval.lexicalSuccessor->isNewBlock = true;
631             lastConstructStmtEvaluation = &eval;
632           },
633           [&](const parser::ElseIfStmt &) {
634             eval.isNewBlock = true;
635             eval.lexicalSuccessor->isNewBlock = true;
636             lastConstructStmtEvaluation->controlSuccessor = &eval;
637             lastConstructStmtEvaluation = &eval;
638           },
639           [&](const parser::ElseStmt &) {
640             eval.isNewBlock = true;
641             lastConstructStmtEvaluation->controlSuccessor = &eval;
642             lastConstructStmtEvaluation = nullptr;
643           },
644           [&](const parser::EndIfStmt &) {
645             if (parentConstruct->lowerAsUnstructured()) {
646               parentConstruct->constructExit->isNewBlock = true;
647             }
648             if (lastConstructStmtEvaluation) {
649               lastConstructStmtEvaluation->controlSuccessor =
650                   parentConstruct->constructExit;
651               lastConstructStmtEvaluation = nullptr;
652             }
653           },
654           [&](const parser::SelectRankStmt &s) {
655             insertConstructName(s, parentConstruct);
656           },
657           [&](const parser::SelectRankCaseStmt &) { eval.isNewBlock = true; },
658           [&](const parser::SelectTypeStmt &s) {
659             insertConstructName(s, parentConstruct);
660           },
661           [&](const parser::TypeGuardStmt &) { eval.isNewBlock = true; },
662 
663           // Constructs - set (unstructured) construct exit targets
664           [&](const parser::AssociateConstruct &) { setConstructExit(eval); },
665           [&](const parser::BlockConstruct &) {
666             // EndBlockStmt may have code.
667             eval.constructExit = &eval.evaluationList->back();
668           },
669           [&](const parser::CaseConstruct &) {
670             setConstructExit(eval);
671             eval.isUnstructured = true;
672           },
673           [&](const parser::ChangeTeamConstruct &) {
674             // EndChangeTeamStmt may have code.
675             eval.constructExit = &eval.evaluationList->back();
676           },
677           [&](const parser::CriticalConstruct &) {
678             // EndCriticalStmt may have code.
679             eval.constructExit = &eval.evaluationList->back();
680           },
681           [&](const parser::DoConstruct &) { setConstructExit(eval); },
682           [&](const parser::IfConstruct &) { setConstructExit(eval); },
683           [&](const parser::SelectRankConstruct &) {
684             setConstructExit(eval);
685             eval.isUnstructured = true;
686           },
687           [&](const parser::SelectTypeConstruct &) {
688             setConstructExit(eval);
689             eval.isUnstructured = true;
690           },
691 
692           [&](const auto &stmt) {
693             using A = std::decay_t<decltype(stmt)>;
694             using IoStmts = std::tuple<parser::BackspaceStmt, parser::CloseStmt,
695                                        parser::EndfileStmt, parser::FlushStmt,
696                                        parser::InquireStmt, parser::OpenStmt,
697                                        parser::ReadStmt, parser::RewindStmt,
698                                        parser::WaitStmt, parser::WriteStmt>;
699             if constexpr (common::HasMember<A, IoStmts>) {
700               analyzeIoBranches(eval, stmt);
701             }
702 
703             /* do nothing */
704           },
705       });
706 
707       // Analyze construct evaluations.
708       if (eval.evaluationList) {
709         analyzeBranches(&eval, *eval.evaluationList);
710       }
711 
712       // Insert branch links for an unstructured IF statement.
713       if (lastIfStmtEvaluation && lastIfStmtEvaluation != &eval) {
714         // eval is the action substatement of an IfStmt.
715         if (eval.lowerAsUnstructured()) {
716           eval.isNewBlock = true;
717           markSuccessorAsNewBlock(eval);
718           lastIfStmtEvaluation->isUnstructured = true;
719         }
720         lastIfStmtEvaluation->controlSuccessor = &eval.nonNopSuccessor();
721         lastIfStmtEvaluation = nullptr;
722       }
723 
724       // Set the successor of the last statement in an IF or SELECT block.
725       if (!eval.controlSuccessor && eval.lexicalSuccessor &&
726           eval.lexicalSuccessor->isIntermediateConstructStmt()) {
727         eval.controlSuccessor = parentConstruct->constructExit;
728         eval.lexicalSuccessor->isNewBlock = true;
729       }
730 
731       // Propagate isUnstructured flag to enclosing construct.
732       if (parentConstruct && eval.isUnstructured) {
733         parentConstruct->isUnstructured = true;
734       }
735 
736       // The successor of a branch starts a new block.
737       if (eval.controlSuccessor && eval.isActionStmt() &&
738           eval.lowerAsUnstructured()) {
739         markSuccessorAsNewBlock(eval);
740       }
741     }
742   }
743 
744   std::unique_ptr<lower::pft::Program> pgm;
745   std::vector<lower::pft::ParentVariant> parentVariantStack;
746   const semantics::SemanticsContext &semanticsContext;
747 
748   /// functionList points to the internal or module procedure function list
749   /// of a FunctionLikeUnit or a ModuleLikeUnit.  It may be null.
750   std::list<lower::pft::FunctionLikeUnit> *functionList{nullptr};
751   std::vector<lower::pft::Evaluation *> constructAndDirectiveStack{};
752   std::vector<lower::pft::Evaluation *> doConstructStack{};
753   /// evaluationListStack is the current nested construct evaluationList state.
754   std::vector<lower::pft::EvaluationList *> evaluationListStack{};
755   llvm::DenseMap<parser::Label, lower::pft::Evaluation *> *labelEvaluationMap{
756       nullptr};
757   lower::pft::SymbolLabelMap *assignSymbolLabelMap{nullptr};
758   std::map<std::string, lower::pft::Evaluation *> constructNameMap{};
759   lower::pft::Evaluation *lastLexicalEvaluation{nullptr};
760 };
761 
762 class PFTDumper {
763 public:
dumpPFT(llvm::raw_ostream & outputStream,lower::pft::Program & pft)764   void dumpPFT(llvm::raw_ostream &outputStream, lower::pft::Program &pft) {
765     for (auto &unit : pft.getUnits()) {
766       std::visit(common::visitors{
767                      [&](lower::pft::BlockDataUnit &unit) {
768                        outputStream << getNodeIndex(unit) << " ";
769                        outputStream << "BlockData: ";
770                        outputStream << "\nEndBlockData\n\n";
771                      },
772                      [&](lower::pft::FunctionLikeUnit &func) {
773                        dumpFunctionLikeUnit(outputStream, func);
774                      },
775                      [&](lower::pft::ModuleLikeUnit &unit) {
776                        dumpModuleLikeUnit(outputStream, unit);
777                      },
778                  },
779                  unit);
780     }
781   }
782 
evaluationName(lower::pft::Evaluation & eval)783   llvm::StringRef evaluationName(lower::pft::Evaluation &eval) {
784     return eval.visit(common::visitors{
785         [](const auto &parseTreeNode) {
786           return parser::ParseTreeDumper::GetNodeName(parseTreeNode);
787         },
788     });
789   }
790 
dumpEvaluationList(llvm::raw_ostream & outputStream,lower::pft::EvaluationList & evaluationList,int indent=1)791   void dumpEvaluationList(llvm::raw_ostream &outputStream,
792                           lower::pft::EvaluationList &evaluationList,
793                           int indent = 1) {
794     static const std::string white{"                                      ++"};
795     std::string indentString{white.substr(0, indent * 2)};
796     for (lower::pft::Evaluation &eval : evaluationList) {
797       llvm::StringRef name{evaluationName(eval)};
798       std::string bang{eval.isUnstructured ? "!" : ""};
799       if (eval.isConstruct() || eval.isDirective()) {
800         outputStream << indentString << "<<" << name << bang << ">>";
801         if (eval.constructExit) {
802           outputStream << " -> " << eval.constructExit->printIndex;
803         }
804         outputStream << '\n';
805         dumpEvaluationList(outputStream, *eval.evaluationList, indent + 1);
806         outputStream << indentString << "<<End " << name << bang << ">>\n";
807         continue;
808       }
809       outputStream << indentString;
810       if (eval.printIndex) {
811         outputStream << eval.printIndex << ' ';
812       }
813       if (eval.isNewBlock) {
814         outputStream << '^';
815       }
816       if (eval.localBlocks.size()) {
817         outputStream << '*';
818       }
819       outputStream << name << bang;
820       if (eval.isActionStmt() || eval.isConstructStmt()) {
821         if (eval.controlSuccessor) {
822           outputStream << " -> " << eval.controlSuccessor->printIndex;
823         }
824       }
825       if (eval.position.size()) {
826         outputStream << ": " << eval.position.ToString();
827       }
828       outputStream << '\n';
829     }
830   }
831 
dumpFunctionLikeUnit(llvm::raw_ostream & outputStream,lower::pft::FunctionLikeUnit & functionLikeUnit)832   void dumpFunctionLikeUnit(llvm::raw_ostream &outputStream,
833                             lower::pft::FunctionLikeUnit &functionLikeUnit) {
834     outputStream << getNodeIndex(functionLikeUnit) << " ";
835     llvm::StringRef unitKind{};
836     std::string name{};
837     std::string header{};
838     if (functionLikeUnit.beginStmt) {
839       functionLikeUnit.beginStmt->visit(common::visitors{
840           [&](const parser::Statement<parser::ProgramStmt> &statement) {
841             unitKind = "Program";
842             name = statement.statement.v.ToString();
843           },
844           [&](const parser::Statement<parser::FunctionStmt> &statement) {
845             unitKind = "Function";
846             name = std::get<parser::Name>(statement.statement.t).ToString();
847             header = statement.source.ToString();
848           },
849           [&](const parser::Statement<parser::SubroutineStmt> &statement) {
850             unitKind = "Subroutine";
851             name = std::get<parser::Name>(statement.statement.t).ToString();
852             header = statement.source.ToString();
853           },
854           [&](const parser::Statement<parser::MpSubprogramStmt> &statement) {
855             unitKind = "MpSubprogram";
856             name = statement.statement.v.ToString();
857             header = statement.source.ToString();
858           },
859           [&](const auto &) {},
860       });
861     } else {
862       unitKind = "Program";
863       name = "<anonymous>";
864     }
865     outputStream << unitKind << ' ' << name;
866     if (header.size())
867       outputStream << ": " << header;
868     outputStream << '\n';
869     dumpEvaluationList(outputStream, functionLikeUnit.evaluationList);
870     if (!functionLikeUnit.nestedFunctions.empty()) {
871       outputStream << "\nContains\n";
872       for (auto &func : functionLikeUnit.nestedFunctions)
873         dumpFunctionLikeUnit(outputStream, func);
874       outputStream << "EndContains\n";
875     }
876     outputStream << "End" << unitKind << ' ' << name << "\n\n";
877   }
878 
dumpModuleLikeUnit(llvm::raw_ostream & outputStream,lower::pft::ModuleLikeUnit & moduleLikeUnit)879   void dumpModuleLikeUnit(llvm::raw_ostream &outputStream,
880                           lower::pft::ModuleLikeUnit &moduleLikeUnit) {
881     outputStream << getNodeIndex(moduleLikeUnit) << " ";
882     outputStream << "ModuleLike: ";
883     outputStream << "\nContains\n";
884     for (auto &func : moduleLikeUnit.nestedFunctions)
885       dumpFunctionLikeUnit(outputStream, func);
886     outputStream << "EndContains\nEndModuleLike\n\n";
887   }
888 
889   template <typename T>
getNodeIndex(const T & node)890   std::size_t getNodeIndex(const T &node) {
891     auto addr{static_cast<const void *>(&node)};
892     auto it{nodeIndexes.find(addr)};
893     if (it != nodeIndexes.end()) {
894       return it->second;
895     }
896     nodeIndexes.try_emplace(addr, nextIndex);
897     return nextIndex++;
898   }
getNodeIndex(const lower::pft::Program &)899   std::size_t getNodeIndex(const lower::pft::Program &) { return 0; }
900 
901 private:
902   llvm::DenseMap<const void *, std::size_t> nodeIndexes;
903   std::size_t nextIndex{1}; // 0 is the root
904 };
905 
906 } // namespace
907 
908 template <typename A, typename T>
909 static lower::pft::FunctionLikeUnit::FunctionStatement
getFunctionStmt(const T & func)910 getFunctionStmt(const T &func) {
911   lower::pft::FunctionLikeUnit::FunctionStatement result{
912       std::get<parser::Statement<A>>(func.t)};
913   return result;
914 }
915 template <typename A, typename T>
getModuleStmt(const T & mod)916 static lower::pft::ModuleLikeUnit::ModuleStatement getModuleStmt(const T &mod) {
917   lower::pft::ModuleLikeUnit::ModuleStatement result{
918       std::get<parser::Statement<A>>(mod.t)};
919   return result;
920 }
921 
getSymbol(std::optional<lower::pft::FunctionLikeUnit::FunctionStatement> & beginStmt)922 static const semantics::Symbol *getSymbol(
923     std::optional<lower::pft::FunctionLikeUnit::FunctionStatement> &beginStmt) {
924   if (!beginStmt)
925     return nullptr;
926 
927   const auto *symbol = beginStmt->visit(common::visitors{
928       [](const parser::Statement<parser::ProgramStmt> &stmt)
929           -> const semantics::Symbol * { return stmt.statement.v.symbol; },
930       [](const parser::Statement<parser::FunctionStmt> &stmt)
931           -> const semantics::Symbol * {
932         return std::get<parser::Name>(stmt.statement.t).symbol;
933       },
934       [](const parser::Statement<parser::SubroutineStmt> &stmt)
935           -> const semantics::Symbol * {
936         return std::get<parser::Name>(stmt.statement.t).symbol;
937       },
938       [](const parser::Statement<parser::MpSubprogramStmt> &stmt)
939           -> const semantics::Symbol * { return stmt.statement.v.symbol; },
940       [](const auto &) -> const semantics::Symbol * {
941         llvm_unreachable("unknown FunctionLike beginStmt");
942         return nullptr;
943       }});
944   assert(symbol && "parser::Name must have resolved symbol");
945   return symbol;
946 }
947 
lowerAsStructured() const948 bool Fortran::lower::pft::Evaluation::lowerAsStructured() const {
949   return !lowerAsUnstructured();
950 }
951 
lowerAsUnstructured() const952 bool Fortran::lower::pft::Evaluation::lowerAsUnstructured() const {
953   return isUnstructured || clDisableStructuredFir;
954 }
955 
956 lower::pft::FunctionLikeUnit *
getOwningProcedure() const957 Fortran::lower::pft::Evaluation::getOwningProcedure() const {
958   return parentVariant.visit(common::visitors{
959       [](lower::pft::FunctionLikeUnit &c) { return &c; },
960       [&](lower::pft::Evaluation &c) { return c.getOwningProcedure(); },
961       [](auto &) -> lower::pft::FunctionLikeUnit * { return nullptr; },
962   });
963 }
964 
965 namespace {
966 /// This helper class is for sorting the symbols in the symbol table. We want
967 /// the symbols in an order such that a symbol will be visited after those it
968 /// depends upon. Otherwise this sort is stable and preserves the order of the
969 /// symbol table, which is sorted by name.
970 struct SymbolDependenceDepth {
SymbolDependenceDepth__anon6f56359d4311::SymbolDependenceDepth971   explicit SymbolDependenceDepth(
972       std::vector<std::vector<lower::pft::Variable>> &vars)
973       : vars{vars} {}
974 
975   // Recursively visit each symbol to determine the height of its dependence on
976   // other symbols.
analyze__anon6f56359d4311::SymbolDependenceDepth977   int analyze(const semantics::Symbol &sym) {
978     auto done = seen.insert(&sym);
979     if (!done.second)
980       return 0;
981     if (semantics::IsProcedure(sym)) {
982       // TODO: add declaration?
983       return 0;
984     }
985     if (sym.has<semantics::UseDetails>() ||
986         sym.has<semantics::HostAssocDetails>() ||
987         sym.has<semantics::NamelistDetails>() ||
988         sym.has<semantics::MiscDetails>()) {
989       // FIXME: do we want to do anything with any of these?
990       return 0;
991     }
992 
993     // Symbol must be something lowering will have to allocate.
994     bool global = semantics::IsSaved(sym);
995     int depth = 0;
996     const auto *symTy = sym.GetType();
997     assert(symTy && "symbol must have a type");
998 
999     // check CHARACTER's length
1000     if (symTy->category() == semantics::DeclTypeSpec::Character)
1001       if (auto e = symTy->characterTypeSpec().length().GetExplicit())
1002         for (const auto &s : evaluate::CollectSymbols(*e))
1003           depth = std::max(analyze(s) + 1, depth);
1004 
1005     if (const auto *details = sym.detailsIf<semantics::ObjectEntityDetails>()) {
1006       auto doExplicit = [&](const auto &bound) {
1007         if (bound.isExplicit()) {
1008           semantics::SomeExpr e{*bound.GetExplicit()};
1009           for (const auto &s : evaluate::CollectSymbols(e))
1010             depth = std::max(analyze(s) + 1, depth);
1011         }
1012       };
1013       // handle any symbols in array bound declarations
1014       for (const auto &subs : details->shape()) {
1015         doExplicit(subs.lbound());
1016         doExplicit(subs.ubound());
1017       }
1018       // handle any symbols in coarray bound declarations
1019       for (const auto &subs : details->coshape()) {
1020         doExplicit(subs.lbound());
1021         doExplicit(subs.ubound());
1022       }
1023       // handle any symbols in initialization expressions
1024       if (auto e = details->init()) {
1025         // A PARAMETER may not be marked as implicitly SAVE, so set the flag.
1026         global = true;
1027         for (const auto &s : evaluate::CollectSymbols(*e))
1028           depth = std::max(analyze(s) + 1, depth);
1029       }
1030     }
1031     adjustSize(depth + 1);
1032     vars[depth].emplace_back(sym, global, depth);
1033     if (Fortran::semantics::IsAllocatable(sym))
1034       vars[depth].back().setHeapAlloc();
1035     if (Fortran::semantics::IsPointer(sym))
1036       vars[depth].back().setPointer();
1037     if (sym.attrs().test(Fortran::semantics::Attr::TARGET))
1038       vars[depth].back().setTarget();
1039     return depth;
1040   }
1041 
1042   // Save the final list of symbols as a single vector and free the rest.
finalize__anon6f56359d4311::SymbolDependenceDepth1043   void finalize() {
1044     for (int i = 1, end = vars.size(); i < end; ++i)
1045       vars[0].insert(vars[0].end(), vars[i].begin(), vars[i].end());
1046     vars.resize(1);
1047   }
1048 
1049 private:
1050   // Make sure the table is of appropriate size.
adjustSize__anon6f56359d4311::SymbolDependenceDepth1051   void adjustSize(std::size_t size) {
1052     if (vars.size() < size)
1053       vars.resize(size);
1054   }
1055 
1056   llvm::SmallSet<const semantics::Symbol *, 32> seen;
1057   std::vector<std::vector<lower::pft::Variable>> &vars;
1058 };
1059 } // namespace
1060 
processSymbolTable(const semantics::Scope & scope)1061 void Fortran::lower::pft::FunctionLikeUnit::processSymbolTable(
1062     const semantics::Scope &scope) {
1063   // TODO: handle equivalence and common blocks
1064   if (!scope.equivalenceSets().empty()) {
1065     llvm::errs() << "TODO: equivalence not yet handled in lowering.\n"
1066                  << "note: equivalence used in "
1067                  << (scope.GetName() && !scope.GetName()->empty()
1068                          ? scope.GetName()->ToString()
1069                          : "unnamed program"s)
1070                  << "\n";
1071     exit(1);
1072   }
1073   SymbolDependenceDepth sdd{varList};
1074   for (const auto &iter : scope)
1075     sdd.analyze(iter.second.get());
1076   sdd.finalize();
1077 }
1078 
FunctionLikeUnit(const parser::MainProgram & func,const lower::pft::ParentVariant & parent,const semantics::SemanticsContext & semanticsContext)1079 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1080     const parser::MainProgram &func, const lower::pft::ParentVariant &parent,
1081     const semantics::SemanticsContext &semanticsContext)
1082     : ProgramUnit{func, parent}, endStmt{
1083                                      getFunctionStmt<parser::EndProgramStmt>(
1084                                          func)} {
1085   const auto &ps{
1086       std::get<std::optional<parser::Statement<parser::ProgramStmt>>>(func.t)};
1087   if (ps.has_value()) {
1088     FunctionStatement begin{ps.value()};
1089     beginStmt = begin;
1090     symbol = getSymbol(beginStmt);
1091     processSymbolTable(*symbol->scope());
1092   } else {
1093     processSymbolTable(semanticsContext.FindScope(
1094         std::get<parser::Statement<parser::EndProgramStmt>>(func.t).source));
1095   }
1096 }
1097 
FunctionLikeUnit(const parser::FunctionSubprogram & func,const lower::pft::ParentVariant & parent,const semantics::SemanticsContext &)1098 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1099     const parser::FunctionSubprogram &func,
1100     const lower::pft::ParentVariant &parent,
1101     const semantics::SemanticsContext &)
1102     : ProgramUnit{func, parent},
1103       beginStmt{getFunctionStmt<parser::FunctionStmt>(func)},
1104       endStmt{getFunctionStmt<parser::EndFunctionStmt>(func)}, symbol{getSymbol(
1105                                                                    beginStmt)} {
1106   processSymbolTable(*symbol->scope());
1107 }
1108 
FunctionLikeUnit(const parser::SubroutineSubprogram & func,const lower::pft::ParentVariant & parent,const semantics::SemanticsContext &)1109 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1110     const parser::SubroutineSubprogram &func,
1111     const lower::pft::ParentVariant &parent,
1112     const semantics::SemanticsContext &)
1113     : ProgramUnit{func, parent},
1114       beginStmt{getFunctionStmt<parser::SubroutineStmt>(func)},
1115       endStmt{getFunctionStmt<parser::EndSubroutineStmt>(func)},
1116       symbol{getSymbol(beginStmt)} {
1117   processSymbolTable(*symbol->scope());
1118 }
1119 
FunctionLikeUnit(const parser::SeparateModuleSubprogram & func,const lower::pft::ParentVariant & parent,const semantics::SemanticsContext &)1120 Fortran::lower::pft::FunctionLikeUnit::FunctionLikeUnit(
1121     const parser::SeparateModuleSubprogram &func,
1122     const lower::pft::ParentVariant &parent,
1123     const semantics::SemanticsContext &)
1124     : ProgramUnit{func, parent},
1125       beginStmt{getFunctionStmt<parser::MpSubprogramStmt>(func)},
1126       endStmt{getFunctionStmt<parser::EndMpSubprogramStmt>(func)},
1127       symbol{getSymbol(beginStmt)} {
1128   processSymbolTable(*symbol->scope());
1129 }
1130 
ModuleLikeUnit(const parser::Module & m,const lower::pft::ParentVariant & parent)1131 Fortran::lower::pft::ModuleLikeUnit::ModuleLikeUnit(
1132     const parser::Module &m, const lower::pft::ParentVariant &parent)
1133     : ProgramUnit{m, parent}, beginStmt{getModuleStmt<parser::ModuleStmt>(m)},
1134       endStmt{getModuleStmt<parser::EndModuleStmt>(m)} {}
1135 
ModuleLikeUnit(const parser::Submodule & m,const lower::pft::ParentVariant & parent)1136 Fortran::lower::pft::ModuleLikeUnit::ModuleLikeUnit(
1137     const parser::Submodule &m, const lower::pft::ParentVariant &parent)
1138     : ProgramUnit{m, parent}, beginStmt{getModuleStmt<parser::SubmoduleStmt>(
1139                                   m)},
1140       endStmt{getModuleStmt<parser::EndSubmoduleStmt>(m)} {}
1141 
BlockDataUnit(const parser::BlockData & bd,const lower::pft::ParentVariant & parent)1142 Fortran::lower::pft::BlockDataUnit::BlockDataUnit(
1143     const parser::BlockData &bd, const lower::pft::ParentVariant &parent)
1144     : ProgramUnit{bd, parent} {}
1145 
1146 std::unique_ptr<lower::pft::Program>
createPFT(const parser::Program & root,const semantics::SemanticsContext & semanticsContext)1147 Fortran::lower::createPFT(const parser::Program &root,
1148                           const semantics::SemanticsContext &semanticsContext) {
1149   PFTBuilder walker(semanticsContext);
1150   Walk(root, walker);
1151   return walker.result();
1152 }
1153 
dumpPFT(llvm::raw_ostream & outputStream,lower::pft::Program & pft)1154 void Fortran::lower::dumpPFT(llvm::raw_ostream &outputStream,
1155                              lower::pft::Program &pft) {
1156   PFTDumper{}.dumpPFT(outputStream, pft);
1157 }
1158 
dump()1159 void Fortran::lower::pft::Program::dump() { dumpPFT(llvm::errs(), *this); }
1160