Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1 | //===-- Bridge.cpp -- bridge to lower to MLIR -----------------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/ |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #include "flang/Lower/Bridge.h" |
Kareem Ergawy | e532241 | 2024-12-18 09:19:45 +0100 | [diff] [blame] | 14 | |
Valentin Clement | c5cf1b9 | 2022-03-07 21:22:28 +0100 | [diff] [blame] | 15 | #include "flang/Lower/Allocatable.h" |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 16 | #include "flang/Lower/CallInterface.h" |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 17 | #include "flang/Lower/Coarray.h" |
Jean Perier | e78e4a1 | 2022-12-01 11:09:35 +0100 | [diff] [blame] | 18 | #include "flang/Lower/ConvertCall.h" |
Valentin Clement | dc6a344 | 2022-02-03 10:40:19 +0100 | [diff] [blame] | 19 | #include "flang/Lower/ConvertExpr.h" |
Jean Perier | c14ef2d | 2022-10-24 15:35:19 +0200 | [diff] [blame] | 20 | #include "flang/Lower/ConvertExprToHLFIR.h" |
Valentin Clement | dc6a344 | 2022-02-03 10:40:19 +0100 | [diff] [blame] | 21 | #include "flang/Lower/ConvertType.h" |
Valentin Clement | 2c2e5a5 | 2022-02-07 09:12:17 +0100 | [diff] [blame] | 22 | #include "flang/Lower/ConvertVariable.h" |
Valentin Clement (バレンタイン クレメン) | d4c519e | 2024-08-29 22:37:20 -0700 | [diff] [blame] | 23 | #include "flang/Lower/Cuda.h" |
Kareem Ergawy | e532241 | 2024-12-18 09:19:45 +0100 | [diff] [blame] | 24 | #include "flang/Lower/DirectivesCommon.h" |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 25 | #include "flang/Lower/HostAssociations.h" |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 26 | #include "flang/Lower/IO.h" |
Valentin Clement | f9704f0 | 2022-02-24 21:09:40 +0100 | [diff] [blame] | 27 | #include "flang/Lower/IterationSpace.h" |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 28 | #include "flang/Lower/Mangler.h" |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 29 | #include "flang/Lower/OpenACC.h" |
Shraiysh Vaishay | e0f549a | 2022-03-10 22:40:23 +0530 | [diff] [blame] | 30 | #include "flang/Lower/OpenMP.h" |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 31 | #include "flang/Lower/PFTBuilder.h" |
Valentin Clement | aab4263 | 2022-02-01 20:53:00 +0100 | [diff] [blame] | 32 | #include "flang/Lower/Runtime.h" |
Valentin Clement | d0b70a0 | 2022-02-23 19:48:07 +0100 | [diff] [blame] | 33 | #include "flang/Lower/StatementContext.h" |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 34 | #include "flang/Lower/Support/Utils.h" |
Valentin Clement | 2a59ead | 2022-02-24 18:11:41 +0100 | [diff] [blame] | 35 | #include "flang/Optimizer/Builder/BoxValue.h" |
Valentin Clement (バレンタイン クレメン) | 9165848 | 2025-01-03 14:37:14 -0800 | [diff] [blame] | 36 | #include "flang/Optimizer/Builder/CUFCommon.h" |
Valentin Clement | 37e84d9 | 2022-02-25 18:21:44 +0100 | [diff] [blame] | 37 | #include "flang/Optimizer/Builder/Character.h" |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 38 | #include "flang/Optimizer/Builder/FIRBuilder.h" |
Valentin Clement | f8ea349 | 2022-12-02 15:51:01 +0100 | [diff] [blame] | 39 | #include "flang/Optimizer/Builder/Runtime/Assign.h" |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 40 | #include "flang/Optimizer/Builder/Runtime/Character.h" |
Valentin Clement | 90e9fcb | 2022-10-31 11:02:50 +0100 | [diff] [blame] | 41 | #include "flang/Optimizer/Builder/Runtime/Derived.h" |
Jonathon Penix | 0ec3ac9 | 2022-07-19 11:47:25 -0700 | [diff] [blame] | 42 | #include "flang/Optimizer/Builder/Runtime/EnvironmentDefaults.h" |
vdonaldson | 6003be7 | 2024-12-04 16:21:11 -0500 | [diff] [blame] | 43 | #include "flang/Optimizer/Builder/Runtime/Exceptions.h" |
David Truby | 8d53866 | 2024-04-29 14:16:25 +0100 | [diff] [blame] | 44 | #include "flang/Optimizer/Builder/Runtime/Main.h" |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 45 | #include "flang/Optimizer/Builder/Runtime/Ragged.h" |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 46 | #include "flang/Optimizer/Builder/Runtime/Stop.h" |
Valentin Clement | 5b66cc1 | 2022-06-10 08:50:40 +0200 | [diff] [blame] | 47 | #include "flang/Optimizer/Builder/Todo.h" |
Valentin Clement (バレンタイン クレメン) | 45daa4f | 2024-05-17 09:37:53 -0700 | [diff] [blame] | 48 | #include "flang/Optimizer/Dialect/CUF/Attributes/CUFAttr.h" |
| 49 | #include "flang/Optimizer/Dialect/CUF/CUFOps.h" |
Valentin Clement | 78a127a | 2022-03-08 20:17:48 +0100 | [diff] [blame] | 50 | #include "flang/Optimizer/Dialect/FIRAttr.h" |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 51 | #include "flang/Optimizer/Dialect/FIRDialect.h" |
| 52 | #include "flang/Optimizer/Dialect/FIROps.h" |
Renaud-K | b07ef9e | 2023-03-08 18:39:40 -0800 | [diff] [blame] | 53 | #include "flang/Optimizer/Dialect/Support/FIRContext.h" |
Jean Perier | dd73bfa | 2022-11-15 12:01:21 +0100 | [diff] [blame] | 54 | #include "flang/Optimizer/HLFIR/HLFIROps.h" |
jeanPerier | e59e848 | 2023-12-06 14:20:06 +0100 | [diff] [blame] | 55 | #include "flang/Optimizer/Support/DataLayout.h" |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 56 | #include "flang/Optimizer/Support/FatalError.h" |
Valentin Clement | 17d7134 | 2022-03-02 18:26:13 +0100 | [diff] [blame] | 57 | #include "flang/Optimizer/Support/InternalNames.h" |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 58 | #include "flang/Optimizer/Transforms/Passes.h" |
| 59 | #include "flang/Parser/parse-tree.h" |
Michael Kruse | c91ba04 | 2024-12-06 15:29:00 +0100 | [diff] [blame] | 60 | #include "flang/Runtime/iostat-consts.h" |
Valentin Clement | 6393d2e | 2022-11-17 10:53:13 +0100 | [diff] [blame] | 61 | #include "flang/Semantics/runtime-type-info.h" |
Sergio Afonso | 29aa749 | 2023-03-29 18:13:48 +0100 | [diff] [blame] | 62 | #include "flang/Semantics/symbol.h" |
Valentin Clement | e641c29 | 2022-02-17 18:23:22 +0100 | [diff] [blame] | 63 | #include "flang/Semantics/tools.h" |
Michael Kruse | b815a39 | 2025-02-06 15:29:10 +0100 | [diff] [blame] | 64 | #include "flang/Support/Version.h" |
Kiran Chandramohan | ae37bb9 | 2022-02-08 23:01:39 +0000 | [diff] [blame] | 65 | #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" |
Asher Mancinelli | 6b52fb2 | 2025-02-10 08:21:22 -0800 | [diff] [blame] | 66 | #include "mlir/IR/BuiltinAttributes.h" |
Valentin Clement (バレンタイン クレメン) | 0bc710f | 2024-05-21 12:42:30 -0700 | [diff] [blame] | 67 | #include "mlir/IR/Matchers.h" |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 68 | #include "mlir/IR/PatternMatch.h" |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 69 | #include "mlir/Parser/Parser.h" |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 70 | #include "mlir/Transforms/RegionUtils.h" |
Valentin Clement | dda0163 | 2023-02-07 09:15:54 +0100 | [diff] [blame] | 71 | #include "llvm/ADT/SmallVector.h" |
Valentin Clement | 6393d2e | 2022-11-17 10:53:13 +0100 | [diff] [blame] | 72 | #include "llvm/ADT/StringSet.h" |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 73 | #include "llvm/Support/CommandLine.h" |
| 74 | #include "llvm/Support/Debug.h" |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 75 | #include "llvm/Support/ErrorHandling.h" |
Kiran Chandramohan | eef0210 | 2023-01-19 16:49:26 +0000 | [diff] [blame] | 76 | #include "llvm/Support/FileSystem.h" |
| 77 | #include "llvm/Support/Path.h" |
Sergio Afonso | 837bff1 | 2024-01-30 13:45:56 +0000 | [diff] [blame] | 78 | #include "llvm/Target/TargetMachine.h" |
Kazu Hirata | 4d4d478 | 2023-01-07 20:55:47 -0800 | [diff] [blame] | 79 | #include <optional> |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 80 | |
| 81 | #define DEBUG_TYPE "flang-lower-bridge" |
| 82 | |
| 83 | static llvm::cl::opt<bool> dumpBeforeFir( |
| 84 | "fdebug-dump-pre-fir", llvm::cl::init(false), |
| 85 | llvm::cl::desc("dump the Pre-FIR tree prior to FIR generation")); |
| 86 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 87 | static llvm::cl::opt<bool> forceLoopToExecuteOnce( |
| 88 | "always-execute-loop-body", llvm::cl::init(false), |
| 89 | llvm::cl::desc("force the body of a loop to execute at least once")); |
| 90 | |
Valentin Clement | 9aeb7f0 | 2022-03-16 17:10:31 +0100 | [diff] [blame] | 91 | namespace { |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 92 | /// Information for generating a structured or unstructured increment loop. |
| 93 | struct IncrementLoopInfo { |
| 94 | template <typename T> |
| 95 | explicit IncrementLoopInfo(Fortran::semantics::Symbol &sym, const T &lower, |
| 96 | const T &upper, const std::optional<T> &step, |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 97 | bool isUnordered = false) |
Krzysztof Parzyszek | dd376f8 | 2023-12-04 08:27:57 -0600 | [diff] [blame] | 98 | : loopVariableSym{&sym}, lowerExpr{Fortran::semantics::GetExpr(lower)}, |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 99 | upperExpr{Fortran::semantics::GetExpr(upper)}, |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 100 | stepExpr{Fortran::semantics::GetExpr(step)}, isUnordered{isUnordered} {} |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 101 | |
| 102 | IncrementLoopInfo(IncrementLoopInfo &&) = default; |
Krzysztof Parzyszek | dd376f8 | 2023-12-04 08:27:57 -0600 | [diff] [blame] | 103 | IncrementLoopInfo &operator=(IncrementLoopInfo &&x) = default; |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 104 | |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 105 | bool isStructured() const { return !headerBlock; } |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 106 | |
| 107 | mlir::Type getLoopVariableType() const { |
| 108 | assert(loopVariable && "must be set"); |
| 109 | return fir::unwrapRefType(loopVariable.getType()); |
| 110 | } |
| 111 | |
V Donaldson | 335b399 | 2023-08-07 13:29:17 -0700 | [diff] [blame] | 112 | bool hasLocalitySpecs() const { |
| 113 | return !localSymList.empty() || !localInitSymList.empty() || |
khaki3 | f11e08f | 2024-06-10 08:41:05 -0700 | [diff] [blame] | 114 | !reduceSymList.empty() || !sharedSymList.empty(); |
V Donaldson | 335b399 | 2023-08-07 13:29:17 -0700 | [diff] [blame] | 115 | } |
| 116 | |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 117 | // Data members common to both structured and unstructured loops. |
Krzysztof Parzyszek | dd376f8 | 2023-12-04 08:27:57 -0600 | [diff] [blame] | 118 | const Fortran::semantics::Symbol *loopVariableSym; |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 119 | const Fortran::lower::SomeExpr *lowerExpr; |
| 120 | const Fortran::lower::SomeExpr *upperExpr; |
| 121 | const Fortran::lower::SomeExpr *stepExpr; |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 122 | const Fortran::lower::SomeExpr *maskExpr = nullptr; |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 123 | bool isUnordered; // do concurrent, forall |
V Donaldson | 335b399 | 2023-08-07 13:29:17 -0700 | [diff] [blame] | 124 | llvm::SmallVector<const Fortran::semantics::Symbol *> localSymList; |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 125 | llvm::SmallVector<const Fortran::semantics::Symbol *> localInitSymList; |
khaki3 | f11e08f | 2024-06-10 08:41:05 -0700 | [diff] [blame] | 126 | llvm::SmallVector< |
| 127 | std::pair<fir::ReduceOperationEnum, const Fortran::semantics::Symbol *>> |
| 128 | reduceSymList; |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 129 | llvm::SmallVector<const Fortran::semantics::Symbol *> sharedSymList; |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 130 | mlir::Value loopVariable = nullptr; |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 131 | |
| 132 | // Data members for structured loops. |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 133 | fir::DoLoopOp doLoop = nullptr; |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 134 | |
| 135 | // Data members for unstructured loops. |
Diana Picus | a159128 | 2022-05-31 10:55:56 +0000 | [diff] [blame] | 136 | bool hasRealControl = false; |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 137 | mlir::Value tripVariable = nullptr; |
Leandro Lupori | 3dbb055 | 2023-09-21 15:59:35 +0200 | [diff] [blame] | 138 | mlir::Value stepVariable = nullptr; |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 139 | mlir::Block *headerBlock = nullptr; // loop entry and test block |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 140 | mlir::Block *maskBlock = nullptr; // concurrent loop mask block |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 141 | mlir::Block *bodyBlock = nullptr; // first loop body block |
| 142 | mlir::Block *exitBlock = nullptr; // loop exit target block |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 143 | }; |
| 144 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 145 | /// Information to support stack management, object deallocation, and |
| 146 | /// object finalization at early and normal construct exits. |
| 147 | struct ConstructContext { |
| 148 | explicit ConstructContext(Fortran::lower::pft::Evaluation &eval, |
| 149 | Fortran::lower::StatementContext &stmtCtx) |
| 150 | : eval{eval}, stmtCtx{stmtCtx} {} |
| 151 | |
| 152 | Fortran::lower::pft::Evaluation &eval; // construct eval |
| 153 | Fortran::lower::StatementContext &stmtCtx; // construct exit code |
jeanPerier | d1aa9ba | 2024-06-03 17:20:07 +0200 | [diff] [blame] | 154 | std::optional<hlfir::Entity> selector; // construct selector, if any. |
| 155 | bool pushedScope = false; // was a scoped pushed for this construct? |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 156 | }; |
| 157 | |
jeanPerier | 66d5ca2 | 2024-07-02 15:19:49 +0200 | [diff] [blame] | 158 | /// Helper to gather the lower bounds of array components with non deferred |
| 159 | /// shape when they are not all ones. Return an empty array attribute otherwise. |
| 160 | static mlir::DenseI64ArrayAttr |
| 161 | gatherComponentNonDefaultLowerBounds(mlir::Location loc, |
| 162 | mlir::MLIRContext *mlirContext, |
| 163 | const Fortran::semantics::Symbol &sym) { |
| 164 | if (Fortran::semantics::IsAllocatableOrObjectPointer(&sym)) |
| 165 | return {}; |
| 166 | mlir::DenseI64ArrayAttr lbs_attr; |
| 167 | if (const auto *objDetails = |
| 168 | sym.detailsIf<Fortran::semantics::ObjectEntityDetails>()) { |
| 169 | llvm::SmallVector<std::int64_t> lbs; |
| 170 | bool hasNonDefaultLbs = false; |
| 171 | for (const Fortran::semantics::ShapeSpec &bounds : objDetails->shape()) |
| 172 | if (auto lb = bounds.lbound().GetExplicit()) { |
| 173 | if (auto constant = Fortran::evaluate::ToInt64(*lb)) { |
| 174 | hasNonDefaultLbs |= (*constant != 1); |
| 175 | lbs.push_back(*constant); |
| 176 | } else { |
| 177 | TODO(loc, "generate fir.dt_component for length parametrized derived " |
| 178 | "types"); |
| 179 | } |
| 180 | } |
| 181 | if (hasNonDefaultLbs) { |
| 182 | assert(static_cast<int>(lbs.size()) == sym.Rank() && |
| 183 | "expected component bounds to be constant or deferred"); |
| 184 | lbs_attr = mlir::DenseI64ArrayAttr::get(mlirContext, lbs); |
| 185 | } |
| 186 | } |
| 187 | return lbs_attr; |
| 188 | } |
| 189 | |
| 190 | // Helper class to generate name of fir.global containing component explicit |
| 191 | // default value for objects, and initial procedure target for procedure pointer |
| 192 | // components. |
| 193 | static mlir::FlatSymbolRefAttr gatherComponentInit( |
| 194 | mlir::Location loc, Fortran::lower::AbstractConverter &converter, |
| 195 | const Fortran::semantics::Symbol &sym, fir::RecordType derivedType) { |
| 196 | mlir::MLIRContext *mlirContext = &converter.getMLIRContext(); |
| 197 | // Return procedure target mangled name for procedure pointer components. |
| 198 | if (const auto *procPtr = |
| 199 | sym.detailsIf<Fortran::semantics::ProcEntityDetails>()) { |
| 200 | if (std::optional<const Fortran::semantics::Symbol *> maybeInitSym = |
| 201 | procPtr->init()) { |
| 202 | // So far, do not make distinction between p => NULL() and p without init, |
| 203 | // f18 always initialize pointers to NULL anyway. |
| 204 | if (!*maybeInitSym) |
| 205 | return {}; |
| 206 | return mlir::FlatSymbolRefAttr::get(mlirContext, |
| 207 | converter.mangleName(**maybeInitSym)); |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | const auto *objDetails = |
| 212 | sym.detailsIf<Fortran::semantics::ObjectEntityDetails>(); |
| 213 | if (!objDetails || !objDetails->init().has_value()) |
| 214 | return {}; |
| 215 | // Object component initial value. Semantic package component object default |
| 216 | // value into compiler generated symbols that are lowered as read-only |
| 217 | // fir.global. Get the name of this global. |
| 218 | std::string name = fir::NameUniquer::getComponentInitName( |
| 219 | derivedType.getName(), toStringRef(sym.name())); |
| 220 | return mlir::FlatSymbolRefAttr::get(mlirContext, name); |
| 221 | } |
| 222 | |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 223 | /// Helper class to generate the runtime type info global data and the |
| 224 | /// fir.type_info operations that contain the dipatch tables (if any). |
| 225 | /// The type info global data is required to describe the derived type to the |
| 226 | /// runtime so that it can operate over it. |
| 227 | /// It must be ensured these operations will be generated for every derived type |
| 228 | /// lowered in the current translated unit. However, these operations |
Valentin Clement | 9aeb7f0 | 2022-03-16 17:10:31 +0100 | [diff] [blame] | 229 | /// cannot be generated before FuncOp have been created for functions since the |
| 230 | /// initializers may take their address (e.g for type bound procedures). This |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 231 | /// class allows registering all the required type info while it is not |
| 232 | /// possible to create GlobalOp/TypeInfoOp, and to generate this data afte |
| 233 | /// function lowering. |
| 234 | class TypeInfoConverter { |
Valentin Clement | 9aeb7f0 | 2022-03-16 17:10:31 +0100 | [diff] [blame] | 235 | /// Store the location and symbols of derived type info to be generated. |
| 236 | /// The location of the derived type instantiation is also stored because |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 237 | /// runtime type descriptor symbols are compiler generated and cannot be |
| 238 | /// mapped to user code on their own. |
| 239 | struct TypeInfo { |
Valentin Clement | 9aeb7f0 | 2022-03-16 17:10:31 +0100 | [diff] [blame] | 240 | Fortran::semantics::SymbolRef symbol; |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 241 | const Fortran::semantics::DerivedTypeSpec &typeSpec; |
| 242 | fir::RecordType type; |
Valentin Clement | 9aeb7f0 | 2022-03-16 17:10:31 +0100 | [diff] [blame] | 243 | mlir::Location loc; |
| 244 | }; |
| 245 | |
| 246 | public: |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 247 | void registerTypeInfo(Fortran::lower::AbstractConverter &converter, |
| 248 | mlir::Location loc, |
| 249 | Fortran::semantics::SymbolRef typeInfoSym, |
| 250 | const Fortran::semantics::DerivedTypeSpec &typeSpec, |
| 251 | fir::RecordType type) { |
Valentin Clement | 9aeb7f0 | 2022-03-16 17:10:31 +0100 | [diff] [blame] | 252 | if (seen.contains(typeInfoSym)) |
| 253 | return; |
| 254 | seen.insert(typeInfoSym); |
jeanPerier | c373f58 | 2023-12-19 17:17:09 +0100 | [diff] [blame] | 255 | currentTypeInfoStack->emplace_back( |
| 256 | TypeInfo{typeInfoSym, typeSpec, type, loc}); |
| 257 | return; |
Valentin Clement | 9aeb7f0 | 2022-03-16 17:10:31 +0100 | [diff] [blame] | 258 | } |
| 259 | |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 260 | void createTypeInfo(Fortran::lower::AbstractConverter &converter) { |
jeanPerier | c373f58 | 2023-12-19 17:17:09 +0100 | [diff] [blame] | 261 | while (!registeredTypeInfoA.empty()) { |
| 262 | currentTypeInfoStack = ®isteredTypeInfoB; |
| 263 | for (const TypeInfo &info : registeredTypeInfoA) |
| 264 | createTypeInfoOpAndGlobal(converter, info); |
| 265 | registeredTypeInfoA.clear(); |
| 266 | currentTypeInfoStack = ®isteredTypeInfoA; |
| 267 | for (const TypeInfo &info : registeredTypeInfoB) |
| 268 | createTypeInfoOpAndGlobal(converter, info); |
| 269 | registeredTypeInfoB.clear(); |
| 270 | } |
Valentin Clement | 9aeb7f0 | 2022-03-16 17:10:31 +0100 | [diff] [blame] | 271 | } |
| 272 | |
| 273 | private: |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 274 | void createTypeInfoOpAndGlobal(Fortran::lower::AbstractConverter &converter, |
| 275 | const TypeInfo &info) { |
vdonaldson | 3aba926 | 2023-12-04 09:55:54 -0800 | [diff] [blame] | 276 | Fortran::lower::createRuntimeTypeInfoGlobal(converter, info.symbol.get()); |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 277 | createTypeInfoOp(converter, info); |
Valentin Clement | 6393d2e | 2022-11-17 10:53:13 +0100 | [diff] [blame] | 278 | } |
| 279 | |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 280 | void createTypeInfoOp(Fortran::lower::AbstractConverter &converter, |
| 281 | const TypeInfo &info) { |
| 282 | fir::RecordType parentType{}; |
| 283 | if (const Fortran::semantics::DerivedTypeSpec *parent = |
| 284 | Fortran::evaluate::GetParentTypeSpec(info.typeSpec)) |
| 285 | parentType = mlir::cast<fir::RecordType>(converter.genType(*parent)); |
Valentin Clement | 6393d2e | 2022-11-17 10:53:13 +0100 | [diff] [blame] | 286 | |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 287 | fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
jeanPerier | 66d5ca2 | 2024-07-02 15:19:49 +0200 | [diff] [blame] | 288 | fir::TypeInfoOp dt; |
| 289 | mlir::OpBuilder::InsertPoint insertPointIfCreated; |
| 290 | std::tie(dt, insertPointIfCreated) = |
| 291 | builder.createTypeInfoOp(info.loc, info.type, parentType); |
| 292 | if (!insertPointIfCreated.isSet()) |
| 293 | return; // fir.type_info was already built in a previous call. |
Valentin Clement | 6393d2e | 2022-11-17 10:53:13 +0100 | [diff] [blame] | 294 | |
jeanPerier | 66d5ca2 | 2024-07-02 15:19:49 +0200 | [diff] [blame] | 295 | // Set init, destroy, and nofinal attributes. |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 296 | if (!info.typeSpec.HasDefaultInitialization(/*ignoreAllocatable=*/false, |
| 297 | /*ignorePointer=*/false)) |
| 298 | dt->setAttr(dt.getNoInitAttrName(), builder.getUnitAttr()); |
| 299 | if (!info.typeSpec.HasDestruction()) |
| 300 | dt->setAttr(dt.getNoDestroyAttrName(), builder.getUnitAttr()); |
| 301 | if (!Fortran::semantics::MayRequireFinalization(info.typeSpec)) |
| 302 | dt->setAttr(dt.getNoFinalAttrName(), builder.getUnitAttr()); |
| 303 | |
jeanPerier | 66d5ca2 | 2024-07-02 15:19:49 +0200 | [diff] [blame] | 304 | const Fortran::semantics::Scope &derivedScope = |
| 305 | DEREF(info.typeSpec.GetScope()); |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 306 | |
jeanPerier | 66d5ca2 | 2024-07-02 15:19:49 +0200 | [diff] [blame] | 307 | // Fill binding table region if the derived type has bindings. |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 308 | Fortran::semantics::SymbolVector bindings = |
jeanPerier | 66d5ca2 | 2024-07-02 15:19:49 +0200 | [diff] [blame] | 309 | Fortran::semantics::CollectBindings(derivedScope); |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 310 | if (!bindings.empty()) { |
| 311 | builder.createBlock(&dt.getDispatchTable()); |
Valentin Clement | d38735e | 2022-11-22 15:13:18 +0100 | [diff] [blame] | 312 | for (const Fortran::semantics::SymbolRef &binding : bindings) { |
Peter Klausler | 7f7bbc7 | 2023-05-16 12:33:29 -0700 | [diff] [blame] | 313 | const auto &details = |
| 314 | binding.get().get<Fortran::semantics::ProcBindingDetails>(); |
| 315 | std::string tbpName = binding.get().name().ToString(); |
| 316 | if (details.numPrivatesNotOverridden() > 0) |
| 317 | tbpName += "."s + std::to_string(details.numPrivatesNotOverridden()); |
| 318 | std::string bindingName = converter.mangleName(details.symbol()); |
Valentin Clement | 6393d2e | 2022-11-17 10:53:13 +0100 | [diff] [blame] | 319 | builder.create<fir::DTEntryOp>( |
Peter Klausler | 7f7bbc7 | 2023-05-16 12:33:29 -0700 | [diff] [blame] | 320 | info.loc, mlir::StringAttr::get(builder.getContext(), tbpName), |
Valentin Clement | 6393d2e | 2022-11-17 10:53:13 +0100 | [diff] [blame] | 321 | mlir::SymbolRefAttr::get(builder.getContext(), bindingName)); |
| 322 | } |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 323 | builder.create<fir::FirEndOp>(info.loc); |
Valentin Clement | 6393d2e | 2022-11-17 10:53:13 +0100 | [diff] [blame] | 324 | } |
jeanPerier | 66d5ca2 | 2024-07-02 15:19:49 +0200 | [diff] [blame] | 325 | // Gather info about components that is not reflected in fir.type and may be |
| 326 | // needed later: component initial values and array component non default |
| 327 | // lower bounds. |
| 328 | mlir::Block *componentInfo = nullptr; |
| 329 | for (const auto &componentName : |
| 330 | info.typeSpec.typeSymbol() |
| 331 | .get<Fortran::semantics::DerivedTypeDetails>() |
| 332 | .componentNames()) { |
| 333 | auto scopeIter = derivedScope.find(componentName); |
| 334 | assert(scopeIter != derivedScope.cend() && |
| 335 | "failed to find derived type component symbol"); |
| 336 | const Fortran::semantics::Symbol &component = scopeIter->second.get(); |
| 337 | mlir::FlatSymbolRefAttr init_val = |
| 338 | gatherComponentInit(info.loc, converter, component, info.type); |
| 339 | mlir::DenseI64ArrayAttr lbs = gatherComponentNonDefaultLowerBounds( |
| 340 | info.loc, builder.getContext(), component); |
| 341 | if (init_val || lbs) { |
| 342 | if (!componentInfo) |
| 343 | componentInfo = builder.createBlock(&dt.getComponentInfo()); |
| 344 | auto compName = mlir::StringAttr::get(builder.getContext(), |
| 345 | toStringRef(component.name())); |
| 346 | builder.create<fir::DTComponentOp>(info.loc, compName, lbs, init_val); |
| 347 | } |
| 348 | } |
| 349 | if (componentInfo) |
| 350 | builder.create<fir::FirEndOp>(info.loc); |
| 351 | builder.restoreInsertionPoint(insertPointIfCreated); |
Valentin Clement | 6393d2e | 2022-11-17 10:53:13 +0100 | [diff] [blame] | 352 | } |
| 353 | |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 354 | /// Store the front-end data that will be required to generate the type info |
jeanPerier | c373f58 | 2023-12-19 17:17:09 +0100 | [diff] [blame] | 355 | /// for the derived types that have been converted to fir.type<>. There are |
| 356 | /// two stacks since the type info may visit new types, so the new types must |
| 357 | /// be added to a new stack. |
| 358 | llvm::SmallVector<TypeInfo> registeredTypeInfoA; |
| 359 | llvm::SmallVector<TypeInfo> registeredTypeInfoB; |
| 360 | llvm::SmallVector<TypeInfo> *currentTypeInfoStack = ®isteredTypeInfoA; |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 361 | /// Track symbols symbols processed during and after the registration |
| 362 | /// to avoid infinite loops between type conversions and global variable |
| 363 | /// creation. |
| 364 | llvm::SmallSetVector<Fortran::semantics::SymbolRef, 32> seen; |
Valentin Clement | 6393d2e | 2022-11-17 10:53:13 +0100 | [diff] [blame] | 365 | }; |
| 366 | |
Slava Zakharin | af7edf1 | 2022-08-18 14:06:19 -0700 | [diff] [blame] | 367 | using IncrementLoopNestInfo = llvm::SmallVector<IncrementLoopInfo, 8>; |
Valentin Clement | 9aeb7f0 | 2022-03-16 17:10:31 +0100 | [diff] [blame] | 368 | } // namespace |
| 369 | |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 370 | //===----------------------------------------------------------------------===// |
| 371 | // FirConverter |
| 372 | //===----------------------------------------------------------------------===// |
| 373 | |
| 374 | namespace { |
| 375 | |
| 376 | /// Traverse the pre-FIR tree (PFT) to generate the FIR dialect of MLIR. |
| 377 | class FirConverter : public Fortran::lower::AbstractConverter { |
| 378 | public: |
| 379 | explicit FirConverter(Fortran::lower::LoweringBridge &bridge) |
Slava Zakharin | f1eb945 | 2022-07-19 20:39:58 -0700 | [diff] [blame] | 380 | : Fortran::lower::AbstractConverter(bridge.getLoweringOptions()), |
jeanPerier | a4798bb | 2024-04-02 14:29:29 +0200 | [diff] [blame] | 381 | bridge{bridge}, foldingContext{bridge.createFoldingContext()}, |
| 382 | mlirSymbolTable{bridge.getModule()} {} |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 383 | virtual ~FirConverter() = default; |
| 384 | |
| 385 | /// Convert the PFT to FIR. |
| 386 | void run(Fortran::lower::pft::Program &pft) { |
Valentin Clement | a142501 | 2022-03-15 21:57:30 +0100 | [diff] [blame] | 387 | // Preliminary translation pass. |
Jean Perier | 2c8cb9a | 2022-04-29 14:52:27 +0200 | [diff] [blame] | 388 | |
vdonaldson | 3aba926 | 2023-12-04 09:55:54 -0800 | [diff] [blame] | 389 | // Lower common blocks, taking into account initialization and the largest |
| 390 | // size of all instances of each common block. This is done before lowering |
| 391 | // since the global definition may differ from any one local definition. |
Jean Perier | 2c8cb9a | 2022-04-29 14:52:27 +0200 | [diff] [blame] | 392 | lowerCommonBlocks(pft.getCommonBlocks()); |
| 393 | |
vdonaldson | 3aba926 | 2023-12-04 09:55:54 -0800 | [diff] [blame] | 394 | // - Declare all functions that have definitions so that definition |
| 395 | // signatures prevail over call site signatures. |
| 396 | // - Define module variables and OpenMP/OpenACC declarative constructs so |
| 397 | // they are available before lowering any function that may use them. |
Jonathon Penix | 0ec3ac9 | 2022-07-19 11:47:25 -0700 | [diff] [blame] | 398 | bool hasMainProgram = false; |
Sergio Afonso | 29aa749 | 2023-03-29 18:13:48 +0100 | [diff] [blame] | 399 | const Fortran::semantics::Symbol *globalOmpRequiresSymbol = nullptr; |
Valentin Clement | 17d7134 | 2022-03-02 18:26:13 +0100 | [diff] [blame] | 400 | for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) { |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 401 | Fortran::common::visit( |
vdonaldson | 87374a8 | 2024-06-12 09:35:14 -0400 | [diff] [blame] | 402 | Fortran::common::visitors{ |
| 403 | [&](Fortran::lower::pft::FunctionLikeUnit &f) { |
| 404 | if (f.isMainProgram()) |
| 405 | hasMainProgram = true; |
| 406 | declareFunction(f); |
| 407 | if (!globalOmpRequiresSymbol) |
| 408 | globalOmpRequiresSymbol = f.getScope().symbol(); |
| 409 | }, |
| 410 | [&](Fortran::lower::pft::ModuleLikeUnit &m) { |
| 411 | lowerModuleDeclScope(m); |
| 412 | for (Fortran::lower::pft::ContainedUnit &unit : |
| 413 | m.containedUnitList) |
| 414 | if (auto *f = |
| 415 | std::get_if<Fortran::lower::pft::FunctionLikeUnit>( |
| 416 | &unit)) |
| 417 | declareFunction(*f); |
| 418 | }, |
| 419 | [&](Fortran::lower::pft::BlockDataUnit &b) { |
| 420 | if (!globalOmpRequiresSymbol) |
| 421 | globalOmpRequiresSymbol = b.symTab.symbol(); |
| 422 | }, |
| 423 | [&](Fortran::lower::pft::CompilerDirectiveUnit &d) {}, |
| 424 | [&](Fortran::lower::pft::OpenACCDirectiveUnit &d) {}, |
| 425 | }, |
| 426 | u); |
Valentin Clement | 17d7134 | 2022-03-02 18:26:13 +0100 | [diff] [blame] | 427 | } |
| 428 | |
vdonaldson | 3aba926 | 2023-12-04 09:55:54 -0800 | [diff] [blame] | 429 | // Create definitions of intrinsic module constants. |
| 430 | createGlobalOutsideOfFunctionLowering( |
| 431 | [&]() { createIntrinsicModuleDefinitions(pft); }); |
| 432 | |
Valentin Clement | 17d7134 | 2022-03-02 18:26:13 +0100 | [diff] [blame] | 433 | // Primary translation pass. |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 434 | for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) { |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 435 | Fortran::common::visit( |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 436 | Fortran::common::visitors{ |
| 437 | [&](Fortran::lower::pft::FunctionLikeUnit &f) { lowerFunc(f); }, |
Valentin Clement | 17d7134 | 2022-03-02 18:26:13 +0100 | [diff] [blame] | 438 | [&](Fortran::lower::pft::ModuleLikeUnit &m) { lowerMod(m); }, |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 439 | [&](Fortran::lower::pft::BlockDataUnit &b) {}, |
V Donaldson | af78197 | 2023-04-12 15:37:19 -0700 | [diff] [blame] | 440 | [&](Fortran::lower::pft::CompilerDirectiveUnit &d) {}, |
Valentin Clement (バレンタイン クレメン) | 8286743 | 2023-10-24 09:17:48 -0700 | [diff] [blame] | 441 | [&](Fortran::lower::pft::OpenACCDirectiveUnit &d) { |
jeanPerier | a4798bb | 2024-04-02 14:29:29 +0200 | [diff] [blame] | 442 | builder = new fir::FirOpBuilder( |
| 443 | bridge.getModule(), bridge.getKindMap(), &mlirSymbolTable); |
Valentin Clement (バレンタイン クレメン) | 8286743 | 2023-10-24 09:17:48 -0700 | [diff] [blame] | 444 | Fortran::lower::genOpenACCRoutineConstruct( |
| 445 | *this, bridge.getSemanticsContext(), bridge.getModule(), |
| 446 | d.routine, accRoutineInfos); |
| 447 | builder = nullptr; |
| 448 | }, |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 449 | }, |
| 450 | u); |
| 451 | } |
Valentin Clement | 9aeb7f0 | 2022-03-16 17:10:31 +0100 | [diff] [blame] | 452 | |
vdonaldson | 3aba926 | 2023-12-04 09:55:54 -0800 | [diff] [blame] | 453 | // Once all the code has been translated, create global runtime type info |
| 454 | // data structures for the derived types that have been processed, as well |
| 455 | // as fir.type_info operations for the dispatch tables. |
Valentin Clement | 9aeb7f0 | 2022-03-16 17:10:31 +0100 | [diff] [blame] | 456 | createGlobalOutsideOfFunctionLowering( |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 457 | [&]() { typeInfoConverter.createTypeInfo(*this); }); |
Valentin Clement | 6393d2e | 2022-11-17 10:53:13 +0100 | [diff] [blame] | 458 | |
David Truby | ecec131 | 2024-04-30 22:38:36 +0100 | [diff] [blame] | 459 | // Generate the `main` entry point if necessary |
Jonathon Penix | 0ec3ac9 | 2022-07-19 11:47:25 -0700 | [diff] [blame] | 460 | if (hasMainProgram) |
| 461 | createGlobalOutsideOfFunctionLowering([&]() { |
David Truby | ecec131 | 2024-04-30 22:38:36 +0100 | [diff] [blame] | 462 | fir::runtime::genMain(*builder, toLocation(), |
Valentin Clement (バレンタイン クレメン) | 654b763 | 2025-01-28 20:57:33 -0800 | [diff] [blame] | 463 | bridge.getEnvironmentDefaults(), |
| 464 | getFoldingContext().languageFeatures().IsEnabled( |
| 465 | Fortran::common::LanguageFeature::CUDA)); |
Jonathon Penix | 0ec3ac9 | 2022-07-19 11:47:25 -0700 | [diff] [blame] | 466 | }); |
Valentin Clement | 69a6bd5 | 2023-08-17 14:25:05 -0700 | [diff] [blame] | 467 | |
| 468 | finalizeOpenACCLowering(); |
Sergio Afonso | 29aa749 | 2023-03-29 18:13:48 +0100 | [diff] [blame] | 469 | finalizeOpenMPLowering(globalOmpRequiresSymbol); |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 470 | } |
| 471 | |
Valentin Clement | 17d7134 | 2022-03-02 18:26:13 +0100 | [diff] [blame] | 472 | /// Declare a function. |
| 473 | void declareFunction(Fortran::lower::pft::FunctionLikeUnit &funit) { |
| 474 | setCurrentPosition(funit.getStartingSourceLoc()); |
| 475 | for (int entryIndex = 0, last = funit.entryPointList.size(); |
| 476 | entryIndex < last; ++entryIndex) { |
| 477 | funit.setActiveEntry(entryIndex); |
River Riddle | 58ceae9 | 2022-04-18 11:53:47 -0700 | [diff] [blame] | 478 | // Calling CalleeInterface ctor will build a declaration |
| 479 | // mlir::func::FuncOp with no other side effects. |
Valentin Clement | 17d7134 | 2022-03-02 18:26:13 +0100 | [diff] [blame] | 480 | // TODO: when doing some compiler profiling on real apps, it may be worth |
| 481 | // to check it's better to save the CalleeInterface instead of recomputing |
| 482 | // it later when lowering the body. CalleeInterface ctor should be linear |
| 483 | // with the number of arguments, so it is not awful to do it that way for |
| 484 | // now, but the linear coefficient might be non negligible. Until |
| 485 | // measured, stick to the solution that impacts the code less. |
| 486 | Fortran::lower::CalleeInterface{funit, *this}; |
| 487 | } |
| 488 | funit.setActiveEntry(0); |
| 489 | |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 490 | // Compute the set of host associated entities from the nested functions. |
| 491 | llvm::SetVector<const Fortran::semantics::Symbol *> escapeHost; |
vdonaldson | 87374a8 | 2024-06-12 09:35:14 -0400 | [diff] [blame] | 492 | for (Fortran::lower::pft::ContainedUnit &unit : funit.containedUnitList) |
| 493 | if (auto *f = std::get_if<Fortran::lower::pft::FunctionLikeUnit>(&unit)) |
| 494 | collectHostAssociatedVariables(*f, escapeHost); |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 495 | funit.setHostAssociatedSymbols(escapeHost); |
| 496 | |
Valentin Clement | 17d7134 | 2022-03-02 18:26:13 +0100 | [diff] [blame] | 497 | // Declare internal procedures |
vdonaldson | 87374a8 | 2024-06-12 09:35:14 -0400 | [diff] [blame] | 498 | for (Fortran::lower::pft::ContainedUnit &unit : funit.containedUnitList) |
| 499 | if (auto *f = std::get_if<Fortran::lower::pft::FunctionLikeUnit>(&unit)) |
| 500 | declareFunction(*f); |
Valentin Clement | 17d7134 | 2022-03-02 18:26:13 +0100 | [diff] [blame] | 501 | } |
| 502 | |
jeanPerier | d26c78b | 2023-09-06 09:07:45 +0200 | [diff] [blame] | 503 | /// Get the scope that is defining or using \p sym. The returned scope is not |
| 504 | /// the ultimate scope, since this helper does not traverse use association. |
| 505 | /// This allows capturing module variables that are referenced in an internal |
| 506 | /// procedure but whose use statement is inside the host program. |
| 507 | const Fortran::semantics::Scope & |
| 508 | getSymbolHostScope(const Fortran::semantics::Symbol &sym) { |
| 509 | const Fortran::semantics::Symbol *hostSymbol = &sym; |
| 510 | while (const auto *details = |
| 511 | hostSymbol->detailsIf<Fortran::semantics::HostAssocDetails>()) |
| 512 | hostSymbol = &details->symbol(); |
| 513 | return hostSymbol->owner(); |
| 514 | } |
| 515 | |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 516 | /// Collects the canonical list of all host associated symbols. These bindings |
| 517 | /// must be aggregated into a tuple which can then be added to each of the |
| 518 | /// internal procedure declarations and passed at each call site. |
| 519 | void collectHostAssociatedVariables( |
| 520 | Fortran::lower::pft::FunctionLikeUnit &funit, |
| 521 | llvm::SetVector<const Fortran::semantics::Symbol *> &escapees) { |
| 522 | const Fortran::semantics::Scope *internalScope = |
| 523 | funit.getSubprogramSymbol().scope(); |
| 524 | assert(internalScope && "internal procedures symbol must create a scope"); |
| 525 | auto addToListIfEscapee = [&](const Fortran::semantics::Symbol &sym) { |
| 526 | const Fortran::semantics::Symbol &ultimate = sym.GetUltimate(); |
| 527 | const auto *namelistDetails = |
| 528 | ultimate.detailsIf<Fortran::semantics::NamelistDetails>(); |
| 529 | if (ultimate.has<Fortran::semantics::ObjectEntityDetails>() || |
| 530 | Fortran::semantics::IsProcedurePointer(ultimate) || |
| 531 | Fortran::semantics::IsDummy(sym) || namelistDetails) { |
jeanPerier | d26c78b | 2023-09-06 09:07:45 +0200 | [diff] [blame] | 532 | const Fortran::semantics::Scope &symbolScope = getSymbolHostScope(sym); |
| 533 | if (symbolScope.kind() == |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 534 | Fortran::semantics::Scope::Kind::MainProgram || |
jeanPerier | d26c78b | 2023-09-06 09:07:45 +0200 | [diff] [blame] | 535 | symbolScope.kind() == Fortran::semantics::Scope::Kind::Subprogram) |
| 536 | if (symbolScope != *internalScope && |
| 537 | symbolScope.Contains(*internalScope)) { |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 538 | if (namelistDetails) { |
| 539 | // So far, namelist symbols are processed on the fly in IO and |
| 540 | // the related namelist data structure is not added to the symbol |
| 541 | // map, so it cannot be passed to the internal procedures. |
| 542 | // Instead, all the symbols of the host namelist used in the |
| 543 | // internal procedure must be considered as host associated so |
| 544 | // that IO lowering can find them when needed. |
| 545 | for (const auto &namelistObject : namelistDetails->objects()) |
| 546 | escapees.insert(&*namelistObject); |
| 547 | } else { |
| 548 | escapees.insert(&ultimate); |
| 549 | } |
| 550 | } |
| 551 | } |
| 552 | }; |
| 553 | Fortran::lower::pft::visitAllSymbols(funit, addToListIfEscapee); |
| 554 | } |
| 555 | |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 556 | //===--------------------------------------------------------------------===// |
| 557 | // AbstractConverter overrides |
| 558 | //===--------------------------------------------------------------------===// |
| 559 | |
| 560 | mlir::Value getSymbolAddress(Fortran::lower::SymbolRef sym) override final { |
| 561 | return lookupSymbol(sym).getAddr(); |
| 562 | } |
| 563 | |
Leandro Lupori | 1fcb6a9 | 2024-12-19 17:26:50 -0300 | [diff] [blame] | 564 | fir::ExtendedValue symBoxToExtendedValue( |
| 565 | const Fortran::lower::SymbolBox &symBox) override final { |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 566 | return symBox.match( |
| 567 | [](const Fortran::lower::SymbolBox::Intrinsic &box) |
| 568 | -> fir::ExtendedValue { return box.getAddr(); }, |
| 569 | [](const Fortran::lower::SymbolBox::None &) -> fir::ExtendedValue { |
| 570 | llvm::report_fatal_error("symbol not mapped"); |
| 571 | }, |
| 572 | [&](const fir::FortranVariableOpInterface &x) -> fir::ExtendedValue { |
| 573 | return hlfir::translateToExtendedValue(getCurrentLocation(), |
| 574 | getFirOpBuilder(), x); |
| 575 | }, |
| 576 | [](const auto &box) -> fir::ExtendedValue { return box; }); |
| 577 | } |
| 578 | |
| 579 | fir::ExtendedValue |
| 580 | getSymbolExtendedValue(const Fortran::semantics::Symbol &sym, |
| 581 | Fortran::lower::SymMap *symMap) override final { |
| 582 | Fortran::lower::SymbolBox sb = lookupSymbol(sym, symMap); |
| 583 | if (!sb) { |
| 584 | LLVM_DEBUG(llvm::dbgs() << "unknown symbol: " << sym << "\nmap: " |
| 585 | << (symMap ? *symMap : localSymbols) << '\n'); |
| 586 | fir::emitFatalError(getCurrentLocation(), |
| 587 | "symbol is not mapped to any IR value"); |
| 588 | } |
| 589 | return symBoxToExtendedValue(sb); |
Peixin-Qiao | 411bd2d | 2022-06-07 15:08:17 +0800 | [diff] [blame] | 590 | } |
| 591 | |
Valentin Clement | b3eb0e1 | 2022-03-08 18:47:28 +0100 | [diff] [blame] | 592 | mlir::Value impliedDoBinding(llvm::StringRef name) override final { |
| 593 | mlir::Value val = localSymbols.lookupImpliedDo(name); |
| 594 | if (!val) |
| 595 | fir::emitFatalError(toLocation(), "ac-do-variable has no binding"); |
| 596 | return val; |
| 597 | } |
| 598 | |
Valentin Clement | a142501 | 2022-03-15 21:57:30 +0100 | [diff] [blame] | 599 | void copySymbolBinding(Fortran::lower::SymbolRef src, |
| 600 | Fortran::lower::SymbolRef target) override final { |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 601 | localSymbols.copySymbolBinding(src, target); |
Valentin Clement | a142501 | 2022-03-15 21:57:30 +0100 | [diff] [blame] | 602 | } |
| 603 | |
| 604 | /// Add the symbol binding to the inner-most level of the symbol map and |
| 605 | /// return true if it is not already present. Otherwise, return false. |
| 606 | bool bindIfNewSymbol(Fortran::lower::SymbolRef sym, |
| 607 | const fir::ExtendedValue &exval) { |
| 608 | if (shallowLookupSymbol(sym)) |
| 609 | return false; |
| 610 | bindSymbol(sym, exval); |
| 611 | return true; |
| 612 | } |
| 613 | |
| 614 | void bindSymbol(Fortran::lower::SymbolRef sym, |
| 615 | const fir::ExtendedValue &exval) override final { |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 616 | addSymbol(sym, exval, /*forced=*/true); |
Valentin Clement | a142501 | 2022-03-15 21:57:30 +0100 | [diff] [blame] | 617 | } |
| 618 | |
jeanPerier | b6b0756 | 2023-10-25 09:22:23 +0200 | [diff] [blame] | 619 | void |
| 620 | overrideExprValues(const Fortran::lower::ExprToValueMap *map) override final { |
| 621 | exprValueOverrides = map; |
| 622 | } |
| 623 | |
| 624 | const Fortran::lower::ExprToValueMap *getExprOverrides() override final { |
| 625 | return exprValueOverrides; |
| 626 | } |
| 627 | |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 628 | bool lookupLabelSet(Fortran::lower::SymbolRef sym, |
| 629 | Fortran::lower::pft::LabelSet &labelSet) override final { |
| 630 | Fortran::lower::pft::FunctionLikeUnit &owningProc = |
| 631 | *getEval().getOwningProcedure(); |
| 632 | auto iter = owningProc.assignSymbolLabelMap.find(sym); |
| 633 | if (iter == owningProc.assignSymbolLabelMap.end()) |
| 634 | return false; |
| 635 | labelSet = iter->second; |
| 636 | return true; |
| 637 | } |
| 638 | |
| 639 | Fortran::lower::pft::Evaluation * |
| 640 | lookupLabel(Fortran::lower::pft::Label label) override final { |
| 641 | Fortran::lower::pft::FunctionLikeUnit &owningProc = |
| 642 | *getEval().getOwningProcedure(); |
Kazu Hirata | a678ed4 | 2023-08-27 08:26:48 -0700 | [diff] [blame] | 643 | return owningProc.labelEvaluationMap.lookup(label); |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 644 | } |
| 645 | |
Jean Perier | 4546397 | 2022-10-17 09:57:16 +0200 | [diff] [blame] | 646 | fir::ExtendedValue |
| 647 | genExprAddr(const Fortran::lower::SomeExpr &expr, |
| 648 | Fortran::lower::StatementContext &context, |
| 649 | mlir::Location *locPtr = nullptr) override final { |
| 650 | mlir::Location loc = locPtr ? *locPtr : toLocation(); |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 651 | if (lowerToHighLevelFIR()) |
Jean Perier | 4e78f88 | 2023-01-10 09:28:08 +0100 | [diff] [blame] | 652 | return Fortran::lower::convertExprToAddress(loc, *this, expr, |
| 653 | localSymbols, context); |
Jean Perier | 4546397 | 2022-10-17 09:57:16 +0200 | [diff] [blame] | 654 | return Fortran::lower::createSomeExtendedAddress(loc, *this, expr, |
| 655 | localSymbols, context); |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 656 | } |
Jean Perier | c14ef2d | 2022-10-24 15:35:19 +0200 | [diff] [blame] | 657 | |
Valentin Clement | 4152674 | 2022-02-02 18:44:09 +0100 | [diff] [blame] | 658 | fir::ExtendedValue |
| 659 | genExprValue(const Fortran::lower::SomeExpr &expr, |
Valentin Clement | d0b70a0 | 2022-02-23 19:48:07 +0100 | [diff] [blame] | 660 | Fortran::lower::StatementContext &context, |
Jean Perier | 4546397 | 2022-10-17 09:57:16 +0200 | [diff] [blame] | 661 | mlir::Location *locPtr = nullptr) override final { |
| 662 | mlir::Location loc = locPtr ? *locPtr : toLocation(); |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 663 | if (lowerToHighLevelFIR()) |
Jean Perier | 199e497 | 2023-01-13 09:15:52 +0100 | [diff] [blame] | 664 | return Fortran::lower::convertExprToValue(loc, *this, expr, localSymbols, |
| 665 | context); |
Jean Perier | 4546397 | 2022-10-17 09:57:16 +0200 | [diff] [blame] | 666 | return Fortran::lower::createSomeExtendedExpression(loc, *this, expr, |
| 667 | localSymbols, context); |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 668 | } |
Eric Schweitz | 1bffc75 | 2022-04-22 13:59:17 -0700 | [diff] [blame] | 669 | |
| 670 | fir::ExtendedValue |
| 671 | genExprBox(mlir::Location loc, const Fortran::lower::SomeExpr &expr, |
| 672 | Fortran::lower::StatementContext &stmtCtx) override final { |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 673 | if (lowerToHighLevelFIR()) |
Jean Perier | 4e78f88 | 2023-01-10 09:28:08 +0100 | [diff] [blame] | 674 | return Fortran::lower::convertExprToBox(loc, *this, expr, localSymbols, |
| 675 | stmtCtx); |
Valentin Clement | 94a1106 | 2022-03-15 22:18:45 +0100 | [diff] [blame] | 676 | return Fortran::lower::createBoxValue(loc, *this, expr, localSymbols, |
Eric Schweitz | 1bffc75 | 2022-04-22 13:59:17 -0700 | [diff] [blame] | 677 | stmtCtx); |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 678 | } |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 679 | |
| 680 | Fortran::evaluate::FoldingContext &getFoldingContext() override final { |
| 681 | return foldingContext; |
| 682 | } |
| 683 | |
Valentin Clement | e641c29 | 2022-02-17 18:23:22 +0100 | [diff] [blame] | 684 | mlir::Type genType(const Fortran::lower::SomeExpr &expr) override final { |
| 685 | return Fortran::lower::translateSomeExprToFIRType(*this, expr); |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 686 | } |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 687 | mlir::Type genType(const Fortran::lower::pft::Variable &var) override final { |
| 688 | return Fortran::lower::translateVariableToFIRType(*this, var); |
| 689 | } |
Valentin Clement | ad40cc1 | 2022-02-14 21:31:46 +0100 | [diff] [blame] | 690 | mlir::Type genType(Fortran::lower::SymbolRef sym) override final { |
| 691 | return Fortran::lower::translateSymbolToFIRType(*this, sym); |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 692 | } |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 693 | mlir::Type |
| 694 | genType(Fortran::common::TypeCategory tc, int kind, |
| 695 | llvm::ArrayRef<std::int64_t> lenParameters) override final { |
| 696 | return Fortran::lower::getFIRType(&getMLIRContext(), tc, kind, |
| 697 | lenParameters); |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 698 | } |
Valentin Clement | 589d51e | 2022-03-10 18:06:20 +0100 | [diff] [blame] | 699 | mlir::Type |
| 700 | genType(const Fortran::semantics::DerivedTypeSpec &tySpec) override final { |
| 701 | return Fortran::lower::translateDerivedTypeToFIRType(*this, tySpec); |
| 702 | } |
| 703 | mlir::Type genType(Fortran::common::TypeCategory tc) override final { |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 704 | return Fortran::lower::getFIRType( |
| 705 | &getMLIRContext(), tc, bridge.getDefaultKinds().GetDefaultKind(tc), |
Kazu Hirata | 9a41739 | 2022-12-03 12:14:21 -0800 | [diff] [blame] | 706 | std::nullopt); |
Kiran Chandramohan | ae37bb9 | 2022-02-08 23:01:39 +0000 | [diff] [blame] | 707 | } |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 708 | |
jeanPerier | c373f58 | 2023-12-19 17:17:09 +0100 | [diff] [blame] | 709 | Fortran::lower::TypeConstructionStack & |
| 710 | getTypeConstructionStack() override final { |
| 711 | return typeConstructionStack; |
| 712 | } |
| 713 | |
Kareem Ergawy | 6af4118 | 2024-05-27 14:26:52 +0200 | [diff] [blame] | 714 | bool |
| 715 | isPresentShallowLookup(const Fortran::semantics::Symbol &sym) override final { |
NimishMishra | 91f92e6 | 2023-11-10 00:17:47 -0800 | [diff] [blame] | 716 | return bool(shallowLookupSymbol(sym)); |
| 717 | } |
| 718 | |
jeanPerier | ff78cd5 | 2024-12-05 14:09:48 +0100 | [diff] [blame] | 719 | bool createHostAssociateVarClone(const Fortran::semantics::Symbol &sym, |
| 720 | bool skipDefaultInit) override final { |
Kiran Chandramohan | 07e16a2 | 2022-04-11 09:05:00 +0000 | [diff] [blame] | 721 | mlir::Location loc = genLocation(sym.name()); |
| 722 | mlir::Type symType = genType(sym); |
| 723 | const auto *details = sym.detailsIf<Fortran::semantics::HostAssocDetails>(); |
| 724 | assert(details && "No host-association found"); |
| 725 | const Fortran::semantics::Symbol &hsym = details->symbol(); |
Leandro Lupori | 29cdc8f | 2024-07-01 14:10:35 -0300 | [diff] [blame] | 726 | mlir::Type hSymType = genType(hsym.GetUltimate()); |
Kareem Ergawy | 3b30559 | 2024-03-11 10:38:28 +0100 | [diff] [blame] | 727 | Fortran::lower::SymbolBox hsb = |
| 728 | lookupSymbol(hsym, /*symMap=*/nullptr, /*forceHlfirBase=*/true); |
Kiran Chandramohan | 07e16a2 | 2022-04-11 09:05:00 +0000 | [diff] [blame] | 729 | |
| 730 | auto allocate = [&](llvm::ArrayRef<mlir::Value> shape, |
| 731 | llvm::ArrayRef<mlir::Value> typeParams) -> mlir::Value { |
| 732 | mlir::Value allocVal = builder->allocateLocal( |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 733 | loc, |
Peter Klausler | 031b4e5 | 2023-08-21 12:21:49 -0700 | [diff] [blame] | 734 | Fortran::semantics::IsAllocatableOrObjectPointer(&hsym.GetUltimate()) |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 735 | ? hSymType |
| 736 | : symType, |
| 737 | mangleName(sym), toStringRef(sym.GetUltimate().name()), |
Kiran Chandramohan | 07e16a2 | 2022-04-11 09:05:00 +0000 | [diff] [blame] | 738 | /*pinned=*/true, shape, typeParams, |
| 739 | sym.GetUltimate().attrs().test(Fortran::semantics::Attr::TARGET)); |
| 740 | return allocVal; |
| 741 | }; |
| 742 | |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 743 | fir::ExtendedValue hexv = symBoxToExtendedValue(hsb); |
Kiran Chandramohan | 07e16a2 | 2022-04-11 09:05:00 +0000 | [diff] [blame] | 744 | fir::ExtendedValue exv = hexv.match( |
| 745 | [&](const fir::BoxValue &box) -> fir::ExtendedValue { |
| 746 | const Fortran::semantics::DeclTypeSpec *type = sym.GetType(); |
| 747 | if (type && type->IsPolymorphic()) |
| 748 | TODO(loc, "create polymorphic host associated copy"); |
| 749 | // Create a contiguous temp with the same shape and length as |
| 750 | // the original variable described by a fir.box. |
| 751 | llvm::SmallVector<mlir::Value> extents = |
Eric Schweitz | 1bffc75 | 2022-04-22 13:59:17 -0700 | [diff] [blame] | 752 | fir::factory::getExtents(loc, *builder, hexv); |
| 753 | if (box.isDerivedWithLenParameters()) |
Kiran Chandramohan | 07e16a2 | 2022-04-11 09:05:00 +0000 | [diff] [blame] | 754 | TODO(loc, "get length parameters from derived type BoxValue"); |
| 755 | if (box.isCharacter()) { |
| 756 | mlir::Value len = fir::factory::readCharLen(*builder, loc, box); |
| 757 | mlir::Value temp = allocate(extents, {len}); |
| 758 | return fir::CharArrayBoxValue{temp, len, extents}; |
| 759 | } |
| 760 | return fir::ArrayBoxValue{allocate(extents, {}), extents}; |
| 761 | }, |
| 762 | [&](const fir::MutableBoxValue &box) -> fir::ExtendedValue { |
| 763 | // Allocate storage for a pointer/allocatble descriptor. |
| 764 | // No shape/lengths to be passed to the alloca. |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 765 | return fir::MutableBoxValue(allocate({}, {}), {}, {}); |
Kiran Chandramohan | 07e16a2 | 2022-04-11 09:05:00 +0000 | [diff] [blame] | 766 | }, |
| 767 | [&](const auto &) -> fir::ExtendedValue { |
| 768 | mlir::Value temp = |
Eric Schweitz | 1bffc75 | 2022-04-22 13:59:17 -0700 | [diff] [blame] | 769 | allocate(fir::factory::getExtents(loc, *builder, hexv), |
Valentin Clement | 53804e4 | 2022-07-07 09:37:12 +0200 | [diff] [blame] | 770 | fir::factory::getTypeParams(loc, *builder, hexv)); |
Kiran Chandramohan | 07e16a2 | 2022-04-11 09:05:00 +0000 | [diff] [blame] | 771 | return fir::substBase(hexv, temp); |
| 772 | }); |
| 773 | |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 774 | // Initialise cloned allocatable |
| 775 | hexv.match( |
| 776 | [&](const fir::MutableBoxValue &box) -> void { |
jeanPerier | ff78cd5 | 2024-12-05 14:09:48 +0100 | [diff] [blame] | 777 | const auto new_box = exv.getBoxOf<fir::MutableBoxValue>(); |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 778 | if (Fortran::semantics::IsPointer(sym.GetUltimate())) { |
jeanPerier | ff78cd5 | 2024-12-05 14:09:48 +0100 | [diff] [blame] | 779 | // Establish the pointer descriptors. The rank and type code/size |
| 780 | // at least must be set properly for later inquiry of the pointer |
| 781 | // to work, and new pointers are always given disassociated status |
| 782 | // by flang for safety, even if this is not required by the |
| 783 | // language. |
| 784 | auto empty = fir::factory::createUnallocatedBox( |
| 785 | *builder, loc, new_box->getBoxTy(), box.nonDeferredLenParams(), |
| 786 | {}); |
| 787 | builder->create<fir::StoreOp>(loc, empty, new_box->getAddr()); |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 788 | return; |
| 789 | } |
jeanPerier | ff78cd5 | 2024-12-05 14:09:48 +0100 | [diff] [blame] | 790 | // Copy allocation status of Allocatables, creating new storage if |
| 791 | // needed. |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 792 | |
| 793 | // allocate if allocated |
| 794 | mlir::Value isAllocated = |
| 795 | fir::factory::genIsAllocatedOrAssociatedTest(*builder, loc, box); |
| 796 | auto if_builder = builder->genIfThenElse(loc, isAllocated); |
| 797 | if_builder.genThen([&]() { |
| 798 | std::string name = mangleName(sym) + ".alloc"; |
Kiran Chandramohan | 57d0d3b | 2024-05-01 12:58:50 +0100 | [diff] [blame] | 799 | fir::ExtendedValue read = fir::factory::genMutableBoxRead( |
| 800 | *builder, loc, box, /*mayBePolymorphic=*/false); |
| 801 | if (auto read_arr_box = read.getBoxOf<fir::ArrayBoxValue>()) { |
| 802 | fir::factory::genInlinedAllocation( |
| 803 | *builder, loc, *new_box, read_arr_box->getLBounds(), |
| 804 | read_arr_box->getExtents(), |
| 805 | /*lenParams=*/std::nullopt, name, |
| 806 | /*mustBeHeap=*/true); |
| 807 | } else if (auto read_char_arr_box = |
| 808 | read.getBoxOf<fir::CharArrayBoxValue>()) { |
| 809 | fir::factory::genInlinedAllocation( |
| 810 | *builder, loc, *new_box, read_char_arr_box->getLBounds(), |
| 811 | read_char_arr_box->getExtents(), read_char_arr_box->getLen(), |
| 812 | name, |
| 813 | /*mustBeHeap=*/true); |
| 814 | } else if (auto read_char_box = |
| 815 | read.getBoxOf<fir::CharBoxValue>()) { |
| 816 | fir::factory::genInlinedAllocation(*builder, loc, *new_box, |
| 817 | /*lbounds=*/std::nullopt, |
| 818 | /*extents=*/std::nullopt, |
| 819 | read_char_box->getLen(), name, |
| 820 | /*mustBeHeap=*/true); |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 821 | } else { |
| 822 | fir::factory::genInlinedAllocation( |
Kiran Chandramohan | d0ef94b | 2023-11-07 11:53:30 +0000 | [diff] [blame] | 823 | *builder, loc, *new_box, box.getMutableProperties().lbounds, |
| 824 | box.getMutableProperties().extents, |
| 825 | box.nonDeferredLenParams(), name, |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 826 | /*mustBeHeap=*/true); |
| 827 | } |
| 828 | }); |
| 829 | if_builder.genElse([&]() { |
| 830 | // nullify box |
| 831 | auto empty = fir::factory::createUnallocatedBox( |
| 832 | *builder, loc, new_box->getBoxTy(), |
| 833 | new_box->nonDeferredLenParams(), {}); |
| 834 | builder->create<fir::StoreOp>(loc, empty, new_box->getAddr()); |
| 835 | }); |
| 836 | if_builder.end(); |
| 837 | }, |
| 838 | [&](const auto &) -> void { |
jeanPerier | d82d53b | 2025-01-07 10:04:27 +0100 | [diff] [blame] | 839 | // Always initialize allocatable component descriptor, even when the |
| 840 | // value is later copied from the host (e.g. firstprivate) because the |
| 841 | // assignment from the host to the copy will fail if the component |
| 842 | // descriptors are not initialized. |
| 843 | if (skipDefaultInit && !hlfir::mayHaveAllocatableComponent(hSymType)) |
jeanPerier | ff78cd5 | 2024-12-05 14:09:48 +0100 | [diff] [blame] | 844 | return; |
| 845 | // Initialize local/private derived types with default |
| 846 | // initialization (Fortran 2023 section 11.1.7.5 and OpenMP 5.2 |
| 847 | // section 5.3). Pointer and allocatable components, when allowed, |
| 848 | // also need to be established so that flang runtime can later work |
| 849 | // with them. |
| 850 | if (const Fortran::semantics::DeclTypeSpec *declTypeSpec = |
| 851 | sym.GetType()) |
| 852 | if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec = |
| 853 | declTypeSpec->AsDerived()) |
| 854 | if (derivedTypeSpec->HasDefaultInitialization( |
| 855 | /*ignoreAllocatable=*/false, /*ignorePointer=*/false)) { |
| 856 | mlir::Value box = builder->createBox(loc, exv); |
| 857 | fir::runtime::genDerivedTypeInitialize(*builder, loc, box); |
| 858 | } |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 859 | }); |
| 860 | |
Kiran Chandramohan | 07e16a2 | 2022-04-11 09:05:00 +0000 | [diff] [blame] | 861 | return bindIfNewSymbol(sym, exv); |
| 862 | } |
| 863 | |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 864 | void createHostAssociateVarCloneDealloc( |
| 865 | const Fortran::semantics::Symbol &sym) override final { |
| 866 | mlir::Location loc = genLocation(sym.name()); |
Kareem Ergawy | 3b30559 | 2024-03-11 10:38:28 +0100 | [diff] [blame] | 867 | Fortran::lower::SymbolBox hsb = |
| 868 | lookupSymbol(sym, /*symMap=*/nullptr, /*forceHlfirBase=*/true); |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 869 | |
| 870 | fir::ExtendedValue hexv = symBoxToExtendedValue(hsb); |
| 871 | hexv.match( |
| 872 | [&](const fir::MutableBoxValue &new_box) -> void { |
| 873 | // Do not process pointers |
| 874 | if (Fortran::semantics::IsPointer(sym.GetUltimate())) { |
| 875 | return; |
| 876 | } |
| 877 | // deallocate allocated in createHostAssociateVarClone value |
jeanPerier | 2cb31fe | 2023-09-21 18:38:23 +0200 | [diff] [blame] | 878 | Fortran::lower::genDeallocateIfAllocated(*this, new_box, loc); |
Dmitriy Smirnov | bc4586d | 2023-07-03 16:31:20 +0000 | [diff] [blame] | 879 | }, |
| 880 | [&](const auto &) -> void { |
| 881 | // Do nothing |
| 882 | }); |
| 883 | } |
| 884 | |
Leandro Lupori | 952bdaa | 2024-06-25 09:25:41 -0300 | [diff] [blame] | 885 | void copyVar(mlir::Location loc, mlir::Value dst, mlir::Value src, |
| 886 | fir::FortranVariableFlagsEnum attrs) override final { |
| 887 | bool isAllocatable = |
| 888 | bitEnumContainsAny(attrs, fir::FortranVariableFlagsEnum::allocatable); |
| 889 | bool isPointer = |
| 890 | bitEnumContainsAny(attrs, fir::FortranVariableFlagsEnum::pointer); |
| 891 | |
Kareem Ergawy | 87cee71 | 2024-03-18 10:44:44 +0100 | [diff] [blame] | 892 | copyVarHLFIR(loc, Fortran::lower::SymbolBox::Intrinsic{dst}, |
Leandro Lupori | 952bdaa | 2024-06-25 09:25:41 -0300 | [diff] [blame] | 893 | Fortran::lower::SymbolBox::Intrinsic{src}, isAllocatable, |
Leandro Lupori | 797f011 | 2024-09-05 14:55:01 -0300 | [diff] [blame] | 894 | isPointer, Fortran::semantics::Symbol::Flags()); |
Leandro Lupori | e50a231 | 2024-02-21 14:51:37 -0300 | [diff] [blame] | 895 | } |
| 896 | |
Kareem Ergawy | a0406ce | 2025-01-16 19:10:12 +0100 | [diff] [blame] | 897 | void |
| 898 | copyHostAssociateVar(const Fortran::semantics::Symbol &sym, |
| 899 | mlir::OpBuilder::InsertPoint *copyAssignIP = nullptr, |
| 900 | bool hostIsSource = true) override final { |
Kiran Chandramohan | 07e16a2 | 2022-04-11 09:05:00 +0000 | [diff] [blame] | 901 | // 1) Fetch the original copy of the variable. |
| 902 | assert(sym.has<Fortran::semantics::HostAssocDetails>() && |
| 903 | "No host-association found"); |
| 904 | const Fortran::semantics::Symbol &hsym = sym.GetUltimate(); |
Peixin-Qiao | 27afb36 | 2022-06-24 15:33:09 +0800 | [diff] [blame] | 905 | Fortran::lower::SymbolBox hsb = lookupOneLevelUpSymbol(hsym); |
| 906 | assert(hsb && "Host symbol box not found"); |
Kiran Chandramohan | 07e16a2 | 2022-04-11 09:05:00 +0000 | [diff] [blame] | 907 | |
Peixin-Qiao | 27afb36 | 2022-06-24 15:33:09 +0800 | [diff] [blame] | 908 | // 2) Fetch the copied one that will mask the original. |
| 909 | Fortran::lower::SymbolBox sb = shallowLookupSymbol(sym); |
| 910 | assert(sb && "Host-associated symbol box not found"); |
| 911 | assert(hsb.getAddr() != sb.getAddr() && |
| 912 | "Host and associated symbol boxes are the same"); |
Kiran Chandramohan | 07e16a2 | 2022-04-11 09:05:00 +0000 | [diff] [blame] | 913 | |
| 914 | // 3) Perform the assignment. |
Kareem Ergawy | a0406ce | 2025-01-16 19:10:12 +0100 | [diff] [blame] | 915 | mlir::OpBuilder::InsertionGuard guard(*builder); |
Peixin Qiao | f4accbf | 2022-10-05 20:22:33 +0800 | [diff] [blame] | 916 | if (copyAssignIP && copyAssignIP->isSet()) |
| 917 | builder->restoreInsertionPoint(*copyAssignIP); |
Arnamoy Bhattacharyya | 17d9bdf | 2022-07-25 20:31:23 -0400 | [diff] [blame] | 918 | else |
jeanPerier | 2ef370b | 2023-10-20 11:11:52 +0200 | [diff] [blame] | 919 | builder->setInsertionPointAfter(sb.getAddr().getDefiningOp()); |
Arnamoy Bhattacharyya | 17d9bdf | 2022-07-25 20:31:23 -0400 | [diff] [blame] | 920 | |
jeanPerier | 2ef370b | 2023-10-20 11:11:52 +0200 | [diff] [blame] | 921 | Fortran::lower::SymbolBox *lhs_sb, *rhs_sb; |
Kareem Ergawy | a0406ce | 2025-01-16 19:10:12 +0100 | [diff] [blame] | 922 | if (!hostIsSource) { |
jeanPerier | 2ef370b | 2023-10-20 11:11:52 +0200 | [diff] [blame] | 923 | lhs_sb = &hsb; |
| 924 | rhs_sb = &sb; |
Arnamoy Bhattacharyya | 17d9bdf | 2022-07-25 20:31:23 -0400 | [diff] [blame] | 925 | } else { |
jeanPerier | 2ef370b | 2023-10-20 11:11:52 +0200 | [diff] [blame] | 926 | lhs_sb = &sb; |
| 927 | rhs_sb = &hsb; |
Arnamoy Bhattacharyya | 17d9bdf | 2022-07-25 20:31:23 -0400 | [diff] [blame] | 928 | } |
| 929 | |
Leandro Lupori | 797f011 | 2024-09-05 14:55:01 -0300 | [diff] [blame] | 930 | copyVar(sym, *lhs_sb, *rhs_sb, sym.flags()); |
Kiran Chandramohan | 07e16a2 | 2022-04-11 09:05:00 +0000 | [diff] [blame] | 931 | } |
| 932 | |
Valentin Clement (バレンタイン クレメン) | fedc54b | 2023-12-14 09:25:27 -0800 | [diff] [blame] | 933 | void genEval(Fortran::lower::pft::Evaluation &eval, |
| 934 | bool unstructuredContext) override final { |
| 935 | genFIR(eval, unstructuredContext); |
| 936 | } |
| 937 | |
Kiran Chandramohan | 07e16a2 | 2022-04-11 09:05:00 +0000 | [diff] [blame] | 938 | //===--------------------------------------------------------------------===// |
| 939 | // Utility methods |
| 940 | //===--------------------------------------------------------------------===// |
| 941 | |
Peixin-Qiao | 411bd2d | 2022-06-07 15:08:17 +0800 | [diff] [blame] | 942 | void collectSymbolSet( |
| 943 | Fortran::lower::pft::Evaluation &eval, |
| 944 | llvm::SetVector<const Fortran::semantics::Symbol *> &symbolSet, |
Nimish Mishra | 435feef | 2022-08-12 16:46:26 +0530 | [diff] [blame] | 945 | Fortran::semantics::Symbol::Flag flag, bool collectSymbols, |
| 946 | bool checkHostAssociatedSymbols) override final { |
Peixin-Qiao | 411bd2d | 2022-06-07 15:08:17 +0800 | [diff] [blame] | 947 | auto addToList = [&](const Fortran::semantics::Symbol &sym) { |
Nimish Mishra | 435feef | 2022-08-12 16:46:26 +0530 | [diff] [blame] | 948 | std::function<void(const Fortran::semantics::Symbol &, bool)> |
| 949 | insertSymbols = [&](const Fortran::semantics::Symbol &oriSymbol, |
| 950 | bool collectSymbol) { |
Thirumalai Shaktivel | 091dcb8 | 2025-04-01 11:35:44 +0530 | [diff] [blame] | 951 | if (collectSymbol && oriSymbol.test(flag)) { |
Nimish Mishra | 435feef | 2022-08-12 16:46:26 +0530 | [diff] [blame] | 952 | symbolSet.insert(&oriSymbol); |
Thirumalai Shaktivel | 091dcb8 | 2025-04-01 11:35:44 +0530 | [diff] [blame] | 953 | } else if (const auto *commonDetails = |
| 954 | oriSymbol.detailsIf< |
| 955 | Fortran::semantics::CommonBlockDetails>()) { |
| 956 | for (const auto &mem : commonDetails->objects()) |
| 957 | if (collectSymbol && mem->test(flag)) |
| 958 | symbolSet.insert(&(*mem).GetUltimate()); |
| 959 | } else if (checkHostAssociatedSymbols) { |
Nimish Mishra | 435feef | 2022-08-12 16:46:26 +0530 | [diff] [blame] | 960 | if (const auto *details{ |
| 961 | oriSymbol |
| 962 | .detailsIf<Fortran::semantics::HostAssocDetails>()}) |
| 963 | insertSymbols(details->symbol(), true); |
Thirumalai Shaktivel | 091dcb8 | 2025-04-01 11:35:44 +0530 | [diff] [blame] | 964 | } |
Nimish Mishra | 435feef | 2022-08-12 16:46:26 +0530 | [diff] [blame] | 965 | }; |
| 966 | insertSymbols(sym, collectSymbols); |
Peixin-Qiao | 411bd2d | 2022-06-07 15:08:17 +0800 | [diff] [blame] | 967 | }; |
| 968 | Fortran::lower::pft::visitAllSymbols(eval, addToList); |
| 969 | } |
| 970 | |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 971 | mlir::Location getCurrentLocation() override final { return toLocation(); } |
| 972 | |
| 973 | /// Generate a dummy location. |
| 974 | mlir::Location genUnknownLocation() override final { |
| 975 | // Note: builder may not be instantiated yet |
| 976 | return mlir::UnknownLoc::get(&getMLIRContext()); |
| 977 | } |
| 978 | |
Valentin Clement (バレンタイン クレメン) | 0ee0eeb | 2024-07-23 09:49:17 -0700 | [diff] [blame] | 979 | static mlir::Location genLocation(Fortran::parser::SourcePosition pos, |
| 980 | mlir::MLIRContext &ctx) { |
| 981 | llvm::SmallString<256> path(*pos.path); |
| 982 | llvm::sys::fs::make_absolute(path); |
| 983 | llvm::sys::path::remove_dots(path); |
| 984 | return mlir::FileLineColLoc::get(&ctx, path.str(), pos.line, pos.column); |
| 985 | } |
| 986 | |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 987 | /// Generate a `Location` from the `CharBlock`. |
| 988 | mlir::Location |
| 989 | genLocation(const Fortran::parser::CharBlock &block) override final { |
Valentin Clement (バレンタイン クレメン) | 0ee0eeb | 2024-07-23 09:49:17 -0700 | [diff] [blame] | 990 | mlir::Location mainLocation = genUnknownLocation(); |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 991 | if (const Fortran::parser::AllCookedSources *cooked = |
| 992 | bridge.getCookedSource()) { |
jeanPerier | 43d2ef2 | 2023-09-26 20:33:01 +0200 | [diff] [blame] | 993 | if (std::optional<Fortran::parser::ProvenanceRange> provenance = |
| 994 | cooked->GetProvenanceRange(block)) { |
| 995 | if (std::optional<Fortran::parser::SourcePosition> filePos = |
Valentin Clement (バレンタイン クレメン) | 0ee0eeb | 2024-07-23 09:49:17 -0700 | [diff] [blame] | 996 | cooked->allSources().GetSourcePosition(provenance->start())) |
| 997 | mainLocation = genLocation(*filePos, getMLIRContext()); |
| 998 | |
| 999 | llvm::SmallVector<mlir::Location> locs; |
| 1000 | locs.push_back(mainLocation); |
| 1001 | |
| 1002 | llvm::SmallVector<fir::LocationKindAttr> locAttrs; |
| 1003 | locAttrs.push_back(fir::LocationKindAttr::get(&getMLIRContext(), |
| 1004 | fir::LocationKind::Base)); |
| 1005 | |
| 1006 | // Gather include location information if any. |
| 1007 | Fortran::parser::ProvenanceRange *prov = &*provenance; |
| 1008 | while (prov) { |
| 1009 | if (std::optional<Fortran::parser::ProvenanceRange> include = |
| 1010 | cooked->allSources().GetInclusionInfo(*prov)) { |
| 1011 | if (std::optional<Fortran::parser::SourcePosition> incPos = |
| 1012 | cooked->allSources().GetSourcePosition(include->start())) { |
| 1013 | locs.push_back(genLocation(*incPos, getMLIRContext())); |
| 1014 | locAttrs.push_back(fir::LocationKindAttr::get( |
| 1015 | &getMLIRContext(), fir::LocationKind::Inclusion)); |
| 1016 | } |
| 1017 | prov = &*include; |
| 1018 | } else { |
| 1019 | prov = nullptr; |
| 1020 | } |
| 1021 | } |
| 1022 | if (locs.size() > 1) { |
| 1023 | assert(locs.size() == locAttrs.size() && |
| 1024 | "expect as many attributes as locations"); |
| 1025 | return mlir::FusedLocWith<fir::LocationKindArrayAttr>::get( |
| 1026 | &getMLIRContext(), locs, |
| 1027 | fir::LocationKindArrayAttr::get(&getMLIRContext(), locAttrs)); |
jeanPerier | 43d2ef2 | 2023-09-26 20:33:01 +0200 | [diff] [blame] | 1028 | } |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1029 | } |
| 1030 | } |
Valentin Clement (バレンタイン クレメン) | 0ee0eeb | 2024-07-23 09:49:17 -0700 | [diff] [blame] | 1031 | return mainLocation; |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1032 | } |
| 1033 | |
V Donaldson | 6f7a3b0 | 2023-05-16 13:34:57 -0700 | [diff] [blame] | 1034 | const Fortran::semantics::Scope &getCurrentScope() override final { |
| 1035 | return bridge.getSemanticsContext().FindScope(currentPosition); |
| 1036 | } |
| 1037 | |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1038 | fir::FirOpBuilder &getFirOpBuilder() override final { return *builder; } |
| 1039 | |
Matthias Springer | c870632 | 2024-12-25 09:42:03 +0100 | [diff] [blame] | 1040 | mlir::ModuleOp getModuleOp() override final { return bridge.getModule(); } |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1041 | |
| 1042 | mlir::MLIRContext &getMLIRContext() override final { |
| 1043 | return bridge.getMLIRContext(); |
| 1044 | } |
| 1045 | std::string |
| 1046 | mangleName(const Fortran::semantics::Symbol &symbol) override final { |
jeanPerier | 6ffea74 | 2023-09-08 10:43:55 +0200 | [diff] [blame] | 1047 | return Fortran::lower::mangle::mangleName( |
| 1048 | symbol, scopeBlockIdMap, /*keepExternalInScope=*/false, |
| 1049 | getLoweringOptions().getUnderscoring()); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1050 | } |
| 1051 | std::string mangleName( |
| 1052 | const Fortran::semantics::DerivedTypeSpec &derivedType) override final { |
| 1053 | return Fortran::lower::mangle::mangleName(derivedType, scopeBlockIdMap); |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1054 | } |
V Donaldson | 6f7a3b0 | 2023-05-16 13:34:57 -0700 | [diff] [blame] | 1055 | std::string mangleName(std::string &name) override final { |
| 1056 | return Fortran::lower::mangle::mangleName(name, getCurrentScope(), |
| 1057 | scopeBlockIdMap); |
| 1058 | } |
Akash Banerjee | 9905728 | 2025-02-18 16:36:01 +0000 | [diff] [blame] | 1059 | std::string |
| 1060 | mangleName(std::string &name, |
| 1061 | const Fortran::semantics::Scope &myScope) override final { |
| 1062 | return Fortran::lower::mangle::mangleName(name, myScope, scopeBlockIdMap); |
| 1063 | } |
jeanPerier | 99a54b8 | 2023-09-18 14:59:56 +0200 | [diff] [blame] | 1064 | std::string getRecordTypeFieldName( |
| 1065 | const Fortran::semantics::Symbol &component) override final { |
| 1066 | return Fortran::lower::mangle::getRecordTypeFieldName(component, |
| 1067 | scopeBlockIdMap); |
| 1068 | } |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1069 | const fir::KindMapping &getKindMap() override final { |
| 1070 | return bridge.getKindMap(); |
| 1071 | } |
| 1072 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1073 | /// Return the current function context, which may be a nested BLOCK context |
| 1074 | /// or a full subprogram context. |
Valentin Clement | 97492fd1a | 2023-01-31 13:46:12 +0100 | [diff] [blame] | 1075 | Fortran::lower::StatementContext &getFctCtx() override final { |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1076 | if (!activeConstructStack.empty() && |
| 1077 | activeConstructStack.back().eval.isA<Fortran::parser::BlockConstruct>()) |
| 1078 | return activeConstructStack.back().stmtCtx; |
Valentin Clement | 97492fd1a | 2023-01-31 13:46:12 +0100 | [diff] [blame] | 1079 | return bridge.fctCtx(); |
| 1080 | } |
| 1081 | |
Valentin Clement | d0b70a0 | 2022-02-23 19:48:07 +0100 | [diff] [blame] | 1082 | mlir::Value hostAssocTupleValue() override final { return hostAssocTuple; } |
| 1083 | |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 1084 | /// Record a binding for the ssa-value of the tuple for this function. |
| 1085 | void bindHostAssocTuple(mlir::Value val) override final { |
| 1086 | assert(!hostAssocTuple && val); |
| 1087 | hostAssocTuple = val; |
| 1088 | } |
| 1089 | |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 1090 | mlir::Value dummyArgsScopeValue() const override final { |
| 1091 | return dummyArgsScope; |
| 1092 | } |
| 1093 | |
| 1094 | bool isRegisteredDummySymbol( |
| 1095 | Fortran::semantics::SymbolRef symRef) const override final { |
| 1096 | auto *sym = &*symRef; |
| 1097 | return registeredDummySymbols.contains(sym); |
| 1098 | } |
| 1099 | |
jeanPerier | bb8bf85 | 2024-11-26 09:21:13 +0100 | [diff] [blame] | 1100 | const Fortran::lower::pft::FunctionLikeUnit * |
| 1101 | getCurrentFunctionUnit() const override final { |
| 1102 | return currentFunctionUnit; |
| 1103 | } |
| 1104 | |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 1105 | void registerTypeInfo(mlir::Location loc, |
| 1106 | Fortran::lower::SymbolRef typeInfoSym, |
| 1107 | const Fortran::semantics::DerivedTypeSpec &typeSpec, |
| 1108 | fir::RecordType type) override final { |
| 1109 | typeInfoConverter.registerTypeInfo(*this, loc, typeInfoSym, typeSpec, type); |
Valentin Clement | 6393d2e | 2022-11-17 10:53:13 +0100 | [diff] [blame] | 1110 | } |
| 1111 | |
Slava Zakharin | be5747e | 2023-05-09 19:50:48 -0700 | [diff] [blame] | 1112 | llvm::StringRef |
| 1113 | getUniqueLitName(mlir::Location loc, |
| 1114 | std::unique_ptr<Fortran::lower::SomeExpr> expr, |
| 1115 | mlir::Type eleTy) override final { |
| 1116 | std::string namePrefix = |
| 1117 | getConstantExprManglePrefix(loc, *expr.get(), eleTy); |
| 1118 | auto [it, inserted] = literalNamesMap.try_emplace( |
| 1119 | expr.get(), namePrefix + std::to_string(uniqueLitId)); |
| 1120 | const auto &name = it->second; |
| 1121 | if (inserted) { |
| 1122 | // Keep ownership of the expr key. |
| 1123 | literalExprsStorage.push_back(std::move(expr)); |
| 1124 | |
| 1125 | // If we've just added a new name, we have to make sure |
| 1126 | // there is no global object with the same name in the module. |
| 1127 | fir::GlobalOp global = builder->getNamedGlobal(name); |
| 1128 | if (global) |
| 1129 | fir::emitFatalError(loc, llvm::Twine("global object with name '") + |
| 1130 | llvm::Twine(name) + |
| 1131 | llvm::Twine("' already exists")); |
| 1132 | ++uniqueLitId; |
| 1133 | return name; |
| 1134 | } |
| 1135 | |
| 1136 | // The name already exists. Verify that the prefix is the same. |
| 1137 | if (!llvm::StringRef(name).starts_with(namePrefix)) |
| 1138 | fir::emitFatalError(loc, llvm::Twine("conflicting prefixes: '") + |
| 1139 | llvm::Twine(name) + |
| 1140 | llvm::Twine("' does not start with '") + |
| 1141 | llvm::Twine(namePrefix) + llvm::Twine("'")); |
| 1142 | |
| 1143 | return name; |
| 1144 | } |
| 1145 | |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1146 | private: |
| 1147 | FirConverter() = delete; |
| 1148 | FirConverter(const FirConverter &) = delete; |
| 1149 | FirConverter &operator=(const FirConverter &) = delete; |
| 1150 | |
| 1151 | //===--------------------------------------------------------------------===// |
| 1152 | // Helper member functions |
| 1153 | //===--------------------------------------------------------------------===// |
| 1154 | |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 1155 | mlir::Value createFIRExpr(mlir::Location loc, |
| 1156 | const Fortran::lower::SomeExpr *expr, |
| 1157 | Fortran::lower::StatementContext &stmtCtx) { |
| 1158 | return fir::getBase(genExprValue(*expr, stmtCtx, &loc)); |
| 1159 | } |
| 1160 | |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1161 | /// Find the symbol in the local map or return null. |
| 1162 | Fortran::lower::SymbolBox |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 1163 | lookupSymbol(const Fortran::semantics::Symbol &sym, |
Kareem Ergawy | 3b30559 | 2024-03-11 10:38:28 +0100 | [diff] [blame] | 1164 | Fortran::lower::SymMap *symMap = nullptr, |
| 1165 | bool forceHlfirBase = false) { |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 1166 | symMap = symMap ? symMap : &localSymbols; |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 1167 | if (lowerToHighLevelFIR()) { |
Kazu Hirata | c092158 | 2023-01-07 22:26:48 -0800 | [diff] [blame] | 1168 | if (std::optional<fir::FortranVariableOpInterface> var = |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 1169 | symMap->lookupVariableDefinition(sym)) { |
Kareem Ergawy | 3b30559 | 2024-03-11 10:38:28 +0100 | [diff] [blame] | 1170 | auto exv = hlfir::translateToExtendedValue(toLocation(), *builder, *var, |
| 1171 | forceHlfirBase); |
Jean Perier | 1981116 | 2022-12-05 09:05:37 +0100 | [diff] [blame] | 1172 | return exv.match( |
| 1173 | [](mlir::Value x) -> Fortran::lower::SymbolBox { |
| 1174 | return Fortran::lower::SymbolBox::Intrinsic{x}; |
| 1175 | }, |
| 1176 | [](auto x) -> Fortran::lower::SymbolBox { return x; }); |
| 1177 | } |
Slava Zakharin | 4eab303 | 2023-05-16 20:05:22 -0700 | [diff] [blame] | 1178 | |
| 1179 | // Entry character result represented as an argument pair |
| 1180 | // needs to be represented in the symbol table even before |
| 1181 | // we can create DeclareOp for it. The temporary mapping |
| 1182 | // is EmboxCharOp that conveys the address and length information. |
| 1183 | // After mapSymbolAttributes is done, the mapping is replaced |
| 1184 | // with the new DeclareOp, and the following table lookups |
| 1185 | // do not reach here. |
| 1186 | if (sym.IsFuncResult()) |
| 1187 | if (const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType()) |
| 1188 | if (declTy->category() == |
| 1189 | Fortran::semantics::DeclTypeSpec::Category::Character) |
| 1190 | return symMap->lookupSymbol(sym); |
| 1191 | |
Jean Perier | cedfd27 | 2023-02-09 09:02:43 +0100 | [diff] [blame] | 1192 | // Procedure dummies are not mapped with an hlfir.declare because |
| 1193 | // they are not "variable" (cannot be assigned to), and it would |
| 1194 | // make hlfir.declare more complex than it needs to to allow this. |
| 1195 | // Do a regular lookup. |
| 1196 | if (Fortran::semantics::IsProcedure(sym)) |
| 1197 | return symMap->lookupSymbol(sym); |
Kiran Chandramohan | 8b834ca | 2023-08-23 11:37:00 +0000 | [diff] [blame] | 1198 | |
| 1199 | // Commonblock names are not variables, but in some lowerings (like |
| 1200 | // OpenMP) it is useful to maintain the address of the commonblock in an |
| 1201 | // MLIR value and query it. hlfir.declare need not be created for these. |
| 1202 | if (sym.detailsIf<Fortran::semantics::CommonBlockDetails>()) |
| 1203 | return symMap->lookupSymbol(sym); |
| 1204 | |
Kareem Ergawy | 26b8be2 | 2024-02-28 10:15:57 +0100 | [diff] [blame] | 1205 | // For symbols to be privatized in OMP, the symbol is mapped to an |
| 1206 | // instance of `SymbolBox::Intrinsic` (i.e. a direct mapping to an MLIR |
| 1207 | // SSA value). This MLIR SSA value is the block argument to the |
| 1208 | // `omp.private`'s `alloc` block. If this is the case, we return this |
| 1209 | // `SymbolBox::Intrinsic` value. |
| 1210 | if (Fortran::lower::SymbolBox v = symMap->lookupSymbol(sym)) |
Kareem Ergawy | 87cee71 | 2024-03-18 10:44:44 +0100 | [diff] [blame] | 1211 | return v; |
Kareem Ergawy | 26b8be2 | 2024-02-28 10:15:57 +0100 | [diff] [blame] | 1212 | |
Jean Perier | 1981116 | 2022-12-05 09:05:37 +0100 | [diff] [blame] | 1213 | return {}; |
| 1214 | } |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 1215 | if (Fortran::lower::SymbolBox v = symMap->lookupSymbol(sym)) |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1216 | return v; |
| 1217 | return {}; |
| 1218 | } |
| 1219 | |
Valentin Clement | a142501 | 2022-03-15 21:57:30 +0100 | [diff] [blame] | 1220 | /// Find the symbol in the inner-most level of the local map or return null. |
| 1221 | Fortran::lower::SymbolBox |
| 1222 | shallowLookupSymbol(const Fortran::semantics::Symbol &sym) { |
| 1223 | if (Fortran::lower::SymbolBox v = localSymbols.shallowLookupSymbol(sym)) |
| 1224 | return v; |
| 1225 | return {}; |
| 1226 | } |
| 1227 | |
Peixin-Qiao | 27afb36 | 2022-06-24 15:33:09 +0800 | [diff] [blame] | 1228 | /// Find the symbol in one level up of symbol map such as for host-association |
| 1229 | /// in OpenMP code or return null. |
| 1230 | Fortran::lower::SymbolBox |
Kareem Ergawy | 26b8be2 | 2024-02-28 10:15:57 +0100 | [diff] [blame] | 1231 | lookupOneLevelUpSymbol(const Fortran::semantics::Symbol &sym) override { |
Peixin-Qiao | 27afb36 | 2022-06-24 15:33:09 +0800 | [diff] [blame] | 1232 | if (Fortran::lower::SymbolBox v = localSymbols.lookupOneLevelUpSymbol(sym)) |
| 1233 | return v; |
| 1234 | return {}; |
| 1235 | } |
| 1236 | |
jeanPerier | a4798bb | 2024-04-02 14:29:29 +0200 | [diff] [blame] | 1237 | mlir::SymbolTable *getMLIRSymbolTable() override { return &mlirSymbolTable; } |
| 1238 | |
Valentin Clement | da7c77b | 2022-02-16 20:27:23 +0100 | [diff] [blame] | 1239 | /// Add the symbol to the local map and return `true`. If the symbol is |
| 1240 | /// already in the map and \p forced is `false`, the map is not updated. |
| 1241 | /// Instead the value `false` is returned. |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 1242 | bool addSymbol(const Fortran::semantics::SymbolRef sym, |
| 1243 | fir::ExtendedValue val, bool forced = false) { |
| 1244 | if (!forced && lookupSymbol(sym)) |
| 1245 | return false; |
| 1246 | if (lowerToHighLevelFIR()) { |
Slava Zakharin | 47025af | 2023-09-18 09:59:06 -0700 | [diff] [blame] | 1247 | Fortran::lower::genDeclareSymbol(*this, localSymbols, sym, val, |
| 1248 | fir::FortranVariableFlagsEnum::None, |
| 1249 | forced); |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 1250 | } else { |
| 1251 | localSymbols.addSymbol(sym, val, forced); |
| 1252 | } |
| 1253 | return true; |
| 1254 | } |
| 1255 | |
Leandro Lupori | e50a231 | 2024-02-21 14:51:37 -0300 | [diff] [blame] | 1256 | void copyVar(const Fortran::semantics::Symbol &sym, |
| 1257 | const Fortran::lower::SymbolBox &lhs_sb, |
Leandro Lupori | 797f011 | 2024-09-05 14:55:01 -0300 | [diff] [blame] | 1258 | const Fortran::lower::SymbolBox &rhs_sb, |
| 1259 | Fortran::semantics::Symbol::Flags flags) { |
Leandro Lupori | e50a231 | 2024-02-21 14:51:37 -0300 | [diff] [blame] | 1260 | mlir::Location loc = genLocation(sym.name()); |
| 1261 | if (lowerToHighLevelFIR()) |
Leandro Lupori | 797f011 | 2024-09-05 14:55:01 -0300 | [diff] [blame] | 1262 | copyVarHLFIR(loc, lhs_sb, rhs_sb, flags); |
Leandro Lupori | e50a231 | 2024-02-21 14:51:37 -0300 | [diff] [blame] | 1263 | else |
| 1264 | copyVarFIR(loc, sym, lhs_sb, rhs_sb); |
| 1265 | } |
| 1266 | |
Kareem Ergawy | 87cee71 | 2024-03-18 10:44:44 +0100 | [diff] [blame] | 1267 | void copyVarHLFIR(mlir::Location loc, Fortran::lower::SymbolBox dst, |
Leandro Lupori | 797f011 | 2024-09-05 14:55:01 -0300 | [diff] [blame] | 1268 | Fortran::lower::SymbolBox src, |
| 1269 | Fortran::semantics::Symbol::Flags flags) { |
Leandro Lupori | e50a231 | 2024-02-21 14:51:37 -0300 | [diff] [blame] | 1270 | assert(lowerToHighLevelFIR()); |
Leandro Lupori | 952bdaa | 2024-06-25 09:25:41 -0300 | [diff] [blame] | 1271 | |
| 1272 | bool isBoxAllocatable = dst.match( |
| 1273 | [](const fir::MutableBoxValue &box) { return box.isAllocatable(); }, |
| 1274 | [](const fir::FortranVariableOpInterface &box) { |
| 1275 | return fir::FortranVariableOpInterface(box).isAllocatable(); |
| 1276 | }, |
| 1277 | [](const auto &box) { return false; }); |
| 1278 | |
| 1279 | bool isBoxPointer = dst.match( |
| 1280 | [](const fir::MutableBoxValue &box) { return box.isPointer(); }, |
| 1281 | [](const fir::FortranVariableOpInterface &box) { |
| 1282 | return fir::FortranVariableOpInterface(box).isPointer(); |
| 1283 | }, |
Leandro Lupori | 29f5d5b | 2025-03-11 09:38:40 -0300 | [diff] [blame] | 1284 | [](const fir::AbstractBox &box) { |
| 1285 | return fir::isBoxProcAddressType(box.getAddr().getType()); |
| 1286 | }, |
Leandro Lupori | 952bdaa | 2024-06-25 09:25:41 -0300 | [diff] [blame] | 1287 | [](const auto &box) { return false; }); |
| 1288 | |
Leandro Lupori | 797f011 | 2024-09-05 14:55:01 -0300 | [diff] [blame] | 1289 | copyVarHLFIR(loc, dst, src, isBoxAllocatable, isBoxPointer, flags); |
Leandro Lupori | 952bdaa | 2024-06-25 09:25:41 -0300 | [diff] [blame] | 1290 | } |
| 1291 | |
| 1292 | void copyVarHLFIR(mlir::Location loc, Fortran::lower::SymbolBox dst, |
| 1293 | Fortran::lower::SymbolBox src, bool isAllocatable, |
Leandro Lupori | 797f011 | 2024-09-05 14:55:01 -0300 | [diff] [blame] | 1294 | bool isPointer, Fortran::semantics::Symbol::Flags flags) { |
Leandro Lupori | 952bdaa | 2024-06-25 09:25:41 -0300 | [diff] [blame] | 1295 | assert(lowerToHighLevelFIR()); |
Kareem Ergawy | 87cee71 | 2024-03-18 10:44:44 +0100 | [diff] [blame] | 1296 | hlfir::Entity lhs{dst.getAddr()}; |
| 1297 | hlfir::Entity rhs{src.getAddr()}; |
Leandro Lupori | 797f011 | 2024-09-05 14:55:01 -0300 | [diff] [blame] | 1298 | |
Leandro Lupori | e50a231 | 2024-02-21 14:51:37 -0300 | [diff] [blame] | 1299 | auto copyData = [&](hlfir::Entity l, hlfir::Entity r) { |
| 1300 | // Dereference RHS and load it if trivial scalar. |
| 1301 | r = hlfir::loadTrivialScalar(loc, *builder, r); |
Leandro Lupori | 797f011 | 2024-09-05 14:55:01 -0300 | [diff] [blame] | 1302 | builder->create<hlfir::AssignOp>(loc, r, l, isAllocatable); |
Leandro Lupori | e50a231 | 2024-02-21 14:51:37 -0300 | [diff] [blame] | 1303 | }; |
Kareem Ergawy | 87cee71 | 2024-03-18 10:44:44 +0100 | [diff] [blame] | 1304 | |
Leandro Lupori | 797f011 | 2024-09-05 14:55:01 -0300 | [diff] [blame] | 1305 | if (isPointer) { |
Leandro Lupori | e50a231 | 2024-02-21 14:51:37 -0300 | [diff] [blame] | 1306 | // Set LHS target to the target of RHS (do not copy the RHS |
| 1307 | // target data into the LHS target storage). |
| 1308 | auto loadVal = builder->create<fir::LoadOp>(loc, rhs); |
| 1309 | builder->create<fir::StoreOp>(loc, loadVal, lhs); |
Leandro Lupori | 797f011 | 2024-09-05 14:55:01 -0300 | [diff] [blame] | 1310 | } else if (isAllocatable && |
Kaviya Rajendiran | daa1820 | 2025-01-23 11:14:00 +0530 | [diff] [blame] | 1311 | flags.test(Fortran::semantics::Symbol::Flag::OmpCopyIn)) { |
| 1312 | // For copyin allocatable variables, RHS must be copied to lhs |
| 1313 | // only when rhs is allocated. |
| 1314 | hlfir::Entity temp = |
| 1315 | hlfir::derefPointersAndAllocatables(loc, *builder, rhs); |
| 1316 | mlir::Value addr = hlfir::genVariableRawAddress(loc, *builder, temp); |
| 1317 | mlir::Value isAllocated = builder->genIsNotNullAddr(loc, addr); |
| 1318 | builder->genIfThenElse(loc, isAllocated) |
| 1319 | .genThen([&]() { copyData(lhs, rhs); }) |
| 1320 | .genElse([&]() { |
| 1321 | fir::ExtendedValue hexv = symBoxToExtendedValue(dst); |
| 1322 | hexv.match( |
| 1323 | [&](const fir::MutableBoxValue &new_box) -> void { |
| 1324 | // if the allocation status of original list item is |
| 1325 | // unallocated, unallocate the copy if it is allocated, else |
| 1326 | // do nothing. |
| 1327 | Fortran::lower::genDeallocateIfAllocated(*this, new_box, loc); |
| 1328 | }, |
| 1329 | [&](const auto &) -> void {}); |
| 1330 | }) |
| 1331 | .end(); |
| 1332 | } else if (isAllocatable && |
| 1333 | flags.test(Fortran::semantics::Symbol::Flag::OmpFirstPrivate)) { |
| 1334 | // For firstprivate allocatable variables, RHS must be copied |
David Truby | 53b5902 | 2024-09-10 14:59:21 +0100 | [diff] [blame] | 1335 | // only when LHS is allocated. |
Leandro Lupori | 797f011 | 2024-09-05 14:55:01 -0300 | [diff] [blame] | 1336 | hlfir::Entity temp = |
| 1337 | hlfir::derefPointersAndAllocatables(loc, *builder, lhs); |
| 1338 | mlir::Value addr = hlfir::genVariableRawAddress(loc, *builder, temp); |
| 1339 | mlir::Value isAllocated = builder->genIsNotNullAddr(loc, addr); |
| 1340 | builder->genIfThen(loc, isAllocated) |
| 1341 | .genThen([&]() { copyData(lhs, rhs); }) |
| 1342 | .end(); |
Leandro Lupori | e50a231 | 2024-02-21 14:51:37 -0300 | [diff] [blame] | 1343 | } else { |
Leandro Lupori | e50a231 | 2024-02-21 14:51:37 -0300 | [diff] [blame] | 1344 | copyData(lhs, rhs); |
| 1345 | } |
| 1346 | } |
| 1347 | |
| 1348 | void copyVarFIR(mlir::Location loc, const Fortran::semantics::Symbol &sym, |
| 1349 | const Fortran::lower::SymbolBox &lhs_sb, |
| 1350 | const Fortran::lower::SymbolBox &rhs_sb) { |
| 1351 | assert(!lowerToHighLevelFIR()); |
| 1352 | fir::ExtendedValue lhs = symBoxToExtendedValue(lhs_sb); |
| 1353 | fir::ExtendedValue rhs = symBoxToExtendedValue(rhs_sb); |
| 1354 | mlir::Type symType = genType(sym); |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 1355 | if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(symType)) { |
Leandro Lupori | e50a231 | 2024-02-21 14:51:37 -0300 | [diff] [blame] | 1356 | Fortran::lower::StatementContext stmtCtx; |
| 1357 | Fortran::lower::createSomeArrayAssignment(*this, lhs, rhs, localSymbols, |
| 1358 | stmtCtx); |
| 1359 | stmtCtx.finalizeAndReset(); |
| 1360 | } else if (lhs.getBoxOf<fir::CharBoxValue>()) { |
| 1361 | fir::factory::CharacterExprHelper{*builder, loc}.createAssign(lhs, rhs); |
| 1362 | } else { |
| 1363 | auto loadVal = builder->create<fir::LoadOp>(loc, fir::getBase(rhs)); |
| 1364 | builder->create<fir::StoreOp>(loc, loadVal, fir::getBase(lhs)); |
| 1365 | } |
| 1366 | } |
| 1367 | |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 1368 | /// Map a block argument to a result or dummy symbol. This is not the |
| 1369 | /// definitive mapping. The specification expression have not been lowered |
| 1370 | /// yet. The final mapping will be done using this pre-mapping in |
| 1371 | /// Fortran::lower::mapSymbolAttributes. |
| 1372 | bool mapBlockArgToDummyOrResult(const Fortran::semantics::SymbolRef sym, |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 1373 | mlir::Value val, bool isResult) { |
| 1374 | localSymbols.addSymbol(sym, val); |
| 1375 | if (!isResult) |
| 1376 | registerDummySymbol(sym); |
| 1377 | |
Valentin Clement | da7c77b | 2022-02-16 20:27:23 +0100 | [diff] [blame] | 1378 | return true; |
| 1379 | } |
| 1380 | |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 1381 | /// Generate the address of loop variable \p sym. |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 1382 | /// If \p sym is not mapped yet, allocate local storage for it. |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 1383 | mlir::Value genLoopVariableAddress(mlir::Location loc, |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 1384 | const Fortran::semantics::Symbol &sym, |
| 1385 | bool isUnordered) { |
| 1386 | if (isUnordered || sym.has<Fortran::semantics::HostAssocDetails>() || |
| 1387 | sym.has<Fortran::semantics::UseDetails>()) { |
Mats Petersson | 8e10a3f | 2024-09-13 12:57:11 +0100 | [diff] [blame] | 1388 | if (!shallowLookupSymbol(sym) && |
| 1389 | !sym.test(Fortran::semantics::Symbol::Flag::OmpShared)) { |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 1390 | // Do concurrent loop variables are not mapped yet since they are local |
| 1391 | // to the Do concurrent scope (same for OpenMP loops). |
Kiran Chandramohan | 90f58eb | 2023-09-01 10:44:35 +0000 | [diff] [blame] | 1392 | mlir::OpBuilder::InsertPoint insPt = builder->saveInsertionPoint(); |
| 1393 | builder->setInsertionPointToStart(builder->getAllocaBlock()); |
| 1394 | mlir::Type tempTy = genType(sym); |
| 1395 | mlir::Value temp = |
| 1396 | builder->createTemporaryAlloc(loc, tempTy, toStringRef(sym.name())); |
| 1397 | bindIfNewSymbol(sym, temp); |
| 1398 | builder->restoreInsertionPoint(insPt); |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 1399 | } |
| 1400 | } |
| 1401 | auto entry = lookupSymbol(sym); |
| 1402 | (void)entry; |
| 1403 | assert(entry && "loop control variable must already be in map"); |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 1404 | Fortran::lower::StatementContext stmtCtx; |
| 1405 | return fir::getBase( |
| 1406 | genExprAddr(Fortran::evaluate::AsGenericExpr(sym).value(), stmtCtx)); |
| 1407 | } |
| 1408 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 1409 | static bool isNumericScalarCategory(Fortran::common::TypeCategory cat) { |
Valentin Clement | e641c29 | 2022-02-17 18:23:22 +0100 | [diff] [blame] | 1410 | return cat == Fortran::common::TypeCategory::Integer || |
| 1411 | cat == Fortran::common::TypeCategory::Real || |
| 1412 | cat == Fortran::common::TypeCategory::Complex || |
| 1413 | cat == Fortran::common::TypeCategory::Logical; |
| 1414 | } |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 1415 | static bool isLogicalCategory(Fortran::common::TypeCategory cat) { |
| 1416 | return cat == Fortran::common::TypeCategory::Logical; |
| 1417 | } |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 1418 | static bool isCharacterCategory(Fortran::common::TypeCategory cat) { |
Valentin Clement | e641c29 | 2022-02-17 18:23:22 +0100 | [diff] [blame] | 1419 | return cat == Fortran::common::TypeCategory::Character; |
| 1420 | } |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 1421 | static bool isDerivedCategory(Fortran::common::TypeCategory cat) { |
Valentin Clement | e641c29 | 2022-02-17 18:23:22 +0100 | [diff] [blame] | 1422 | return cat == Fortran::common::TypeCategory::Derived; |
| 1423 | } |
| 1424 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1425 | /// Insert a new block before \p block. Leave the insertion point unchanged. |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 1426 | mlir::Block *insertBlock(mlir::Block *block) { |
| 1427 | mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); |
| 1428 | mlir::Block *newBlock = builder->createBlock(block); |
| 1429 | builder->restoreInsertionPoint(insertPt); |
| 1430 | return newBlock; |
| 1431 | } |
| 1432 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1433 | Fortran::lower::pft::Evaluation &evalOfLabel(Fortran::parser::Label label) { |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 1434 | const Fortran::lower::pft::LabelEvalMap &labelEvaluationMap = |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1435 | getEval().getOwningProcedure()->labelEvaluationMap; |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 1436 | const auto iter = labelEvaluationMap.find(label); |
| 1437 | assert(iter != labelEvaluationMap.end() && "label missing from map"); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1438 | return *iter->second; |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 1439 | } |
| 1440 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1441 | void genBranch(mlir::Block *targetBlock) { |
Kiran Chandramohan | ae37bb9 | 2022-02-08 23:01:39 +0000 | [diff] [blame] | 1442 | assert(targetBlock && "missing unconditional target block"); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 1443 | builder->create<mlir::cf::BranchOp>(toLocation(), targetBlock); |
Kiran Chandramohan | ae37bb9 | 2022-02-08 23:01:39 +0000 | [diff] [blame] | 1444 | } |
| 1445 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1446 | void genConditionalBranch(mlir::Value cond, mlir::Block *trueTarget, |
| 1447 | mlir::Block *falseTarget) { |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 1448 | assert(trueTarget && "missing conditional branch true block"); |
| 1449 | assert(falseTarget && "missing conditional branch false block"); |
| 1450 | mlir::Location loc = toLocation(); |
| 1451 | mlir::Value bcc = builder->createConvert(loc, builder->getI1Type(), cond); |
Kazu Hirata | 9a41739 | 2022-12-03 12:14:21 -0800 | [diff] [blame] | 1452 | builder->create<mlir::cf::CondBranchOp>(loc, bcc, trueTarget, std::nullopt, |
| 1453 | falseTarget, std::nullopt); |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 1454 | } |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1455 | void genConditionalBranch(mlir::Value cond, |
| 1456 | Fortran::lower::pft::Evaluation *trueTarget, |
| 1457 | Fortran::lower::pft::Evaluation *falseTarget) { |
| 1458 | genConditionalBranch(cond, trueTarget->block, falseTarget->block); |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 1459 | } |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1460 | void genConditionalBranch(const Fortran::parser::ScalarLogicalExpr &expr, |
| 1461 | mlir::Block *trueTarget, mlir::Block *falseTarget) { |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 1462 | Fortran::lower::StatementContext stmtCtx; |
| 1463 | mlir::Value cond = |
| 1464 | createFIRExpr(toLocation(), Fortran::semantics::GetExpr(expr), stmtCtx); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1465 | stmtCtx.finalizeAndReset(); |
| 1466 | genConditionalBranch(cond, trueTarget, falseTarget); |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 1467 | } |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1468 | void genConditionalBranch(const Fortran::parser::ScalarLogicalExpr &expr, |
| 1469 | Fortran::lower::pft::Evaluation *trueTarget, |
| 1470 | Fortran::lower::pft::Evaluation *falseTarget) { |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 1471 | Fortran::lower::StatementContext stmtCtx; |
| 1472 | mlir::Value cond = |
| 1473 | createFIRExpr(toLocation(), Fortran::semantics::GetExpr(expr), stmtCtx); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1474 | stmtCtx.finalizeAndReset(); |
| 1475 | genConditionalBranch(cond, trueTarget->block, falseTarget->block); |
| 1476 | } |
| 1477 | |
| 1478 | /// Return the nearest active ancestor construct of \p eval, or nullptr. |
| 1479 | Fortran::lower::pft::Evaluation * |
| 1480 | getActiveAncestor(const Fortran::lower::pft::Evaluation &eval) { |
| 1481 | Fortran::lower::pft::Evaluation *ancestor = eval.parentConstruct; |
| 1482 | for (; ancestor; ancestor = ancestor->parentConstruct) |
| 1483 | if (ancestor->activeConstruct) |
| 1484 | break; |
| 1485 | return ancestor; |
| 1486 | } |
| 1487 | |
| 1488 | /// Return the predicate: "a branch to \p targetEval has exit code". |
| 1489 | bool hasExitCode(const Fortran::lower::pft::Evaluation &targetEval) { |
| 1490 | Fortran::lower::pft::Evaluation *activeAncestor = |
| 1491 | getActiveAncestor(targetEval); |
| 1492 | for (auto it = activeConstructStack.rbegin(), |
| 1493 | rend = activeConstructStack.rend(); |
| 1494 | it != rend; ++it) { |
| 1495 | if (&it->eval == activeAncestor) |
| 1496 | break; |
| 1497 | if (it->stmtCtx.hasCode()) |
| 1498 | return true; |
| 1499 | } |
| 1500 | return false; |
| 1501 | } |
| 1502 | |
| 1503 | /// Generate a branch to \p targetEval after generating on-exit code for |
| 1504 | /// any enclosing construct scopes that are exited by taking the branch. |
| 1505 | void |
| 1506 | genConstructExitBranch(const Fortran::lower::pft::Evaluation &targetEval) { |
| 1507 | Fortran::lower::pft::Evaluation *activeAncestor = |
| 1508 | getActiveAncestor(targetEval); |
| 1509 | for (auto it = activeConstructStack.rbegin(), |
| 1510 | rend = activeConstructStack.rend(); |
| 1511 | it != rend; ++it) { |
| 1512 | if (&it->eval == activeAncestor) |
| 1513 | break; |
| 1514 | it->stmtCtx.finalizeAndKeep(); |
| 1515 | } |
| 1516 | genBranch(targetEval.block); |
| 1517 | } |
| 1518 | |
Krzysztof Parzyszek | c1b5b7c | 2024-05-21 08:19:54 -0500 | [diff] [blame] | 1519 | /// A construct contains nested evaluations. Some of these evaluations |
| 1520 | /// may start a new basic block, others will add code to an existing |
| 1521 | /// block. |
| 1522 | /// Collect the list of nested evaluations that are last in their block, |
| 1523 | /// organize them into two sets: |
| 1524 | /// 1. Exiting evaluations: they may need a branch exiting from their |
| 1525 | /// parent construct, |
| 1526 | /// 2. Fall-through evaluations: they will continue to the following |
| 1527 | /// evaluation. They may still need a branch, but they do not exit |
| 1528 | /// the construct. They appear in cases where the following evaluation |
| 1529 | /// is a target of some branch. |
| 1530 | void collectFinalEvaluations( |
| 1531 | Fortran::lower::pft::Evaluation &construct, |
| 1532 | llvm::SmallVector<Fortran::lower::pft::Evaluation *> &exits, |
| 1533 | llvm::SmallVector<Fortran::lower::pft::Evaluation *> &fallThroughs) { |
| 1534 | Fortran::lower::pft::EvaluationList &nested = |
| 1535 | construct.getNestedEvaluations(); |
| 1536 | if (nested.empty()) |
| 1537 | return; |
| 1538 | |
| 1539 | Fortran::lower::pft::Evaluation *exit = construct.constructExit; |
| 1540 | Fortran::lower::pft::Evaluation *previous = &nested.front(); |
| 1541 | |
| 1542 | for (auto it = ++nested.begin(), end = nested.end(); it != end; |
| 1543 | previous = &*it++) { |
| 1544 | if (it->block == nullptr) |
| 1545 | continue; |
| 1546 | // "*it" starts a new block, check what to do with "previous" |
| 1547 | if (it->isIntermediateConstructStmt() && previous != exit) |
| 1548 | exits.push_back(previous); |
| 1549 | else if (previous->lexicalSuccessor && previous->lexicalSuccessor->block) |
| 1550 | fallThroughs.push_back(previous); |
| 1551 | } |
| 1552 | if (previous != exit) |
| 1553 | exits.push_back(previous); |
| 1554 | } |
| 1555 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1556 | /// Generate a SelectOp or branch sequence that compares \p selector against |
| 1557 | /// values in \p valueList and targets corresponding labels in \p labelList. |
| 1558 | /// If no value matches the selector, branch to \p defaultEval. |
| 1559 | /// |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 1560 | /// Three cases require special processing. |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 1561 | /// |
| 1562 | /// An empty \p valueList indicates an ArithmeticIfStmt context that requires |
| 1563 | /// two comparisons against 0 or 0.0. The selector may have either INTEGER |
| 1564 | /// or REAL type. |
| 1565 | /// |
| 1566 | /// A nonpositive \p valuelist value indicates an IO statement context |
| 1567 | /// (0 for ERR, -1 for END, -2 for EOR). An ERR branch must be taken for |
| 1568 | /// any positive (IOSTAT) value. A missing (zero) label requires a branch |
| 1569 | /// to \p defaultEval for that value. |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1570 | /// |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 1571 | /// A non-null \p errorBlock indicates an AssignedGotoStmt context that |
| 1572 | /// must always branch to an explicit target. There is no valid defaultEval |
| 1573 | /// in this case. Generate a branch to \p errorBlock for an AssignedGotoStmt |
| 1574 | /// that violates this program requirement. |
| 1575 | /// |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1576 | /// If this is not an ArithmeticIfStmt and no targets have exit code, |
| 1577 | /// generate a SelectOp. Otherwise, for each target, if it has exit code, |
| 1578 | /// branch to a new block, insert exit code, and then branch to the target. |
| 1579 | /// Otherwise, branch directly to the target. |
| 1580 | void genMultiwayBranch(mlir::Value selector, |
| 1581 | llvm::SmallVector<int64_t> valueList, |
| 1582 | llvm::SmallVector<Fortran::parser::Label> labelList, |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 1583 | const Fortran::lower::pft::Evaluation &defaultEval, |
| 1584 | mlir::Block *errorBlock = nullptr) { |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1585 | bool inArithmeticIfContext = valueList.empty(); |
| 1586 | assert(((inArithmeticIfContext && labelList.size() == 2) || |
| 1587 | (valueList.size() && labelList.size() == valueList.size())) && |
| 1588 | "mismatched multiway branch targets"); |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 1589 | mlir::Block *defaultBlock = errorBlock ? errorBlock : defaultEval.block; |
| 1590 | bool defaultHasExitCode = !errorBlock && hasExitCode(defaultEval); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1591 | bool hasAnyExitCode = defaultHasExitCode; |
| 1592 | if (!hasAnyExitCode) |
| 1593 | for (auto label : labelList) |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 1594 | if (label && hasExitCode(evalOfLabel(label))) { |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1595 | hasAnyExitCode = true; |
| 1596 | break; |
| 1597 | } |
| 1598 | mlir::Location loc = toLocation(); |
| 1599 | size_t branchCount = labelList.size(); |
| 1600 | if (!inArithmeticIfContext && !hasAnyExitCode && |
| 1601 | !getEval().forceAsUnstructured()) { // from -no-structured-fir option |
| 1602 | // Generate a SelectOp. |
| 1603 | llvm::SmallVector<mlir::Block *> blockList; |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 1604 | for (auto label : labelList) { |
| 1605 | mlir::Block *block = |
| 1606 | label ? evalOfLabel(label).block : defaultEval.block; |
| 1607 | assert(block && "missing multiway branch block"); |
| 1608 | blockList.push_back(block); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1609 | } |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 1610 | blockList.push_back(defaultBlock); |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 1611 | if (valueList[branchCount - 1] == 0) // Swap IO ERR and default blocks. |
| 1612 | std::swap(blockList[branchCount - 1], blockList[branchCount]); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1613 | builder->create<fir::SelectOp>(loc, selector, valueList, blockList); |
| 1614 | return; |
| 1615 | } |
| 1616 | mlir::Type selectorType = selector.getType(); |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 1617 | bool realSelector = mlir::isa<mlir::FloatType>(selectorType); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1618 | assert((inArithmeticIfContext || !realSelector) && "invalid selector type"); |
| 1619 | mlir::Value zero; |
| 1620 | if (inArithmeticIfContext) |
| 1621 | zero = |
| 1622 | realSelector |
| 1623 | ? builder->create<mlir::arith::ConstantOp>( |
| 1624 | loc, selectorType, builder->getFloatAttr(selectorType, 0.0)) |
| 1625 | : builder->createIntegerConstant(loc, selectorType, 0); |
| 1626 | for (auto label : llvm::enumerate(labelList)) { |
| 1627 | mlir::Value cond; |
| 1628 | if (realSelector) // inArithmeticIfContext |
| 1629 | cond = builder->create<mlir::arith::CmpFOp>( |
| 1630 | loc, |
| 1631 | label.index() == 0 ? mlir::arith::CmpFPredicate::OLT |
| 1632 | : mlir::arith::CmpFPredicate::OGT, |
| 1633 | selector, zero); |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 1634 | else if (inArithmeticIfContext) // INTEGER selector |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1635 | cond = builder->create<mlir::arith::CmpIOp>( |
| 1636 | loc, |
| 1637 | label.index() == 0 ? mlir::arith::CmpIPredicate::slt |
| 1638 | : mlir::arith::CmpIPredicate::sgt, |
| 1639 | selector, zero); |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 1640 | else // A value of 0 is an IO ERR branch: invert comparison. |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1641 | cond = builder->create<mlir::arith::CmpIOp>( |
| 1642 | loc, |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 1643 | valueList[label.index()] == 0 ? mlir::arith::CmpIPredicate::ne |
| 1644 | : mlir::arith::CmpIPredicate::eq, |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1645 | selector, |
| 1646 | builder->createIntegerConstant(loc, selectorType, |
| 1647 | valueList[label.index()])); |
| 1648 | // Branch to a new block with exit code and then to the target, or branch |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 1649 | // directly to the target. defaultBlock is the "else" target. |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1650 | bool lastBranch = label.index() == branchCount - 1; |
| 1651 | mlir::Block *nextBlock = |
| 1652 | lastBranch && !defaultHasExitCode |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 1653 | ? defaultBlock |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1654 | : builder->getBlock()->splitBlock(builder->getInsertionPoint()); |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 1655 | const Fortran::lower::pft::Evaluation &targetEval = |
| 1656 | label.value() ? evalOfLabel(label.value()) : defaultEval; |
| 1657 | if (hasExitCode(targetEval)) { |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1658 | mlir::Block *jumpBlock = |
| 1659 | builder->getBlock()->splitBlock(builder->getInsertionPoint()); |
| 1660 | genConditionalBranch(cond, jumpBlock, nextBlock); |
| 1661 | startBlock(jumpBlock); |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 1662 | genConstructExitBranch(targetEval); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1663 | } else { |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 1664 | genConditionalBranch(cond, targetEval.block, nextBlock); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1665 | } |
| 1666 | if (!lastBranch) { |
| 1667 | startBlock(nextBlock); |
| 1668 | } else if (defaultHasExitCode) { |
| 1669 | startBlock(nextBlock); |
| 1670 | genConstructExitBranch(defaultEval); |
| 1671 | } |
| 1672 | } |
| 1673 | } |
| 1674 | |
| 1675 | void pushActiveConstruct(Fortran::lower::pft::Evaluation &eval, |
| 1676 | Fortran::lower::StatementContext &stmtCtx) { |
| 1677 | activeConstructStack.push_back(ConstructContext{eval, stmtCtx}); |
| 1678 | eval.activeConstruct = true; |
| 1679 | } |
| 1680 | void popActiveConstruct() { |
| 1681 | assert(!activeConstructStack.empty() && "invalid active construct stack"); |
| 1682 | activeConstructStack.back().eval.activeConstruct = false; |
jeanPerier | d1aa9ba | 2024-06-03 17:20:07 +0200 | [diff] [blame] | 1683 | if (activeConstructStack.back().pushedScope) |
| 1684 | localSymbols.popScope(); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1685 | activeConstructStack.pop_back(); |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 1686 | } |
| 1687 | |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1688 | //===--------------------------------------------------------------------===// |
| 1689 | // Termination of symbolically referenced execution units |
| 1690 | //===--------------------------------------------------------------------===// |
| 1691 | |
khaki3 | ff7fca7 | 2024-11-15 08:44:42 -0800 | [diff] [blame] | 1692 | /// Exit of a routine |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1693 | /// |
khaki3 | ff7fca7 | 2024-11-15 08:44:42 -0800 | [diff] [blame] | 1694 | /// Generate the cleanup block before the routine exits |
| 1695 | void genExitRoutine(bool earlyReturn, mlir::ValueRange retval = {}) { |
| 1696 | if (blockIsUnterminated()) { |
| 1697 | bridge.openAccCtx().finalizeAndKeep(); |
| 1698 | bridge.fctCtx().finalizeAndKeep(); |
| 1699 | builder->create<mlir::func::ReturnOp>(toLocation(), retval); |
| 1700 | } |
| 1701 | if (!earlyReturn) { |
| 1702 | bridge.openAccCtx().pop(); |
| 1703 | bridge.fctCtx().pop(); |
| 1704 | } |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1705 | } |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 1706 | |
Valentin Clement | ad40cc1 | 2022-02-14 21:31:46 +0100 | [diff] [blame] | 1707 | /// END of procedure-like constructs |
| 1708 | /// |
| 1709 | /// Generate the cleanup block before the procedure exits |
| 1710 | void genReturnSymbol(const Fortran::semantics::Symbol &functionSymbol) { |
| 1711 | const Fortran::semantics::Symbol &resultSym = |
| 1712 | functionSymbol.get<Fortran::semantics::SubprogramDetails>().result(); |
| 1713 | Fortran::lower::SymbolBox resultSymBox = lookupSymbol(resultSym); |
| 1714 | mlir::Location loc = toLocation(); |
| 1715 | if (!resultSymBox) { |
Valentin Clement | 39377d5 | 2022-07-01 08:29:19 +0200 | [diff] [blame] | 1716 | mlir::emitError(loc, "internal error when processing function return"); |
Valentin Clement | ad40cc1 | 2022-02-14 21:31:46 +0100 | [diff] [blame] | 1717 | return; |
| 1718 | } |
| 1719 | mlir::Value resultVal = resultSymBox.match( |
| 1720 | [&](const fir::CharBoxValue &x) -> mlir::Value { |
Valentin Clement | de3efd1 | 2022-09-24 08:58:50 +0200 | [diff] [blame] | 1721 | if (Fortran::semantics::IsBindCProcedure(functionSymbol)) |
| 1722 | return builder->create<fir::LoadOp>(loc, x.getBuffer()); |
Valentin Clement | 37e84d9 | 2022-02-25 18:21:44 +0100 | [diff] [blame] | 1723 | return fir::factory::CharacterExprHelper{*builder, loc} |
| 1724 | .createEmboxChar(x.getBuffer(), x.getLen()); |
Valentin Clement | ad40cc1 | 2022-02-14 21:31:46 +0100 | [diff] [blame] | 1725 | }, |
Slava Zakharin | de8939f | 2023-09-05 10:26:16 -0700 | [diff] [blame] | 1726 | [&](const fir::MutableBoxValue &x) -> mlir::Value { |
| 1727 | mlir::Value resultRef = resultSymBox.getAddr(); |
| 1728 | mlir::Value load = builder->create<fir::LoadOp>(loc, resultRef); |
| 1729 | unsigned rank = x.rank(); |
| 1730 | if (x.isAllocatable() && rank > 0) { |
| 1731 | // ALLOCATABLE array result must have default lower bounds. |
| 1732 | // At the call site the result box of a function reference |
| 1733 | // might be considered having default lower bounds, but |
| 1734 | // the runtime box should probably comply with this assumption |
| 1735 | // as well. If the result box has proper lbounds in runtime, |
| 1736 | // this may improve the debugging experience of Fortran apps. |
| 1737 | // We may consider removing this, if the overhead of setting |
| 1738 | // default lower bounds is too big. |
| 1739 | mlir::Value one = |
| 1740 | builder->createIntegerConstant(loc, builder->getIndexType(), 1); |
| 1741 | llvm::SmallVector<mlir::Value> lbounds{rank, one}; |
| 1742 | auto shiftTy = fir::ShiftType::get(builder->getContext(), rank); |
| 1743 | mlir::Value shiftOp = |
| 1744 | builder->create<fir::ShiftOp>(loc, shiftTy, lbounds); |
| 1745 | load = builder->create<fir::ReboxOp>( |
| 1746 | loc, load.getType(), load, shiftOp, /*slice=*/mlir::Value{}); |
| 1747 | } |
| 1748 | return load; |
| 1749 | }, |
Valentin Clement | ad40cc1 | 2022-02-14 21:31:46 +0100 | [diff] [blame] | 1750 | [&](const auto &) -> mlir::Value { |
| 1751 | mlir::Value resultRef = resultSymBox.getAddr(); |
| 1752 | mlir::Type resultType = genType(resultSym); |
| 1753 | mlir::Type resultRefType = builder->getRefType(resultType); |
| 1754 | // A function with multiple entry points returning different types |
| 1755 | // tags all result variables with one of the largest types to allow |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1756 | // them to share the same storage. Convert this to the actual type. |
Valentin Clement | ad40cc1 | 2022-02-14 21:31:46 +0100 | [diff] [blame] | 1757 | if (resultRef.getType() != resultRefType) |
Valentin Clement | 76134f4 | 2022-03-15 22:01:34 +0100 | [diff] [blame] | 1758 | resultRef = builder->createConvert(loc, resultRefType, resultRef); |
Valentin Clement | ad40cc1 | 2022-02-14 21:31:46 +0100 | [diff] [blame] | 1759 | return builder->create<fir::LoadOp>(loc, resultRef); |
| 1760 | }); |
khaki3 | ff7fca7 | 2024-11-15 08:44:42 -0800 | [diff] [blame] | 1761 | genExitRoutine(false, resultVal); |
Valentin Clement | ad40cc1 | 2022-02-14 21:31:46 +0100 | [diff] [blame] | 1762 | } |
| 1763 | |
Valentin Clement | 76134f4 | 2022-03-15 22:01:34 +0100 | [diff] [blame] | 1764 | /// Get the return value of a call to \p symbol, which is a subroutine entry |
| 1765 | /// point that has alternative return specifiers. |
| 1766 | const mlir::Value |
| 1767 | getAltReturnResult(const Fortran::semantics::Symbol &symbol) { |
| 1768 | assert(Fortran::semantics::HasAlternateReturns(symbol) && |
| 1769 | "subroutine does not have alternate returns"); |
| 1770 | return getSymbolAddress(symbol); |
| 1771 | } |
| 1772 | |
Valentin Clement | 8927530 | 2022-02-01 15:26:47 +0100 | [diff] [blame] | 1773 | void genFIRProcedureExit(Fortran::lower::pft::FunctionLikeUnit &funit, |
| 1774 | const Fortran::semantics::Symbol &symbol) { |
Valentin Clement | 85b89ed | 2022-02-10 18:35:16 +0100 | [diff] [blame] | 1775 | if (mlir::Block *finalBlock = funit.finalBlock) { |
| 1776 | // The current block must end with a terminator. |
| 1777 | if (blockIsUnterminated()) |
| 1778 | builder->create<mlir::cf::BranchOp>(toLocation(), finalBlock); |
| 1779 | // Set insertion point to final block. |
| 1780 | builder->setInsertionPoint(finalBlock, finalBlock->end()); |
| 1781 | } |
Valentin Clement | 8927530 | 2022-02-01 15:26:47 +0100 | [diff] [blame] | 1782 | if (Fortran::semantics::IsFunction(symbol)) { |
Valentin Clement | ad40cc1 | 2022-02-14 21:31:46 +0100 | [diff] [blame] | 1783 | genReturnSymbol(symbol); |
Valentin Clement | 76134f4 | 2022-03-15 22:01:34 +0100 | [diff] [blame] | 1784 | } else if (Fortran::semantics::HasAlternateReturns(symbol)) { |
| 1785 | mlir::Value retval = builder->create<fir::LoadOp>( |
| 1786 | toLocation(), getAltReturnResult(symbol)); |
khaki3 | ff7fca7 | 2024-11-15 08:44:42 -0800 | [diff] [blame] | 1787 | genExitRoutine(false, retval); |
Valentin Clement | 8927530 | 2022-02-01 15:26:47 +0100 | [diff] [blame] | 1788 | } else { |
khaki3 | ff7fca7 | 2024-11-15 08:44:42 -0800 | [diff] [blame] | 1789 | genExitRoutine(false); |
Valentin Clement | 8927530 | 2022-02-01 15:26:47 +0100 | [diff] [blame] | 1790 | } |
| 1791 | } |
| 1792 | |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 1793 | // |
| 1794 | // Statements that have control-flow semantics |
| 1795 | // |
| 1796 | |
| 1797 | /// Generate an If[Then]Stmt condition or its negation. |
| 1798 | template <typename A> |
| 1799 | mlir::Value genIfCondition(const A *stmt, bool negate = false) { |
| 1800 | mlir::Location loc = toLocation(); |
| 1801 | Fortran::lower::StatementContext stmtCtx; |
| 1802 | mlir::Value condExpr = createFIRExpr( |
| 1803 | loc, |
| 1804 | Fortran::semantics::GetExpr( |
| 1805 | std::get<Fortran::parser::ScalarLogicalExpr>(stmt->t)), |
| 1806 | stmtCtx); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1807 | stmtCtx.finalizeAndReset(); |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 1808 | mlir::Value cond = |
| 1809 | builder->createConvert(loc, builder->getI1Type(), condExpr); |
| 1810 | if (negate) |
| 1811 | cond = builder->create<mlir::arith::XOrIOp>( |
| 1812 | loc, cond, builder->createIntegerConstant(loc, cond.getType(), 1)); |
| 1813 | return cond; |
| 1814 | } |
| 1815 | |
River Riddle | 58ceae9 | 2022-04-18 11:53:47 -0700 | [diff] [blame] | 1816 | mlir::func::FuncOp getFunc(llvm::StringRef name, mlir::FunctionType ty) { |
| 1817 | if (mlir::func::FuncOp func = builder->getNamedFunction(name)) { |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 1818 | assert(func.getFunctionType() == ty); |
| 1819 | return func; |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 1820 | } |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 1821 | return builder->createFunction(toLocation(), name, ty); |
Valentin Clement | e641c29 | 2022-02-17 18:23:22 +0100 | [diff] [blame] | 1822 | } |
| 1823 | |
Valentin Clement | d0b70a0 | 2022-02-23 19:48:07 +0100 | [diff] [blame] | 1824 | /// Lowering of CALL statement |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 1825 | void genFIR(const Fortran::parser::CallStmt &stmt) { |
Valentin Clement | d0b70a0 | 2022-02-23 19:48:07 +0100 | [diff] [blame] | 1826 | Fortran::lower::StatementContext stmtCtx; |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 1827 | Fortran::lower::pft::Evaluation &eval = getEval(); |
Peter Klausler | 4ad7279 | 2023-05-06 15:03:39 -0700 | [diff] [blame] | 1828 | setCurrentPosition(stmt.source); |
Valentin Clement | d0b70a0 | 2022-02-23 19:48:07 +0100 | [diff] [blame] | 1829 | assert(stmt.typedCall && "Call was not analyzed"); |
Jean Perier | e78e4a1 | 2022-12-01 11:09:35 +0100 | [diff] [blame] | 1830 | mlir::Value res{}; |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 1831 | if (lowerToHighLevelFIR()) { |
Kazu Hirata | 91682b2 | 2023-01-14 14:06:18 -0800 | [diff] [blame] | 1832 | std::optional<mlir::Type> resultType; |
Jean Perier | e78e4a1 | 2022-12-01 11:09:35 +0100 | [diff] [blame] | 1833 | if (stmt.typedCall->hasAlternateReturns()) |
| 1834 | resultType = builder->getIndexType(); |
| 1835 | auto hlfirRes = Fortran::lower::convertCallToHLFIR( |
| 1836 | toLocation(), *this, *stmt.typedCall, resultType, localSymbols, |
| 1837 | stmtCtx); |
| 1838 | if (hlfirRes) |
| 1839 | res = *hlfirRes; |
| 1840 | } else { |
| 1841 | // Call statement lowering shares code with function call lowering. |
| 1842 | res = Fortran::lower::createSubroutineCall( |
| 1843 | *this, *stmt.typedCall, explicitIterSpace, implicitIterSpace, |
| 1844 | localSymbols, stmtCtx, /*isUserDefAssignment=*/false); |
| 1845 | } |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1846 | stmtCtx.finalizeAndReset(); |
Valentin Clement | d0b70a0 | 2022-02-23 19:48:07 +0100 | [diff] [blame] | 1847 | if (!res) |
| 1848 | return; // "Normal" subroutine call. |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 1849 | // Call with alternate return specifiers. |
| 1850 | // The call returns an index that selects an alternate return branch target. |
| 1851 | llvm::SmallVector<int64_t> indexList; |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1852 | llvm::SmallVector<Fortran::parser::Label> labelList; |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 1853 | int64_t index = 0; |
| 1854 | for (const Fortran::parser::ActualArgSpec &arg : |
Peter Klausler | 4ad7279 | 2023-05-06 15:03:39 -0700 | [diff] [blame] | 1855 | std::get<std::list<Fortran::parser::ActualArgSpec>>(stmt.call.t)) { |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 1856 | const auto &actual = std::get<Fortran::parser::ActualArg>(arg.t); |
| 1857 | if (const auto *altReturn = |
| 1858 | std::get_if<Fortran::parser::AltReturnSpec>(&actual.u)) { |
| 1859 | indexList.push_back(++index); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1860 | labelList.push_back(altReturn->v); |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 1861 | } |
| 1862 | } |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1863 | genMultiwayBranch(res, indexList, labelList, eval.nonNopSuccessor()); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 1864 | } |
| 1865 | |
| 1866 | void genFIR(const Fortran::parser::ComputedGotoStmt &stmt) { |
Valentin Clement | 78a127a | 2022-03-08 20:17:48 +0100 | [diff] [blame] | 1867 | Fortran::lower::StatementContext stmtCtx; |
| 1868 | Fortran::lower::pft::Evaluation &eval = getEval(); |
| 1869 | mlir::Value selectExpr = |
| 1870 | createFIRExpr(toLocation(), |
| 1871 | Fortran::semantics::GetExpr( |
| 1872 | std::get<Fortran::parser::ScalarIntExpr>(stmt.t)), |
| 1873 | stmtCtx); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1874 | stmtCtx.finalizeAndReset(); |
Valentin Clement | 78a127a | 2022-03-08 20:17:48 +0100 | [diff] [blame] | 1875 | llvm::SmallVector<int64_t> indexList; |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1876 | llvm::SmallVector<Fortran::parser::Label> labelList; |
Valentin Clement | 78a127a | 2022-03-08 20:17:48 +0100 | [diff] [blame] | 1877 | int64_t index = 0; |
| 1878 | for (Fortran::parser::Label label : |
| 1879 | std::get<std::list<Fortran::parser::Label>>(stmt.t)) { |
| 1880 | indexList.push_back(++index); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1881 | labelList.push_back(label); |
Valentin Clement | 78a127a | 2022-03-08 20:17:48 +0100 | [diff] [blame] | 1882 | } |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1883 | genMultiwayBranch(selectExpr, indexList, labelList, eval.nonNopSuccessor()); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 1884 | } |
| 1885 | |
| 1886 | void genFIR(const Fortran::parser::ArithmeticIfStmt &stmt) { |
Valentin Clement | 78a127a | 2022-03-08 20:17:48 +0100 | [diff] [blame] | 1887 | Fortran::lower::StatementContext stmtCtx; |
Valentin Clement | 78a127a | 2022-03-08 20:17:48 +0100 | [diff] [blame] | 1888 | mlir::Value expr = createFIRExpr( |
| 1889 | toLocation(), |
| 1890 | Fortran::semantics::GetExpr(std::get<Fortran::parser::Expr>(stmt.t)), |
| 1891 | stmtCtx); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1892 | stmtCtx.finalizeAndReset(); |
| 1893 | // Raise an exception if REAL expr is a NaN. |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 1894 | if (mlir::isa<mlir::FloatType>(expr.getType())) |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1895 | expr = builder->create<mlir::arith::AddFOp>(toLocation(), expr, expr); |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 1896 | // An empty valueList indicates to genMultiwayBranch that the branch is |
| 1897 | // an ArithmeticIfStmt that has two branches on value 0 or 0.0. |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1898 | llvm::SmallVector<int64_t> valueList; |
| 1899 | llvm::SmallVector<Fortran::parser::Label> labelList; |
| 1900 | labelList.push_back(std::get<1>(stmt.t)); |
| 1901 | labelList.push_back(std::get<3>(stmt.t)); |
| 1902 | const Fortran::lower::pft::LabelEvalMap &labelEvaluationMap = |
| 1903 | getEval().getOwningProcedure()->labelEvaluationMap; |
| 1904 | const auto iter = labelEvaluationMap.find(std::get<2>(stmt.t)); |
| 1905 | assert(iter != labelEvaluationMap.end() && "label missing from map"); |
| 1906 | genMultiwayBranch(expr, valueList, labelList, *iter->second); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 1907 | } |
| 1908 | |
| 1909 | void genFIR(const Fortran::parser::AssignedGotoStmt &stmt) { |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 1910 | // See Fortran 90 Clause 8.2.4. |
| 1911 | // Relax the requirement that the GOTO variable must have a value in the |
| 1912 | // label list when a list is present, and allow a branch to any non-format |
| 1913 | // target that has an ASSIGN statement for the variable. |
Valentin Clement | 78a127a | 2022-03-08 20:17:48 +0100 | [diff] [blame] | 1914 | mlir::Location loc = toLocation(); |
| 1915 | Fortran::lower::pft::Evaluation &eval = getEval(); |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 1916 | Fortran::lower::pft::FunctionLikeUnit &owningProc = |
| 1917 | *eval.getOwningProcedure(); |
Valentin Clement | 78a127a | 2022-03-08 20:17:48 +0100 | [diff] [blame] | 1918 | const Fortran::lower::pft::SymbolLabelMap &symbolLabelMap = |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 1919 | owningProc.assignSymbolLabelMap; |
| 1920 | const Fortran::lower::pft::LabelEvalMap &labelEvalMap = |
| 1921 | owningProc.labelEvaluationMap; |
Valentin Clement | 78a127a | 2022-03-08 20:17:48 +0100 | [diff] [blame] | 1922 | const Fortran::semantics::Symbol &symbol = |
| 1923 | *std::get<Fortran::parser::Name>(stmt.t).symbol; |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 1924 | auto labelSetIter = symbolLabelMap.find(symbol); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 1925 | llvm::SmallVector<int64_t> valueList; |
| 1926 | llvm::SmallVector<Fortran::parser::Label> labelList; |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 1927 | if (labelSetIter != symbolLabelMap.end()) { |
| 1928 | for (auto &label : labelSetIter->second) { |
| 1929 | const auto evalIter = labelEvalMap.find(label); |
| 1930 | assert(evalIter != labelEvalMap.end() && "assigned goto label missing"); |
| 1931 | if (evalIter->second->block) { // non-format statement |
| 1932 | valueList.push_back(label); // label as an integer |
| 1933 | labelList.push_back(label); |
| 1934 | } |
Valentin Clement | 78a127a | 2022-03-08 20:17:48 +0100 | [diff] [blame] | 1935 | } |
| 1936 | } |
V Donaldson | fd922e6 | 2023-04-05 11:13:36 -0700 | [diff] [blame] | 1937 | if (!labelList.empty()) { |
| 1938 | auto selectExpr = |
| 1939 | builder->create<fir::LoadOp>(loc, getSymbolAddress(symbol)); |
| 1940 | // Add a default error target in case the goto is nonconforming. |
| 1941 | mlir::Block *errorBlock = |
| 1942 | builder->getBlock()->splitBlock(builder->getInsertionPoint()); |
| 1943 | genMultiwayBranch(selectExpr, valueList, labelList, |
| 1944 | eval.nonNopSuccessor(), errorBlock); |
| 1945 | startBlock(errorBlock); |
| 1946 | } |
| 1947 | fir::runtime::genReportFatalUserError( |
| 1948 | *builder, loc, |
| 1949 | "Assigned GOTO variable '" + symbol.name().ToString() + |
| 1950 | "' does not have a valid target label value"); |
| 1951 | builder->create<fir::UnreachableOp>(loc); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 1952 | } |
| 1953 | |
khaki3 | f11e08f | 2024-06-10 08:41:05 -0700 | [diff] [blame] | 1954 | fir::ReduceOperationEnum |
| 1955 | getReduceOperationEnum(const Fortran::parser::ReductionOperator &rOpr) { |
| 1956 | switch (rOpr.v) { |
| 1957 | case Fortran::parser::ReductionOperator::Operator::Plus: |
| 1958 | return fir::ReduceOperationEnum::Add; |
| 1959 | case Fortran::parser::ReductionOperator::Operator::Multiply: |
| 1960 | return fir::ReduceOperationEnum::Multiply; |
| 1961 | case Fortran::parser::ReductionOperator::Operator::And: |
| 1962 | return fir::ReduceOperationEnum::AND; |
| 1963 | case Fortran::parser::ReductionOperator::Operator::Or: |
| 1964 | return fir::ReduceOperationEnum::OR; |
| 1965 | case Fortran::parser::ReductionOperator::Operator::Eqv: |
| 1966 | return fir::ReduceOperationEnum::EQV; |
| 1967 | case Fortran::parser::ReductionOperator::Operator::Neqv: |
| 1968 | return fir::ReduceOperationEnum::NEQV; |
| 1969 | case Fortran::parser::ReductionOperator::Operator::Max: |
| 1970 | return fir::ReduceOperationEnum::MAX; |
| 1971 | case Fortran::parser::ReductionOperator::Operator::Min: |
| 1972 | return fir::ReduceOperationEnum::MIN; |
| 1973 | case Fortran::parser::ReductionOperator::Operator::Iand: |
| 1974 | return fir::ReduceOperationEnum::IAND; |
| 1975 | case Fortran::parser::ReductionOperator::Operator::Ior: |
| 1976 | return fir::ReduceOperationEnum::IOR; |
| 1977 | case Fortran::parser::ReductionOperator::Operator::Ieor: |
| 1978 | return fir::ReduceOperationEnum::EIOR; |
| 1979 | } |
| 1980 | llvm_unreachable("illegal reduction operator"); |
| 1981 | } |
| 1982 | |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 1983 | /// Collect DO CONCURRENT or FORALL loop control information. |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 1984 | IncrementLoopNestInfo getConcurrentControl( |
| 1985 | const Fortran::parser::ConcurrentHeader &header, |
| 1986 | const std::list<Fortran::parser::LocalitySpec> &localityList = {}) { |
| 1987 | IncrementLoopNestInfo incrementLoopNestInfo; |
| 1988 | for (const Fortran::parser::ConcurrentControl &control : |
| 1989 | std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) |
| 1990 | incrementLoopNestInfo.emplace_back( |
| 1991 | *std::get<0>(control.t).symbol, std::get<1>(control.t), |
| 1992 | std::get<2>(control.t), std::get<3>(control.t), /*isUnordered=*/true); |
| 1993 | IncrementLoopInfo &info = incrementLoopNestInfo.back(); |
| 1994 | info.maskExpr = Fortran::semantics::GetExpr( |
| 1995 | std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>(header.t)); |
| 1996 | for (const Fortran::parser::LocalitySpec &x : localityList) { |
V Donaldson | 335b399 | 2023-08-07 13:29:17 -0700 | [diff] [blame] | 1997 | if (const auto *localList = |
| 1998 | std::get_if<Fortran::parser::LocalitySpec::Local>(&x.u)) |
| 1999 | for (const Fortran::parser::Name &x : localList->v) |
| 2000 | info.localSymList.push_back(x.symbol); |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 2001 | if (const auto *localInitList = |
| 2002 | std::get_if<Fortran::parser::LocalitySpec::LocalInit>(&x.u)) |
| 2003 | for (const Fortran::parser::Name &x : localInitList->v) |
| 2004 | info.localInitSymList.push_back(x.symbol); |
khaki3 | 85f4593 | 2024-06-17 09:21:30 -0700 | [diff] [blame] | 2005 | for (IncrementLoopInfo &info : incrementLoopNestInfo) { |
| 2006 | if (const auto *reduceList = |
| 2007 | std::get_if<Fortran::parser::LocalitySpec::Reduce>(&x.u)) { |
| 2008 | fir::ReduceOperationEnum reduce_operation = getReduceOperationEnum( |
| 2009 | std::get<Fortran::parser::ReductionOperator>(reduceList->t)); |
| 2010 | for (const Fortran::parser::Name &x : |
| 2011 | std::get<std::list<Fortran::parser::Name>>(reduceList->t)) { |
| 2012 | info.reduceSymList.push_back( |
| 2013 | std::make_pair(reduce_operation, x.symbol)); |
| 2014 | } |
khaki3 | f11e08f | 2024-06-10 08:41:05 -0700 | [diff] [blame] | 2015 | } |
| 2016 | } |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 2017 | if (const auto *sharedList = |
| 2018 | std::get_if<Fortran::parser::LocalitySpec::Shared>(&x.u)) |
| 2019 | for (const Fortran::parser::Name &x : sharedList->v) |
| 2020 | info.sharedSymList.push_back(x.symbol); |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 2021 | } |
| 2022 | return incrementLoopNestInfo; |
| 2023 | } |
| 2024 | |
V Donaldson | 335b399 | 2023-08-07 13:29:17 -0700 | [diff] [blame] | 2025 | /// Create DO CONCURRENT construct symbol bindings and generate LOCAL_INIT |
| 2026 | /// assignments. |
| 2027 | void handleLocalitySpecs(const IncrementLoopInfo &info) { |
| 2028 | Fortran::semantics::SemanticsContext &semanticsContext = |
| 2029 | bridge.getSemanticsContext(); |
| 2030 | for (const Fortran::semantics::Symbol *sym : info.localSymList) |
jeanPerier | ff78cd5 | 2024-12-05 14:09:48 +0100 | [diff] [blame] | 2031 | createHostAssociateVarClone(*sym, /*skipDefaultInit=*/false); |
V Donaldson | 335b399 | 2023-08-07 13:29:17 -0700 | [diff] [blame] | 2032 | for (const Fortran::semantics::Symbol *sym : info.localInitSymList) { |
jeanPerier | ff78cd5 | 2024-12-05 14:09:48 +0100 | [diff] [blame] | 2033 | createHostAssociateVarClone(*sym, /*skipDefaultInit=*/true); |
V Donaldson | 335b399 | 2023-08-07 13:29:17 -0700 | [diff] [blame] | 2034 | const auto *hostDetails = |
| 2035 | sym->detailsIf<Fortran::semantics::HostAssocDetails>(); |
| 2036 | assert(hostDetails && "missing locality spec host symbol"); |
| 2037 | const Fortran::semantics::Symbol *hostSym = &hostDetails->symbol(); |
| 2038 | Fortran::evaluate::ExpressionAnalyzer ea{semanticsContext}; |
| 2039 | Fortran::evaluate::Assignment assign{ |
| 2040 | ea.Designate(Fortran::evaluate::DataRef{*sym}).value(), |
| 2041 | ea.Designate(Fortran::evaluate::DataRef{*hostSym}).value()}; |
| 2042 | if (Fortran::semantics::IsPointer(*sym)) |
| 2043 | assign.u = Fortran::evaluate::Assignment::BoundsSpec{}; |
| 2044 | genAssignment(assign); |
| 2045 | } |
| 2046 | for (const Fortran::semantics::Symbol *sym : info.sharedSymList) { |
| 2047 | const auto *hostDetails = |
| 2048 | sym->detailsIf<Fortran::semantics::HostAssocDetails>(); |
| 2049 | copySymbolBinding(hostDetails->symbol(), *sym); |
| 2050 | } |
jeanPerier | ff78cd5 | 2024-12-05 14:09:48 +0100 | [diff] [blame] | 2051 | // Note that allocatable, types with ultimate components, and type |
| 2052 | // requiring finalization are forbidden in LOCAL/LOCAL_INIT (F2023 C1130), |
| 2053 | // so no clean-up needs to be generated for these entities. |
V Donaldson | 335b399 | 2023-08-07 13:29:17 -0700 | [diff] [blame] | 2054 | } |
| 2055 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2056 | /// Generate FIR for a DO construct. There are six variants: |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 2057 | /// - unstructured infinite and while loops |
| 2058 | /// - structured and unstructured increment loops |
| 2059 | /// - structured and unstructured concurrent loops |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2060 | void genFIR(const Fortran::parser::DoConstruct &doConstruct) { |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2061 | setCurrentPositionAt(doConstruct); |
| 2062 | // Collect loop nest information. |
| 2063 | // Generate begin loop code directly for infinite and while loops. |
| 2064 | Fortran::lower::pft::Evaluation &eval = getEval(); |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 2065 | bool unstructuredContext = eval.lowerAsUnstructured(); |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2066 | Fortran::lower::pft::Evaluation &doStmtEval = |
| 2067 | eval.getFirstNestedEvaluation(); |
| 2068 | auto *doStmt = doStmtEval.getIf<Fortran::parser::NonLabelDoStmt>(); |
| 2069 | const auto &loopControl = |
| 2070 | std::get<std::optional<Fortran::parser::LoopControl>>(doStmt->t); |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 2071 | mlir::Block *preheaderBlock = doStmtEval.block; |
| 2072 | mlir::Block *beginBlock = |
| 2073 | preheaderBlock ? preheaderBlock : builder->getBlock(); |
| 2074 | auto createNextBeginBlock = [&]() { |
| 2075 | // Step beginBlock through unstructured preheader, header, and mask |
| 2076 | // blocks, created in outermost to innermost order. |
| 2077 | return beginBlock = beginBlock->splitBlock(beginBlock->end()); |
| 2078 | }; |
| 2079 | mlir::Block *headerBlock = |
| 2080 | unstructuredContext ? createNextBeginBlock() : nullptr; |
| 2081 | mlir::Block *bodyBlock = doStmtEval.lexicalSuccessor->block; |
| 2082 | mlir::Block *exitBlock = doStmtEval.parentConstruct->constructExit->block; |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2083 | IncrementLoopNestInfo incrementLoopNestInfo; |
Diana Picus | 11fb1aa | 2022-05-25 12:51:10 +0000 | [diff] [blame] | 2084 | const Fortran::parser::ScalarLogicalExpr *whileCondition = nullptr; |
Kiran Chandramohan | 8c349d7 | 2022-06-01 11:48:20 +0000 | [diff] [blame] | 2085 | bool infiniteLoop = !loopControl.has_value(); |
| 2086 | if (infiniteLoop) { |
| 2087 | assert(unstructuredContext && "infinite loop must be unstructured"); |
| 2088 | startBlock(headerBlock); |
| 2089 | } else if ((whileCondition = |
| 2090 | std::get_if<Fortran::parser::ScalarLogicalExpr>( |
| 2091 | &loopControl->u))) { |
Diana Picus | 11fb1aa | 2022-05-25 12:51:10 +0000 | [diff] [blame] | 2092 | assert(unstructuredContext && "while loop must be unstructured"); |
| 2093 | maybeStartBlock(preheaderBlock); // no block or empty block |
| 2094 | startBlock(headerBlock); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2095 | genConditionalBranch(*whileCondition, bodyBlock, exitBlock); |
Diana Picus | 11fb1aa | 2022-05-25 12:51:10 +0000 | [diff] [blame] | 2096 | } else if (const auto *bounds = |
| 2097 | std::get_if<Fortran::parser::LoopControl::Bounds>( |
| 2098 | &loopControl->u)) { |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2099 | // Non-concurrent increment loop. |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 2100 | IncrementLoopInfo &info = incrementLoopNestInfo.emplace_back( |
| 2101 | *bounds->name.thing.symbol, bounds->lower, bounds->upper, |
| 2102 | bounds->step); |
| 2103 | if (unstructuredContext) { |
| 2104 | maybeStartBlock(preheaderBlock); |
Krzysztof Parzyszek | dd376f8 | 2023-12-04 08:27:57 -0600 | [diff] [blame] | 2105 | info.hasRealControl = info.loopVariableSym->GetType()->IsNumeric( |
Diana Picus | a159128 | 2022-05-31 10:55:56 +0000 | [diff] [blame] | 2106 | Fortran::common::TypeCategory::Real); |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 2107 | info.headerBlock = headerBlock; |
| 2108 | info.bodyBlock = bodyBlock; |
| 2109 | info.exitBlock = exitBlock; |
| 2110 | } |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2111 | } else { |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 2112 | const auto *concurrent = |
| 2113 | std::get_if<Fortran::parser::LoopControl::Concurrent>( |
| 2114 | &loopControl->u); |
| 2115 | assert(concurrent && "invalid DO loop variant"); |
| 2116 | incrementLoopNestInfo = getConcurrentControl( |
| 2117 | std::get<Fortran::parser::ConcurrentHeader>(concurrent->t), |
| 2118 | std::get<std::list<Fortran::parser::LocalitySpec>>(concurrent->t)); |
| 2119 | if (unstructuredContext) { |
| 2120 | maybeStartBlock(preheaderBlock); |
| 2121 | for (IncrementLoopInfo &info : incrementLoopNestInfo) { |
| 2122 | // The original loop body provides the body and latch blocks of the |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2123 | // innermost dimension. The (first) body block of a non-innermost |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 2124 | // dimension is the preheader block of the immediately enclosed |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2125 | // dimension. The latch block of a non-innermost dimension is the |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 2126 | // exit block of the immediately enclosed dimension. |
| 2127 | auto createNextExitBlock = [&]() { |
| 2128 | // Create unstructured loop exit blocks, outermost to innermost. |
| 2129 | return exitBlock = insertBlock(exitBlock); |
| 2130 | }; |
| 2131 | bool isInnermost = &info == &incrementLoopNestInfo.back(); |
| 2132 | bool isOutermost = &info == &incrementLoopNestInfo.front(); |
| 2133 | info.headerBlock = isOutermost ? headerBlock : createNextBeginBlock(); |
| 2134 | info.bodyBlock = isInnermost ? bodyBlock : createNextBeginBlock(); |
| 2135 | info.exitBlock = isOutermost ? exitBlock : createNextExitBlock(); |
| 2136 | if (info.maskExpr) |
| 2137 | info.maskBlock = createNextBeginBlock(); |
| 2138 | } |
| 2139 | } |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2140 | } |
| 2141 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2142 | // Increment loop begin code. (Infinite/while code was already generated.) |
Kiran Chandramohan | 8c349d7 | 2022-06-01 11:48:20 +0000 | [diff] [blame] | 2143 | if (!infiniteLoop && !whileCondition) |
David Truby | c6b6e18 | 2024-06-14 14:10:41 +0100 | [diff] [blame] | 2144 | genFIRIncrementLoopBegin(incrementLoopNestInfo, doStmtEval.dirs); |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2145 | |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 2146 | // Loop body code. |
| 2147 | auto iter = eval.getNestedEvaluations().begin(); |
| 2148 | for (auto end = --eval.getNestedEvaluations().end(); iter != end; ++iter) |
| 2149 | genFIR(*iter, unstructuredContext); |
| 2150 | |
| 2151 | // An EndDoStmt in unstructured code may start a new block. |
| 2152 | Fortran::lower::pft::Evaluation &endDoEval = *iter; |
| 2153 | assert(endDoEval.getIf<Fortran::parser::EndDoStmt>() && "no enddo stmt"); |
| 2154 | if (unstructuredContext) |
| 2155 | maybeStartBlock(endDoEval.block); |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2156 | |
Kiran Chandramohan | 8c349d7 | 2022-06-01 11:48:20 +0000 | [diff] [blame] | 2157 | // Loop end code. |
| 2158 | if (infiniteLoop || whileCondition) |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2159 | genBranch(headerBlock); |
Diana Picus | 11fb1aa | 2022-05-25 12:51:10 +0000 | [diff] [blame] | 2160 | else |
| 2161 | genFIRIncrementLoopEnd(incrementLoopNestInfo); |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 2162 | |
| 2163 | // This call may generate a branch in some contexts. |
| 2164 | genFIR(endDoEval, unstructuredContext); |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2165 | } |
| 2166 | |
Leandro Lupori | 3dbb055 | 2023-09-21 15:59:35 +0200 | [diff] [blame] | 2167 | /// Generate FIR to evaluate loop control values (lower, upper and step). |
| 2168 | mlir::Value genControlValue(const Fortran::lower::SomeExpr *expr, |
| 2169 | const IncrementLoopInfo &info, |
| 2170 | bool *isConst = nullptr) { |
| 2171 | mlir::Location loc = toLocation(); |
| 2172 | mlir::Type controlType = info.isStructured() ? builder->getIndexType() |
| 2173 | : info.getLoopVariableType(); |
| 2174 | Fortran::lower::StatementContext stmtCtx; |
| 2175 | if (expr) { |
| 2176 | if (isConst) |
| 2177 | *isConst = Fortran::evaluate::IsConstantExpr(*expr); |
| 2178 | return builder->createConvert(loc, controlType, |
| 2179 | createFIRExpr(loc, expr, stmtCtx)); |
| 2180 | } |
| 2181 | |
| 2182 | if (isConst) |
| 2183 | *isConst = true; |
| 2184 | if (info.hasRealControl) |
| 2185 | return builder->createRealConstant(loc, controlType, 1u); |
| 2186 | return builder->createIntegerConstant(loc, controlType, 1); // step |
| 2187 | } |
| 2188 | |
Asher Mancinelli | 6b52fb2 | 2025-02-10 08:21:22 -0800 | [diff] [blame] | 2189 | // For unroll directives without a value, force full unrolling. |
| 2190 | // For unroll directives with a value, if the value is greater than 1, |
| 2191 | // force unrolling with the given factor. Otherwise, disable unrolling. |
| 2192 | mlir::LLVM::LoopUnrollAttr |
| 2193 | genLoopUnrollAttr(std::optional<std::uint64_t> directiveArg) { |
| 2194 | mlir::BoolAttr falseAttr = |
| 2195 | mlir::BoolAttr::get(builder->getContext(), false); |
| 2196 | mlir::BoolAttr trueAttr = mlir::BoolAttr::get(builder->getContext(), true); |
| 2197 | mlir::IntegerAttr countAttr; |
| 2198 | mlir::BoolAttr fullUnrollAttr; |
| 2199 | bool shouldUnroll = true; |
| 2200 | if (directiveArg.has_value()) { |
| 2201 | auto unrollingFactor = directiveArg.value(); |
| 2202 | if (unrollingFactor == 0 || unrollingFactor == 1) { |
| 2203 | shouldUnroll = false; |
| 2204 | } else { |
| 2205 | countAttr = |
| 2206 | builder->getIntegerAttr(builder->getI64Type(), unrollingFactor); |
| 2207 | } |
| 2208 | } else { |
| 2209 | fullUnrollAttr = trueAttr; |
| 2210 | } |
| 2211 | |
| 2212 | mlir::BoolAttr disableAttr = shouldUnroll ? falseAttr : trueAttr; |
| 2213 | return mlir::LLVM::LoopUnrollAttr::get( |
| 2214 | builder->getContext(), /*disable=*/disableAttr, /*count=*/countAttr, {}, |
| 2215 | /*full=*/fullUnrollAttr, {}, {}, {}); |
| 2216 | } |
| 2217 | |
Jean-Didier PAILLEUX | d6c6bde | 2025-02-19 16:00:09 +0100 | [diff] [blame] | 2218 | // Enabling unroll and jamming directive without a value. |
| 2219 | // For directives with a value, if the value is greater than 1, |
| 2220 | // force unrolling with the given factor. Otherwise, disable unrolling and |
| 2221 | // jamming. |
| 2222 | mlir::LLVM::LoopUnrollAndJamAttr |
| 2223 | genLoopUnrollAndJamAttr(std::optional<std::uint64_t> count) { |
| 2224 | mlir::BoolAttr falseAttr = |
| 2225 | mlir::BoolAttr::get(builder->getContext(), false); |
| 2226 | mlir::BoolAttr trueAttr = mlir::BoolAttr::get(builder->getContext(), true); |
| 2227 | mlir::IntegerAttr countAttr; |
| 2228 | bool shouldUnroll = true; |
| 2229 | if (count.has_value()) { |
| 2230 | auto unrollingFactor = count.value(); |
| 2231 | if (unrollingFactor == 0 || unrollingFactor == 1) { |
| 2232 | shouldUnroll = false; |
| 2233 | } else { |
| 2234 | countAttr = |
| 2235 | builder->getIntegerAttr(builder->getI64Type(), unrollingFactor); |
| 2236 | } |
| 2237 | } |
| 2238 | |
| 2239 | mlir::BoolAttr disableAttr = shouldUnroll ? falseAttr : trueAttr; |
| 2240 | return mlir::LLVM::LoopUnrollAndJamAttr::get( |
| 2241 | builder->getContext(), /*disable=*/disableAttr, /*count*/ countAttr, {}, |
| 2242 | {}, {}, {}, {}); |
| 2243 | } |
| 2244 | |
Jean-Didier PAILLEUX | e811cb0 | 2025-01-29 09:44:09 +0100 | [diff] [blame] | 2245 | void addLoopAnnotationAttr( |
| 2246 | IncrementLoopInfo &info, |
| 2247 | llvm::SmallVectorImpl<const Fortran::parser::CompilerDirective *> &dirs) { |
Jean-Didier PAILLEUX | e811cb0 | 2025-01-29 09:44:09 +0100 | [diff] [blame] | 2248 | mlir::LLVM::LoopVectorizeAttr va; |
| 2249 | mlir::LLVM::LoopUnrollAttr ua; |
Jean-Didier PAILLEUX | d6c6bde | 2025-02-19 16:00:09 +0100 | [diff] [blame] | 2250 | mlir::LLVM::LoopUnrollAndJamAttr uja; |
Jean-Didier PAILLEUX | e811cb0 | 2025-01-29 09:44:09 +0100 | [diff] [blame] | 2251 | bool has_attrs = false; |
| 2252 | for (const auto *dir : dirs) { |
| 2253 | Fortran::common::visit( |
| 2254 | Fortran::common::visitors{ |
| 2255 | [&](const Fortran::parser::CompilerDirective::VectorAlways &) { |
Asher Mancinelli | 6b52fb2 | 2025-02-10 08:21:22 -0800 | [diff] [blame] | 2256 | mlir::BoolAttr falseAttr = |
| 2257 | mlir::BoolAttr::get(builder->getContext(), false); |
Jean-Didier PAILLEUX | e811cb0 | 2025-01-29 09:44:09 +0100 | [diff] [blame] | 2258 | va = mlir::LLVM::LoopVectorizeAttr::get(builder->getContext(), |
Asher Mancinelli | 6b52fb2 | 2025-02-10 08:21:22 -0800 | [diff] [blame] | 2259 | /*disable=*/falseAttr, |
| 2260 | {}, {}, {}, {}, {}, {}); |
Jean-Didier PAILLEUX | e811cb0 | 2025-01-29 09:44:09 +0100 | [diff] [blame] | 2261 | has_attrs = true; |
| 2262 | }, |
| 2263 | [&](const Fortran::parser::CompilerDirective::Unroll &u) { |
Asher Mancinelli | 6b52fb2 | 2025-02-10 08:21:22 -0800 | [diff] [blame] | 2264 | ua = genLoopUnrollAttr(u.v); |
Jean-Didier PAILLEUX | e811cb0 | 2025-01-29 09:44:09 +0100 | [diff] [blame] | 2265 | has_attrs = true; |
| 2266 | }, |
Jean-Didier PAILLEUX | d6c6bde | 2025-02-19 16:00:09 +0100 | [diff] [blame] | 2267 | [&](const Fortran::parser::CompilerDirective::UnrollAndJam &u) { |
| 2268 | uja = genLoopUnrollAndJamAttr(u.v); |
| 2269 | has_attrs = true; |
| 2270 | }, |
Jean-Didier PAILLEUX | c309abd | 2025-04-02 14:30:01 +0200 | [diff] [blame] | 2271 | [&](const Fortran::parser::CompilerDirective::NoVector &u) { |
| 2272 | mlir::BoolAttr trueAttr = |
| 2273 | mlir::BoolAttr::get(builder->getContext(), true); |
| 2274 | va = mlir::LLVM::LoopVectorizeAttr::get(builder->getContext(), |
| 2275 | /*disable=*/trueAttr, |
| 2276 | {}, {}, {}, {}, {}, {}); |
| 2277 | has_attrs = true; |
| 2278 | }, |
| 2279 | [&](const Fortran::parser::CompilerDirective::NoUnroll &u) { |
| 2280 | ua = genLoopUnrollAttr(/*unrollingFactor=*/0); |
| 2281 | has_attrs = true; |
| 2282 | }, |
| 2283 | [&](const Fortran::parser::CompilerDirective::NoUnrollAndJam &u) { |
| 2284 | uja = genLoopUnrollAndJamAttr(/*unrollingFactor=*/0); |
| 2285 | has_attrs = true; |
| 2286 | }, |
| 2287 | |
Jean-Didier PAILLEUX | e811cb0 | 2025-01-29 09:44:09 +0100 | [diff] [blame] | 2288 | [&](const auto &) {}}, |
| 2289 | dir->u); |
| 2290 | } |
David Truby | c6b6e18 | 2024-06-14 14:10:41 +0100 | [diff] [blame] | 2291 | mlir::LLVM::LoopAnnotationAttr la = mlir::LLVM::LoopAnnotationAttr::get( |
Jean-Didier PAILLEUX | d6c6bde | 2025-02-19 16:00:09 +0100 | [diff] [blame] | 2292 | builder->getContext(), {}, /*vectorize=*/va, {}, /*unroll*/ ua, |
| 2293 | /*unroll_and_jam*/ uja, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}); |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2294 | if (has_attrs) |
| 2295 | info.doLoop.setLoopAnnotationAttr(la); |
David Truby | c6b6e18 | 2024-06-14 14:10:41 +0100 | [diff] [blame] | 2296 | } |
| 2297 | |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2298 | /// Generate FIR to begin a structured or unstructured increment loop nest. |
David Truby | c6b6e18 | 2024-06-14 14:10:41 +0100 | [diff] [blame] | 2299 | void genFIRIncrementLoopBegin( |
| 2300 | IncrementLoopNestInfo &incrementLoopNestInfo, |
| 2301 | llvm::SmallVectorImpl<const Fortran::parser::CompilerDirective *> &dirs) { |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2302 | assert(!incrementLoopNestInfo.empty() && "empty loop nest"); |
| 2303 | mlir::Location loc = toLocation(); |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2304 | mlir::Operation *boundsAndStepIP = nullptr; |
Yusuke MINATO | e573c6b | 2024-11-28 08:58:09 +0900 | [diff] [blame] | 2305 | mlir::arith::IntegerOverflowFlags iofBackup{}; |
Kareem Ergawy | 0698482 | 2024-10-31 09:19:18 +0100 | [diff] [blame] | 2306 | |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2307 | for (IncrementLoopInfo &info : incrementLoopNestInfo) { |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2308 | mlir::Value lowerValue; |
| 2309 | mlir::Value upperValue; |
| 2310 | mlir::Value stepValue; |
Kareem Ergawy | 0698482 | 2024-10-31 09:19:18 +0100 | [diff] [blame] | 2311 | |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2312 | { |
| 2313 | mlir::OpBuilder::InsertionGuard guard(*builder); |
| 2314 | |
| 2315 | // Set the IP before the first loop in the nest so that all nest bounds |
| 2316 | // and step values are created outside the nest. |
| 2317 | if (boundsAndStepIP) |
| 2318 | builder->setInsertionPointAfter(boundsAndStepIP); |
| 2319 | |
Kareem Ergawy | 0698482 | 2024-10-31 09:19:18 +0100 | [diff] [blame] | 2320 | info.loopVariable = genLoopVariableAddress(loc, *info.loopVariableSym, |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2321 | info.isUnordered); |
| 2322 | if (!getLoweringOptions().getIntegerWrapAround()) { |
| 2323 | iofBackup = builder->getIntegerOverflowFlags(); |
| 2324 | builder->setIntegerOverflowFlags( |
| 2325 | mlir::arith::IntegerOverflowFlags::nsw); |
| 2326 | } |
| 2327 | lowerValue = genControlValue(info.lowerExpr, info); |
| 2328 | upperValue = genControlValue(info.upperExpr, info); |
| 2329 | bool isConst = true; |
| 2330 | stepValue = genControlValue(info.stepExpr, info, |
| 2331 | info.isStructured() ? nullptr : &isConst); |
| 2332 | if (!getLoweringOptions().getIntegerWrapAround()) |
| 2333 | builder->setIntegerOverflowFlags(iofBackup); |
| 2334 | boundsAndStepIP = stepValue.getDefiningOp(); |
Kareem Ergawy | 0698482 | 2024-10-31 09:19:18 +0100 | [diff] [blame] | 2335 | |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2336 | // Use a temp variable for unstructured loops with non-const step. |
| 2337 | if (!isConst) { |
| 2338 | info.stepVariable = |
| 2339 | builder->createTemporary(loc, stepValue.getType()); |
| 2340 | boundsAndStepIP = |
| 2341 | builder->create<fir::StoreOp>(loc, stepValue, info.stepVariable); |
Kareem Ergawy | 04b87e1 | 2025-04-16 06:14:38 +0200 | [diff] [blame] | 2342 | } |
| 2343 | } |
Kareem Ergawy | 04b87e1 | 2025-04-16 06:14:38 +0200 | [diff] [blame] | 2344 | |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2345 | // Structured loop - generate fir.do_loop. |
| 2346 | if (info.isStructured()) { |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 2347 | mlir::Type loopVarType = info.getLoopVariableType(); |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2348 | mlir::Value loopValue; |
| 2349 | if (info.isUnordered) { |
| 2350 | llvm::SmallVector<mlir::Value> reduceOperands; |
| 2351 | llvm::SmallVector<mlir::Attribute> reduceAttrs; |
| 2352 | // Create DO CONCURRENT reduce operands and attributes |
| 2353 | for (const auto &reduceSym : info.reduceSymList) { |
| 2354 | const fir::ReduceOperationEnum reduce_operation = reduceSym.first; |
| 2355 | const Fortran::semantics::Symbol *sym = reduceSym.second; |
| 2356 | fir::ExtendedValue exv = getSymbolExtendedValue(*sym, nullptr); |
| 2357 | reduceOperands.push_back(fir::getBase(exv)); |
| 2358 | auto reduce_attr = |
| 2359 | fir::ReduceAttr::get(builder->getContext(), reduce_operation); |
| 2360 | reduceAttrs.push_back(reduce_attr); |
| 2361 | } |
| 2362 | // The loop variable value is explicitly updated. |
| 2363 | info.doLoop = builder->create<fir::DoLoopOp>( |
| 2364 | loc, lowerValue, upperValue, stepValue, /*unordered=*/true, |
| 2365 | /*finalCountValue=*/false, /*iterArgs=*/std::nullopt, |
| 2366 | llvm::ArrayRef<mlir::Value>(reduceOperands), reduceAttrs); |
| 2367 | builder->setInsertionPointToStart(info.doLoop.getBody()); |
| 2368 | loopValue = builder->createConvert(loc, loopVarType, |
| 2369 | info.doLoop.getInductionVar()); |
| 2370 | } else { |
| 2371 | // The loop variable is a doLoop op argument. |
| 2372 | info.doLoop = builder->create<fir::DoLoopOp>( |
| 2373 | loc, lowerValue, upperValue, stepValue, /*unordered=*/false, |
| 2374 | /*finalCountValue=*/true, |
| 2375 | builder->createConvert(loc, loopVarType, lowerValue)); |
| 2376 | builder->setInsertionPointToStart(info.doLoop.getBody()); |
| 2377 | loopValue = info.doLoop.getRegionIterArgs()[0]; |
| 2378 | } |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 2379 | // Update the loop variable value in case it has non-index references. |
| 2380 | builder->create<fir::StoreOp>(loc, loopValue, info.loopVariable); |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2381 | if (info.maskExpr) { |
| 2382 | Fortran::lower::StatementContext stmtCtx; |
| 2383 | mlir::Value maskCond = createFIRExpr(loc, info.maskExpr, stmtCtx); |
| 2384 | stmtCtx.finalizeAndReset(); |
| 2385 | mlir::Value maskCondCast = |
| 2386 | builder->createConvert(loc, builder->getI1Type(), maskCond); |
| 2387 | auto ifOp = builder->create<fir::IfOp>(loc, maskCondCast, |
| 2388 | /*withElseRegion=*/false); |
| 2389 | builder->setInsertionPointToStart(&ifOp.getThenRegion().front()); |
| 2390 | } |
| 2391 | if (info.hasLocalitySpecs()) |
| 2392 | handleLocalitySpecs(info); |
| 2393 | |
Jean-Didier PAILLEUX | e811cb0 | 2025-01-29 09:44:09 +0100 | [diff] [blame] | 2394 | addLoopAnnotationAttr(info, dirs); |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2395 | continue; |
| 2396 | } |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 2397 | |
| 2398 | // Unstructured loop preheader - initialize tripVariable and loopVariable. |
| 2399 | mlir::Value tripCount; |
Diana Picus | a159128 | 2022-05-31 10:55:56 +0000 | [diff] [blame] | 2400 | if (info.hasRealControl) { |
| 2401 | auto diff1 = |
| 2402 | builder->create<mlir::arith::SubFOp>(loc, upperValue, lowerValue); |
| 2403 | auto diff2 = |
Leandro Lupori | 3dbb055 | 2023-09-21 15:59:35 +0200 | [diff] [blame] | 2404 | builder->create<mlir::arith::AddFOp>(loc, diff1, stepValue); |
| 2405 | tripCount = builder->create<mlir::arith::DivFOp>(loc, diff2, stepValue); |
Diana Picus | a159128 | 2022-05-31 10:55:56 +0000 | [diff] [blame] | 2406 | tripCount = |
| 2407 | builder->createConvert(loc, builder->getIndexType(), tripCount); |
Diana Picus | a159128 | 2022-05-31 10:55:56 +0000 | [diff] [blame] | 2408 | } else { |
| 2409 | auto diff1 = |
| 2410 | builder->create<mlir::arith::SubIOp>(loc, upperValue, lowerValue); |
| 2411 | auto diff2 = |
Leandro Lupori | 3dbb055 | 2023-09-21 15:59:35 +0200 | [diff] [blame] | 2412 | builder->create<mlir::arith::AddIOp>(loc, diff1, stepValue); |
Diana Picus | a159128 | 2022-05-31 10:55:56 +0000 | [diff] [blame] | 2413 | tripCount = |
Leandro Lupori | 3dbb055 | 2023-09-21 15:59:35 +0200 | [diff] [blame] | 2414 | builder->create<mlir::arith::DivSIOp>(loc, diff2, stepValue); |
Diana Picus | a159128 | 2022-05-31 10:55:56 +0000 | [diff] [blame] | 2415 | } |
Kiran Chandramohan | 7eecfc0 | 2022-06-07 09:57:38 +0000 | [diff] [blame] | 2416 | if (forceLoopToExecuteOnce) { // minimum tripCount is 1 |
| 2417 | mlir::Value one = |
| 2418 | builder->createIntegerConstant(loc, tripCount.getType(), 1); |
| 2419 | auto cond = builder->create<mlir::arith::CmpIOp>( |
| 2420 | loc, mlir::arith::CmpIPredicate::slt, tripCount, one); |
| 2421 | tripCount = |
| 2422 | builder->create<mlir::arith::SelectOp>(loc, cond, one, tripCount); |
| 2423 | } |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 2424 | info.tripVariable = builder->createTemporary(loc, tripCount.getType()); |
| 2425 | builder->create<fir::StoreOp>(loc, tripCount, info.tripVariable); |
| 2426 | builder->create<fir::StoreOp>(loc, lowerValue, info.loopVariable); |
| 2427 | |
| 2428 | // Unstructured loop header - generate loop condition and mask. |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 2429 | // Note - Currently there is no way to tag a loop as a concurrent loop. |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 2430 | startBlock(info.headerBlock); |
| 2431 | tripCount = builder->create<fir::LoadOp>(loc, info.tripVariable); |
| 2432 | mlir::Value zero = |
| 2433 | builder->createIntegerConstant(loc, tripCount.getType(), 0); |
| 2434 | auto cond = builder->create<mlir::arith::CmpIOp>( |
| 2435 | loc, mlir::arith::CmpIPredicate::sgt, tripCount, zero); |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 2436 | if (info.maskExpr) { |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2437 | genConditionalBranch(cond, info.maskBlock, info.exitBlock); |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 2438 | startBlock(info.maskBlock); |
| 2439 | mlir::Block *latchBlock = getEval().getLastNestedEvaluation().block; |
| 2440 | assert(latchBlock && "missing masked concurrent loop latch block"); |
| 2441 | Fortran::lower::StatementContext stmtCtx; |
| 2442 | mlir::Value maskCond = createFIRExpr(loc, info.maskExpr, stmtCtx); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2443 | stmtCtx.finalizeAndReset(); |
| 2444 | genConditionalBranch(maskCond, info.bodyBlock, latchBlock); |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 2445 | } else { |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2446 | genConditionalBranch(cond, info.bodyBlock, info.exitBlock); |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 2447 | if (&info != &incrementLoopNestInfo.back()) // not innermost |
| 2448 | startBlock(info.bodyBlock); // preheader block of enclosed dimension |
| 2449 | } |
V Donaldson | 335b399 | 2023-08-07 13:29:17 -0700 | [diff] [blame] | 2450 | if (info.hasLocalitySpecs()) { |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 2451 | mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); |
| 2452 | builder->setInsertionPointToStart(info.bodyBlock); |
V Donaldson | 335b399 | 2023-08-07 13:29:17 -0700 | [diff] [blame] | 2453 | handleLocalitySpecs(info); |
Mats Petersson | 84b9ae6 | 2022-06-07 14:00:08 +0100 | [diff] [blame] | 2454 | builder->restoreInsertionPoint(insertPt); |
| 2455 | } |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2456 | } |
| 2457 | } |
| 2458 | |
| 2459 | /// Generate FIR to end a structured or unstructured increment loop nest. |
| 2460 | void genFIRIncrementLoopEnd(IncrementLoopNestInfo &incrementLoopNestInfo) { |
| 2461 | assert(!incrementLoopNestInfo.empty() && "empty loop nest"); |
| 2462 | mlir::Location loc = toLocation(); |
Yusuke MINATO | 526553b | 2024-05-16 13:16:07 +0900 | [diff] [blame] | 2463 | mlir::arith::IntegerOverflowFlags flags{}; |
Yusuke MINATO | a88677e | 2024-12-10 16:26:53 +0900 | [diff] [blame] | 2464 | if (!getLoweringOptions().getIntegerWrapAround()) |
Yusuke MINATO | 526553b | 2024-05-16 13:16:07 +0900 | [diff] [blame] | 2465 | flags = bitEnumSet(flags, mlir::arith::IntegerOverflowFlags::nsw); |
| 2466 | auto iofAttr = mlir::arith::IntegerOverflowFlagsAttr::get( |
| 2467 | builder->getContext(), flags); |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2468 | for (auto it = incrementLoopNestInfo.rbegin(), |
| 2469 | rend = incrementLoopNestInfo.rend(); |
| 2470 | it != rend; ++it) { |
| 2471 | IncrementLoopInfo &info = *it; |
| 2472 | if (info.isStructured()) { |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2473 | // End fir.do_loop. |
| 2474 | if (info.isUnordered) { |
| 2475 | builder->setInsertionPointAfter(info.doLoop); |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2476 | continue; |
Slava Zakharin | af7edf1 | 2022-08-18 14:06:19 -0700 | [diff] [blame] | 2477 | } |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 2478 | // Decrement tripVariable. |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2479 | builder->setInsertionPointToEnd(info.doLoop.getBody()); |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 2480 | llvm::SmallVector<mlir::Value, 2> results; |
| 2481 | results.push_back(builder->create<mlir::arith::AddIOp>( |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2482 | loc, info.doLoop.getInductionVar(), info.doLoop.getStep(), |
| 2483 | iofAttr)); |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 2484 | // Step loopVariable to help optimizations such as vectorization. |
| 2485 | // Induction variable elimination will clean up as necessary. |
| 2486 | mlir::Value step = builder->createConvert( |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2487 | loc, info.getLoopVariableType(), info.doLoop.getStep()); |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 2488 | mlir::Value loopVar = |
| 2489 | builder->create<fir::LoadOp>(loc, info.loopVariable); |
| 2490 | results.push_back( |
Yusuke MINATO | 526553b | 2024-05-16 13:16:07 +0900 | [diff] [blame] | 2491 | builder->create<mlir::arith::AddIOp>(loc, loopVar, step, iofAttr)); |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 2492 | builder->create<fir::ResultOp>(loc, results); |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2493 | builder->setInsertionPointAfter(info.doLoop); |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 2494 | // The loop control variable may be used after the loop. |
Kareem Ergawy | 30990c0 | 2025-04-16 14:20:27 +0200 | [diff] [blame^] | 2495 | builder->create<fir::StoreOp>(loc, info.doLoop.getResult(1), |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 2496 | info.loopVariable); |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2497 | continue; |
| 2498 | } |
| 2499 | |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 2500 | // Unstructured loop - decrement tripVariable and step loopVariable. |
| 2501 | mlir::Value tripCount = |
| 2502 | builder->create<fir::LoadOp>(loc, info.tripVariable); |
| 2503 | mlir::Value one = |
| 2504 | builder->createIntegerConstant(loc, tripCount.getType(), 1); |
| 2505 | tripCount = builder->create<mlir::arith::SubIOp>(loc, tripCount, one); |
| 2506 | builder->create<fir::StoreOp>(loc, tripCount, info.tripVariable); |
| 2507 | mlir::Value value = builder->create<fir::LoadOp>(loc, info.loopVariable); |
Leandro Lupori | 3dbb055 | 2023-09-21 15:59:35 +0200 | [diff] [blame] | 2508 | mlir::Value step; |
| 2509 | if (info.stepVariable) |
| 2510 | step = builder->create<fir::LoadOp>(loc, info.stepVariable); |
Diana Picus | a159128 | 2022-05-31 10:55:56 +0000 | [diff] [blame] | 2511 | else |
Leandro Lupori | 3dbb055 | 2023-09-21 15:59:35 +0200 | [diff] [blame] | 2512 | step = genControlValue(info.stepExpr, info); |
| 2513 | if (info.hasRealControl) |
| 2514 | value = builder->create<mlir::arith::AddFOp>(loc, value, step); |
| 2515 | else |
Yusuke MINATO | 526553b | 2024-05-16 13:16:07 +0900 | [diff] [blame] | 2516 | value = builder->create<mlir::arith::AddIOp>(loc, value, step, iofAttr); |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 2517 | builder->create<fir::StoreOp>(loc, value, info.loopVariable); |
| 2518 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2519 | genBranch(info.headerBlock); |
Kiran Chandramohan | aa0e167 | 2022-05-06 09:09:01 +0000 | [diff] [blame] | 2520 | if (&info != &incrementLoopNestInfo.front()) // not outermost |
| 2521 | startBlock(info.exitBlock); // latch block of enclosing dimension |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 2522 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2523 | } |
| 2524 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 2525 | /// Generate structured or unstructured FIR for an IF construct. |
| 2526 | /// The initial statement may be either an IfStmt or an IfThenStmt. |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2527 | void genFIR(const Fortran::parser::IfConstruct &) { |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 2528 | Fortran::lower::pft::Evaluation &eval = getEval(); |
vdonaldson | cda8270 | 2024-05-03 09:11:10 -0400 | [diff] [blame] | 2529 | |
| 2530 | // Structured fir.if nest. |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 2531 | if (eval.lowerAsStructured()) { |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 2532 | fir::IfOp topIfOp, currentIfOp; |
| 2533 | for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) { |
| 2534 | auto genIfOp = [&](mlir::Value cond) { |
vdonaldson | 8586d03 | 2024-08-30 09:07:30 -0400 | [diff] [blame] | 2535 | Fortran::lower::pft::Evaluation &succ = *e.controlSuccessor; |
| 2536 | bool hasElse = succ.isA<Fortran::parser::ElseIfStmt>() || |
| 2537 | succ.isA<Fortran::parser::ElseStmt>(); |
| 2538 | auto ifOp = builder->create<fir::IfOp>(toLocation(), cond, |
| 2539 | /*withElseRegion=*/hasElse); |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 2540 | builder->setInsertionPointToStart(&ifOp.getThenRegion().front()); |
| 2541 | return ifOp; |
| 2542 | }; |
vdonaldson | cda8270 | 2024-05-03 09:11:10 -0400 | [diff] [blame] | 2543 | setCurrentPosition(e.position); |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 2544 | if (auto *s = e.getIf<Fortran::parser::IfThenStmt>()) { |
| 2545 | topIfOp = currentIfOp = genIfOp(genIfCondition(s, e.negateCondition)); |
| 2546 | } else if (auto *s = e.getIf<Fortran::parser::IfStmt>()) { |
| 2547 | topIfOp = currentIfOp = genIfOp(genIfCondition(s, e.negateCondition)); |
| 2548 | } else if (auto *s = e.getIf<Fortran::parser::ElseIfStmt>()) { |
| 2549 | builder->setInsertionPointToStart( |
| 2550 | ¤tIfOp.getElseRegion().front()); |
| 2551 | currentIfOp = genIfOp(genIfCondition(s)); |
| 2552 | } else if (e.isA<Fortran::parser::ElseStmt>()) { |
| 2553 | builder->setInsertionPointToStart( |
| 2554 | ¤tIfOp.getElseRegion().front()); |
| 2555 | } else if (e.isA<Fortran::parser::EndIfStmt>()) { |
| 2556 | builder->setInsertionPointAfter(topIfOp); |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 2557 | genFIR(e, /*unstructuredContext=*/false); // may generate branch |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 2558 | } else { |
| 2559 | genFIR(e, /*unstructuredContext=*/false); |
| 2560 | } |
| 2561 | } |
| 2562 | return; |
| 2563 | } |
| 2564 | |
| 2565 | // Unstructured branch sequence. |
Krzysztof Parzyszek | c1b5b7c | 2024-05-21 08:19:54 -0500 | [diff] [blame] | 2566 | llvm::SmallVector<Fortran::lower::pft::Evaluation *> exits, fallThroughs; |
| 2567 | collectFinalEvaluations(eval, exits, fallThroughs); |
| 2568 | |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 2569 | for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) { |
| 2570 | auto genIfBranch = [&](mlir::Value cond) { |
| 2571 | if (e.lexicalSuccessor == e.controlSuccessor) // empty block -> exit |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2572 | genConditionalBranch(cond, e.parentConstruct->constructExit, |
| 2573 | e.controlSuccessor); |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 2574 | else // non-empty block |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2575 | genConditionalBranch(cond, e.lexicalSuccessor, e.controlSuccessor); |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 2576 | }; |
vdonaldson | cda8270 | 2024-05-03 09:11:10 -0400 | [diff] [blame] | 2577 | setCurrentPosition(e.position); |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 2578 | if (auto *s = e.getIf<Fortran::parser::IfThenStmt>()) { |
| 2579 | maybeStartBlock(e.block); |
| 2580 | genIfBranch(genIfCondition(s, e.negateCondition)); |
| 2581 | } else if (auto *s = e.getIf<Fortran::parser::IfStmt>()) { |
| 2582 | maybeStartBlock(e.block); |
| 2583 | genIfBranch(genIfCondition(s, e.negateCondition)); |
| 2584 | } else if (auto *s = e.getIf<Fortran::parser::ElseIfStmt>()) { |
| 2585 | startBlock(e.block); |
| 2586 | genIfBranch(genIfCondition(s)); |
| 2587 | } else { |
| 2588 | genFIR(e); |
Krzysztof Parzyszek | c1b5b7c | 2024-05-21 08:19:54 -0500 | [diff] [blame] | 2589 | if (blockIsUnterminated()) { |
| 2590 | if (llvm::is_contained(exits, &e)) |
| 2591 | genConstructExitBranch(*eval.constructExit); |
| 2592 | else if (llvm::is_contained(fallThroughs, &e)) |
| 2593 | genBranch(e.lexicalSuccessor->block); |
| 2594 | } |
Valentin Clement | 764f95a | 2022-03-07 19:55:48 +0100 | [diff] [blame] | 2595 | } |
| 2596 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2597 | } |
| 2598 | |
jeanPerier | d1aa9ba | 2024-06-03 17:20:07 +0200 | [diff] [blame] | 2599 | void genCaseOrRankConstruct() { |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2600 | Fortran::lower::pft::Evaluation &eval = getEval(); |
| 2601 | Fortran::lower::StatementContext stmtCtx; |
| 2602 | pushActiveConstruct(eval, stmtCtx); |
Krzysztof Parzyszek | c1b5b7c | 2024-05-21 08:19:54 -0500 | [diff] [blame] | 2603 | |
| 2604 | llvm::SmallVector<Fortran::lower::pft::Evaluation *> exits, fallThroughs; |
| 2605 | collectFinalEvaluations(eval, exits, fallThroughs); |
| 2606 | |
Carlos Eduardo Seo | 9ceb0a7 | 2023-05-20 05:16:50 +0000 | [diff] [blame] | 2607 | for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) { |
| 2608 | if (e.getIf<Fortran::parser::EndSelectStmt>()) |
| 2609 | maybeStartBlock(e.block); |
| 2610 | else |
| 2611 | genFIR(e); |
Krzysztof Parzyszek | c1b5b7c | 2024-05-21 08:19:54 -0500 | [diff] [blame] | 2612 | if (blockIsUnterminated()) { |
| 2613 | if (llvm::is_contained(exits, &e)) |
| 2614 | genConstructExitBranch(*eval.constructExit); |
| 2615 | else if (llvm::is_contained(fallThroughs, &e)) |
| 2616 | genBranch(e.lexicalSuccessor->block); |
| 2617 | } |
Carlos Eduardo Seo | 9ceb0a7 | 2023-05-20 05:16:50 +0000 | [diff] [blame] | 2618 | } |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 2619 | popActiveConstruct(); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2620 | } |
jeanPerier | d1aa9ba | 2024-06-03 17:20:07 +0200 | [diff] [blame] | 2621 | void genFIR(const Fortran::parser::CaseConstruct &) { |
| 2622 | genCaseOrRankConstruct(); |
| 2623 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2624 | |
Valentin Clement | 7a6a165 | 2022-03-10 18:43:40 +0100 | [diff] [blame] | 2625 | template <typename A> |
| 2626 | void genNestedStatement(const Fortran::parser::Statement<A> &stmt) { |
| 2627 | setCurrentPosition(stmt.source); |
| 2628 | genFIR(stmt.statement); |
| 2629 | } |
| 2630 | |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 2631 | /// Force the binding of an explicit symbol. This is used to bind and re-bind |
| 2632 | /// a concurrent control symbol to its value. |
| 2633 | void forceControlVariableBinding(const Fortran::semantics::Symbol *sym, |
| 2634 | mlir::Value inducVar) { |
| 2635 | mlir::Location loc = toLocation(); |
| 2636 | assert(sym && "There must be a symbol to bind"); |
| 2637 | mlir::Type toTy = genType(*sym); |
| 2638 | // FIXME: this should be a "per iteration" temporary. |
Mats Petersson | 0ccef6a | 2023-11-29 16:15:43 +0000 | [diff] [blame] | 2639 | mlir::Value tmp = |
| 2640 | builder->createTemporary(loc, toTy, toStringRef(sym->name()), |
| 2641 | llvm::ArrayRef<mlir::NamedAttribute>{ |
| 2642 | fir::getAdaptToByRefAttr(*builder)}); |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 2643 | mlir::Value cast = builder->createConvert(loc, toTy, inducVar); |
| 2644 | builder->create<fir::StoreOp>(loc, cast, tmp); |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 2645 | addSymbol(*sym, tmp, /*force=*/true); |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 2646 | } |
| 2647 | |
| 2648 | /// Process a concurrent header for a FORALL. (Concurrent headers for DO |
| 2649 | /// CONCURRENT loops are lowered elsewhere.) |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2650 | void genFIR(const Fortran::parser::ConcurrentHeader &header) { |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 2651 | llvm::SmallVector<mlir::Value> lows; |
| 2652 | llvm::SmallVector<mlir::Value> highs; |
| 2653 | llvm::SmallVector<mlir::Value> steps; |
| 2654 | if (explicitIterSpace.isOutermostForall()) { |
| 2655 | // For the outermost forall, we evaluate the bounds expressions once. |
| 2656 | // Contrastingly, if this forall is nested, the bounds expressions are |
| 2657 | // assumed to be pure, possibly dependent on outer concurrent control |
| 2658 | // variables, possibly variant with respect to arguments, and will be |
| 2659 | // re-evaluated. |
| 2660 | mlir::Location loc = toLocation(); |
| 2661 | mlir::Type idxTy = builder->getIndexType(); |
| 2662 | Fortran::lower::StatementContext &stmtCtx = |
| 2663 | explicitIterSpace.stmtContext(); |
| 2664 | auto lowerExpr = [&](auto &e) { |
| 2665 | return fir::getBase(genExprValue(e, stmtCtx)); |
| 2666 | }; |
| 2667 | for (const Fortran::parser::ConcurrentControl &ctrl : |
| 2668 | std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) { |
| 2669 | const Fortran::lower::SomeExpr *lo = |
| 2670 | Fortran::semantics::GetExpr(std::get<1>(ctrl.t)); |
| 2671 | const Fortran::lower::SomeExpr *hi = |
| 2672 | Fortran::semantics::GetExpr(std::get<2>(ctrl.t)); |
| 2673 | auto &optStep = |
| 2674 | std::get<std::optional<Fortran::parser::ScalarIntExpr>>(ctrl.t); |
| 2675 | lows.push_back(builder->createConvert(loc, idxTy, lowerExpr(*lo))); |
| 2676 | highs.push_back(builder->createConvert(loc, idxTy, lowerExpr(*hi))); |
| 2677 | steps.push_back( |
| 2678 | optStep.has_value() |
| 2679 | ? builder->createConvert( |
| 2680 | loc, idxTy, |
| 2681 | lowerExpr(*Fortran::semantics::GetExpr(*optStep))) |
| 2682 | : builder->createIntegerConstant(loc, idxTy, 1)); |
| 2683 | } |
| 2684 | } |
| 2685 | auto lambda = [&, lows, highs, steps]() { |
| 2686 | // Create our iteration space from the header spec. |
| 2687 | mlir::Location loc = toLocation(); |
| 2688 | mlir::Type idxTy = builder->getIndexType(); |
| 2689 | llvm::SmallVector<fir::DoLoopOp> loops; |
| 2690 | Fortran::lower::StatementContext &stmtCtx = |
| 2691 | explicitIterSpace.stmtContext(); |
| 2692 | auto lowerExpr = [&](auto &e) { |
| 2693 | return fir::getBase(genExprValue(e, stmtCtx)); |
| 2694 | }; |
| 2695 | const bool outermost = !lows.empty(); |
| 2696 | std::size_t headerIndex = 0; |
| 2697 | for (const Fortran::parser::ConcurrentControl &ctrl : |
| 2698 | std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) { |
| 2699 | const Fortran::semantics::Symbol *ctrlVar = |
| 2700 | std::get<Fortran::parser::Name>(ctrl.t).symbol; |
| 2701 | mlir::Value lb; |
| 2702 | mlir::Value ub; |
| 2703 | mlir::Value by; |
| 2704 | if (outermost) { |
| 2705 | assert(headerIndex < lows.size()); |
| 2706 | if (headerIndex == 0) |
| 2707 | explicitIterSpace.resetInnerArgs(); |
| 2708 | lb = lows[headerIndex]; |
| 2709 | ub = highs[headerIndex]; |
| 2710 | by = steps[headerIndex++]; |
| 2711 | } else { |
| 2712 | const Fortran::lower::SomeExpr *lo = |
| 2713 | Fortran::semantics::GetExpr(std::get<1>(ctrl.t)); |
| 2714 | const Fortran::lower::SomeExpr *hi = |
| 2715 | Fortran::semantics::GetExpr(std::get<2>(ctrl.t)); |
| 2716 | auto &optStep = |
| 2717 | std::get<std::optional<Fortran::parser::ScalarIntExpr>>(ctrl.t); |
| 2718 | lb = builder->createConvert(loc, idxTy, lowerExpr(*lo)); |
| 2719 | ub = builder->createConvert(loc, idxTy, lowerExpr(*hi)); |
| 2720 | by = optStep.has_value() |
| 2721 | ? builder->createConvert( |
| 2722 | loc, idxTy, |
| 2723 | lowerExpr(*Fortran::semantics::GetExpr(*optStep))) |
| 2724 | : builder->createIntegerConstant(loc, idxTy, 1); |
| 2725 | } |
| 2726 | auto lp = builder->create<fir::DoLoopOp>( |
| 2727 | loc, lb, ub, by, /*unordered=*/true, |
| 2728 | /*finalCount=*/false, explicitIterSpace.getInnerArgs()); |
Valentin Clement | 0dd4fb0 | 2022-07-01 10:36:45 +0200 | [diff] [blame] | 2729 | if ((!loops.empty() || !outermost) && !lp.getRegionIterArgs().empty()) |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 2730 | builder->create<fir::ResultOp>(loc, lp.getResults()); |
| 2731 | explicitIterSpace.setInnerArgs(lp.getRegionIterArgs()); |
| 2732 | builder->setInsertionPointToStart(lp.getBody()); |
| 2733 | forceControlVariableBinding(ctrlVar, lp.getInductionVar()); |
| 2734 | loops.push_back(lp); |
| 2735 | } |
| 2736 | if (outermost) |
| 2737 | explicitIterSpace.setOuterLoop(loops[0]); |
| 2738 | explicitIterSpace.appendLoops(loops); |
| 2739 | if (const auto &mask = |
| 2740 | std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>( |
| 2741 | header.t); |
| 2742 | mask.has_value()) { |
| 2743 | mlir::Type i1Ty = builder->getI1Type(); |
| 2744 | fir::ExtendedValue maskExv = |
| 2745 | genExprValue(*Fortran::semantics::GetExpr(mask.value()), stmtCtx); |
| 2746 | mlir::Value cond = |
| 2747 | builder->createConvert(loc, i1Ty, fir::getBase(maskExv)); |
| 2748 | auto ifOp = builder->create<fir::IfOp>( |
| 2749 | loc, explicitIterSpace.innerArgTypes(), cond, |
| 2750 | /*withElseRegion=*/true); |
| 2751 | builder->create<fir::ResultOp>(loc, ifOp.getResults()); |
| 2752 | builder->setInsertionPointToStart(&ifOp.getElseRegion().front()); |
| 2753 | builder->create<fir::ResultOp>(loc, explicitIterSpace.getInnerArgs()); |
| 2754 | builder->setInsertionPointToStart(&ifOp.getThenRegion().front()); |
| 2755 | } |
| 2756 | }; |
| 2757 | // Push the lambda to gen the loop nest context. |
| 2758 | explicitIterSpace.pushLoopNest(lambda); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2759 | } |
| 2760 | |
| 2761 | void genFIR(const Fortran::parser::ForallAssignmentStmt &stmt) { |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 2762 | Fortran::common::visit([&](const auto &x) { genFIR(x); }, stmt.u); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2763 | } |
| 2764 | |
| 2765 | void genFIR(const Fortran::parser::EndForallStmt &) { |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 2766 | if (!lowerToHighLevelFIR()) |
| 2767 | cleanupExplicitSpace(); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2768 | } |
| 2769 | |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 2770 | template <typename A> |
| 2771 | void prepareExplicitSpace(const A &forall) { |
| 2772 | if (!explicitIterSpace.isActive()) |
| 2773 | analyzeExplicitSpace(forall); |
| 2774 | localSymbols.pushScope(); |
| 2775 | explicitIterSpace.enter(); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2776 | } |
| 2777 | |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 2778 | /// Cleanup all the FORALL context information when we exit. |
| 2779 | void cleanupExplicitSpace() { |
| 2780 | explicitIterSpace.leave(); |
| 2781 | localSymbols.popScope(); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2782 | } |
| 2783 | |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 2784 | /// Generate FIR for a FORALL statement. |
| 2785 | void genFIR(const Fortran::parser::ForallStmt &stmt) { |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 2786 | const auto &concurrentHeader = |
| 2787 | std::get< |
| 2788 | Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>( |
| 2789 | stmt.t) |
| 2790 | .value(); |
| 2791 | if (lowerToHighLevelFIR()) { |
Sergio Afonso | 433ca3e | 2024-09-10 11:09:25 +0100 | [diff] [blame] | 2792 | mlir::OpBuilder::InsertionGuard guard(*builder); |
| 2793 | Fortran::lower::SymMapScope scope(localSymbols); |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 2794 | genForallNest(concurrentHeader); |
| 2795 | genFIR(std::get<Fortran::parser::UnlabeledStatement< |
| 2796 | Fortran::parser::ForallAssignmentStmt>>(stmt.t) |
| 2797 | .statement); |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 2798 | return; |
| 2799 | } |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 2800 | prepareExplicitSpace(stmt); |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 2801 | genFIR(concurrentHeader); |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 2802 | genFIR(std::get<Fortran::parser::UnlabeledStatement< |
| 2803 | Fortran::parser::ForallAssignmentStmt>>(stmt.t) |
| 2804 | .statement); |
| 2805 | cleanupExplicitSpace(); |
| 2806 | } |
| 2807 | |
| 2808 | /// Generate FIR for a FORALL construct. |
| 2809 | void genFIR(const Fortran::parser::ForallConstruct &forall) { |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 2810 | mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); |
| 2811 | if (lowerToHighLevelFIR()) |
| 2812 | localSymbols.pushScope(); |
| 2813 | else |
| 2814 | prepareExplicitSpace(forall); |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 2815 | genNestedStatement( |
| 2816 | std::get< |
| 2817 | Fortran::parser::Statement<Fortran::parser::ForallConstructStmt>>( |
| 2818 | forall.t)); |
| 2819 | for (const Fortran::parser::ForallBodyConstruct &s : |
| 2820 | std::get<std::list<Fortran::parser::ForallBodyConstruct>>(forall.t)) { |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 2821 | Fortran::common::visit( |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 2822 | Fortran::common::visitors{ |
| 2823 | [&](const Fortran::parser::WhereConstruct &b) { genFIR(b); }, |
| 2824 | [&](const Fortran::common::Indirection< |
| 2825 | Fortran::parser::ForallConstruct> &b) { genFIR(b.value()); }, |
| 2826 | [&](const auto &b) { genNestedStatement(b); }}, |
| 2827 | s.u); |
| 2828 | } |
| 2829 | genNestedStatement( |
| 2830 | std::get<Fortran::parser::Statement<Fortran::parser::EndForallStmt>>( |
| 2831 | forall.t)); |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 2832 | if (lowerToHighLevelFIR()) { |
| 2833 | localSymbols.popScope(); |
| 2834 | builder->restoreInsertionPoint(insertPt); |
| 2835 | } |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 2836 | } |
| 2837 | |
| 2838 | /// Lower the concurrent header specification. |
| 2839 | void genFIR(const Fortran::parser::ForallConstructStmt &stmt) { |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 2840 | const auto &concurrentHeader = |
| 2841 | std::get< |
| 2842 | Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>( |
| 2843 | stmt.t) |
| 2844 | .value(); |
| 2845 | if (lowerToHighLevelFIR()) |
| 2846 | genForallNest(concurrentHeader); |
| 2847 | else |
| 2848 | genFIR(concurrentHeader); |
| 2849 | } |
| 2850 | |
| 2851 | /// Generate hlfir.forall and hlfir.forall_mask nest given a Forall |
| 2852 | /// concurrent header |
| 2853 | void genForallNest(const Fortran::parser::ConcurrentHeader &header) { |
| 2854 | mlir::Location loc = getCurrentLocation(); |
| 2855 | const bool isOutterForall = !isInsideHlfirForallOrWhere(); |
| 2856 | hlfir::ForallOp outerForall; |
| 2857 | auto evaluateControl = [&](const auto &parserExpr, mlir::Region ®ion, |
| 2858 | bool isMask = false) { |
| 2859 | if (region.empty()) |
| 2860 | builder->createBlock(®ion); |
| 2861 | Fortran::lower::StatementContext localStmtCtx; |
| 2862 | const Fortran::semantics::SomeExpr *anlalyzedExpr = |
| 2863 | Fortran::semantics::GetExpr(parserExpr); |
| 2864 | assert(anlalyzedExpr && "expression semantics failed"); |
| 2865 | // Generate the controls of outer forall outside of the hlfir.forall |
| 2866 | // region. They do not depend on any previous forall indices (C1123) and |
| 2867 | // no assignment has been made yet that could modify their value. This |
| 2868 | // will simplify hlfir.forall analysis because the SSA integer value |
| 2869 | // yielded will obviously not depend on any variable modified by the |
| 2870 | // forall when produced outside of it. |
| 2871 | // This is not done for the mask because it may (and in usual code, does) |
| 2872 | // depend on the forall indices that have just been defined as |
| 2873 | // hlfir.forall block arguments. |
| 2874 | mlir::OpBuilder::InsertPoint innerInsertionPoint; |
| 2875 | if (outerForall && !isMask) { |
| 2876 | innerInsertionPoint = builder->saveInsertionPoint(); |
| 2877 | builder->setInsertionPoint(outerForall); |
| 2878 | } |
| 2879 | mlir::Value exprVal = |
| 2880 | fir::getBase(genExprValue(*anlalyzedExpr, localStmtCtx, &loc)); |
| 2881 | localStmtCtx.finalizeAndPop(); |
| 2882 | if (isMask) |
| 2883 | exprVal = builder->createConvert(loc, builder->getI1Type(), exprVal); |
| 2884 | if (innerInsertionPoint.isSet()) |
| 2885 | builder->restoreInsertionPoint(innerInsertionPoint); |
| 2886 | builder->create<hlfir::YieldOp>(loc, exprVal); |
| 2887 | }; |
| 2888 | for (const Fortran::parser::ConcurrentControl &control : |
| 2889 | std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) { |
| 2890 | auto forallOp = builder->create<hlfir::ForallOp>(loc); |
| 2891 | if (isOutterForall && !outerForall) |
| 2892 | outerForall = forallOp; |
| 2893 | evaluateControl(std::get<1>(control.t), forallOp.getLbRegion()); |
| 2894 | evaluateControl(std::get<2>(control.t), forallOp.getUbRegion()); |
| 2895 | if (const auto &optionalStep = |
| 2896 | std::get<std::optional<Fortran::parser::ScalarIntExpr>>( |
| 2897 | control.t)) |
| 2898 | evaluateControl(*optionalStep, forallOp.getStepRegion()); |
| 2899 | // Create block argument and map it to a symbol via an hlfir.forall_index |
| 2900 | // op (symbols must be mapped to in memory values). |
| 2901 | const Fortran::semantics::Symbol *controlVar = |
| 2902 | std::get<Fortran::parser::Name>(control.t).symbol; |
| 2903 | assert(controlVar && "symbol analysis failed"); |
| 2904 | mlir::Type controlVarType = genType(*controlVar); |
| 2905 | mlir::Block *forallBody = builder->createBlock(&forallOp.getBody(), {}, |
| 2906 | {controlVarType}, {loc}); |
| 2907 | auto forallIndex = builder->create<hlfir::ForallIndexOp>( |
| 2908 | loc, fir::ReferenceType::get(controlVarType), |
| 2909 | forallBody->getArguments()[0], |
| 2910 | builder->getStringAttr(controlVar->name().ToString())); |
| 2911 | localSymbols.addVariableDefinition(*controlVar, forallIndex, |
| 2912 | /*force=*/true); |
| 2913 | auto end = builder->create<fir::FirEndOp>(loc); |
| 2914 | builder->setInsertionPoint(end); |
| 2915 | } |
| 2916 | |
| 2917 | if (const auto &maskExpr = |
| 2918 | std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>( |
| 2919 | header.t)) { |
| 2920 | // Create hlfir.forall_mask and set insertion point in its body. |
| 2921 | auto forallMaskOp = builder->create<hlfir::ForallMaskOp>(loc); |
| 2922 | evaluateControl(*maskExpr, forallMaskOp.getMaskRegion(), /*isMask=*/true); |
| 2923 | builder->createBlock(&forallMaskOp.getBody()); |
| 2924 | auto end = builder->create<fir::FirEndOp>(loc); |
| 2925 | builder->setInsertionPoint(end); |
| 2926 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2927 | } |
| 2928 | |
David Truby | c6b6e18 | 2024-06-14 14:10:41 +0100 | [diff] [blame] | 2929 | void attachDirectiveToLoop(const Fortran::parser::CompilerDirective &dir, |
| 2930 | Fortran::lower::pft::Evaluation *e) { |
| 2931 | while (e->isDirective()) |
| 2932 | e = e->lexicalSuccessor; |
| 2933 | |
| 2934 | if (e->isA<Fortran::parser::NonLabelDoStmt>()) |
| 2935 | e->dirs.push_back(&dir); |
David Truby | c6b6e18 | 2024-06-14 14:10:41 +0100 | [diff] [blame] | 2936 | } |
| 2937 | |
| 2938 | void genFIR(const Fortran::parser::CompilerDirective &dir) { |
| 2939 | Fortran::lower::pft::Evaluation &eval = getEval(); |
| 2940 | |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 2941 | Fortran::common::visit( |
David Truby | c6b6e18 | 2024-06-14 14:10:41 +0100 | [diff] [blame] | 2942 | Fortran::common::visitors{ |
| 2943 | [&](const Fortran::parser::CompilerDirective::VectorAlways &) { |
| 2944 | attachDirectiveToLoop(dir, &eval); |
| 2945 | }, |
Jean-Didier PAILLEUX | e811cb0 | 2025-01-29 09:44:09 +0100 | [diff] [blame] | 2946 | [&](const Fortran::parser::CompilerDirective::Unroll &) { |
| 2947 | attachDirectiveToLoop(dir, &eval); |
| 2948 | }, |
Jean-Didier PAILLEUX | d6c6bde | 2025-02-19 16:00:09 +0100 | [diff] [blame] | 2949 | [&](const Fortran::parser::CompilerDirective::UnrollAndJam &) { |
| 2950 | attachDirectiveToLoop(dir, &eval); |
| 2951 | }, |
Jean-Didier PAILLEUX | c309abd | 2025-04-02 14:30:01 +0200 | [diff] [blame] | 2952 | [&](const Fortran::parser::CompilerDirective::NoVector &) { |
| 2953 | attachDirectiveToLoop(dir, &eval); |
| 2954 | }, |
| 2955 | [&](const Fortran::parser::CompilerDirective::NoUnroll &) { |
| 2956 | attachDirectiveToLoop(dir, &eval); |
| 2957 | }, |
| 2958 | [&](const Fortran::parser::CompilerDirective::NoUnrollAndJam &) { |
| 2959 | attachDirectiveToLoop(dir, &eval); |
| 2960 | }, |
David Truby | c6b6e18 | 2024-06-14 14:10:41 +0100 | [diff] [blame] | 2961 | [&](const auto &) {}}, |
| 2962 | dir.u); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 2963 | } |
| 2964 | |
Valentin Clement | 12d22ce | 2022-03-24 15:00:52 +0100 | [diff] [blame] | 2965 | void genFIR(const Fortran::parser::OpenACCConstruct &acc) { |
| 2966 | mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); |
Razvan Lupusoru | e070ea4 | 2023-09-11 13:58:10 -0700 | [diff] [blame] | 2967 | localSymbols.pushScope(); |
Valentin Clement (バレンタイン クレメン) | a9a5af8 | 2023-11-30 14:25:03 -0800 | [diff] [blame] | 2968 | mlir::Value exitCond = genOpenACCConstruct( |
| 2969 | *this, bridge.getSemanticsContext(), getEval(), acc); |
Valentin Clement (バレンタイン クレメン) | 5062a17 | 2024-01-22 10:31:37 -0800 | [diff] [blame] | 2970 | |
| 2971 | const Fortran::parser::OpenACCLoopConstruct *accLoop = |
| 2972 | std::get_if<Fortran::parser::OpenACCLoopConstruct>(&acc.u); |
| 2973 | const Fortran::parser::OpenACCCombinedConstruct *accCombined = |
| 2974 | std::get_if<Fortran::parser::OpenACCCombinedConstruct>(&acc.u); |
| 2975 | |
| 2976 | Fortran::lower::pft::Evaluation *curEval = &getEval(); |
| 2977 | |
| 2978 | if (accLoop || accCombined) { |
| 2979 | int64_t collapseValue; |
| 2980 | if (accLoop) { |
| 2981 | const Fortran::parser::AccBeginLoopDirective &beginLoopDir = |
| 2982 | std::get<Fortran::parser::AccBeginLoopDirective>(accLoop->t); |
| 2983 | const Fortran::parser::AccClauseList &clauseList = |
| 2984 | std::get<Fortran::parser::AccClauseList>(beginLoopDir.t); |
| 2985 | collapseValue = Fortran::lower::getCollapseValue(clauseList); |
| 2986 | } else if (accCombined) { |
| 2987 | const Fortran::parser::AccBeginCombinedDirective &beginCombinedDir = |
| 2988 | std::get<Fortran::parser::AccBeginCombinedDirective>( |
| 2989 | accCombined->t); |
| 2990 | const Fortran::parser::AccClauseList &clauseList = |
| 2991 | std::get<Fortran::parser::AccClauseList>(beginCombinedDir.t); |
| 2992 | collapseValue = Fortran::lower::getCollapseValue(clauseList); |
| 2993 | } |
| 2994 | |
| 2995 | if (curEval->lowerAsStructured()) { |
| 2996 | curEval = &curEval->getFirstNestedEvaluation(); |
| 2997 | for (int64_t i = 1; i < collapseValue; i++) |
| 2998 | curEval = &*std::next(curEval->getNestedEvaluations().begin()); |
| 2999 | } |
| 3000 | } |
| 3001 | |
| 3002 | for (Fortran::lower::pft::Evaluation &e : curEval->getNestedEvaluations()) |
Valentin Clement | 12d22ce | 2022-03-24 15:00:52 +0100 | [diff] [blame] | 3003 | genFIR(e); |
Razvan Lupusoru | e070ea4 | 2023-09-11 13:58:10 -0700 | [diff] [blame] | 3004 | localSymbols.popScope(); |
Valentin Clement | 12d22ce | 2022-03-24 15:00:52 +0100 | [diff] [blame] | 3005 | builder->restoreInsertionPoint(insertPt); |
Valentin Clement (バレンタイン クレメン) | a9a5af8 | 2023-11-30 14:25:03 -0800 | [diff] [blame] | 3006 | |
Valentin Clement (バレンタイン クレメン) | a9a5af8 | 2023-11-30 14:25:03 -0800 | [diff] [blame] | 3007 | if (accLoop && exitCond) { |
| 3008 | Fortran::lower::pft::FunctionLikeUnit *funit = |
| 3009 | getEval().getOwningProcedure(); |
| 3010 | assert(funit && "not inside main program, function or subroutine"); |
| 3011 | mlir::Block *continueBlock = |
| 3012 | builder->getBlock()->splitBlock(builder->getBlock()->end()); |
| 3013 | builder->create<mlir::cf::CondBranchOp>(toLocation(), exitCond, |
| 3014 | funit->finalBlock, continueBlock); |
| 3015 | builder->setInsertionPointToEnd(continueBlock); |
| 3016 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3017 | } |
| 3018 | |
Peixin-Qiao | b6b8d34 | 2022-04-28 09:40:30 +0800 | [diff] [blame] | 3019 | void genFIR(const Fortran::parser::OpenACCDeclarativeConstruct &accDecl) { |
Valentin Clement | c217ff8 | 2023-07-26 09:55:57 -0700 | [diff] [blame] | 3020 | genOpenACCDeclarativeConstruct(*this, bridge.getSemanticsContext(), |
Valentin Clement (バレンタイン クレメン) | a3700cc | 2023-11-14 14:42:11 -0800 | [diff] [blame] | 3021 | bridge.openAccCtx(), accDecl, |
| 3022 | accRoutineInfos); |
Peixin-Qiao | b6b8d34 | 2022-04-28 09:40:30 +0800 | [diff] [blame] | 3023 | for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations()) |
| 3024 | genFIR(e); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3025 | } |
| 3026 | |
Valentin Clement (バレンタイン クレメン) | 8286743 | 2023-10-24 09:17:48 -0700 | [diff] [blame] | 3027 | void genFIR(const Fortran::parser::OpenACCRoutineConstruct &acc) { |
| 3028 | // Handled by genFIR(const Fortran::parser::OpenACCDeclarativeConstruct &) |
| 3029 | } |
| 3030 | |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3031 | void genFIR(const Fortran::parser::CUFKernelDoConstruct &kernel) { |
Sergio Afonso | 433ca3e | 2024-09-10 11:09:25 +0100 | [diff] [blame] | 3032 | Fortran::lower::SymMapScope scope(localSymbols); |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3033 | const Fortran::parser::CUFKernelDoConstruct::Directive &dir = |
| 3034 | std::get<Fortran::parser::CUFKernelDoConstruct::Directive>(kernel.t); |
| 3035 | |
| 3036 | mlir::Location loc = genLocation(dir.source); |
| 3037 | |
| 3038 | Fortran::lower::StatementContext stmtCtx; |
| 3039 | |
| 3040 | unsigned nestedLoops = 1; |
| 3041 | |
| 3042 | const auto &nLoops = |
| 3043 | std::get<std::optional<Fortran::parser::ScalarIntConstantExpr>>(dir.t); |
| 3044 | if (nLoops) |
| 3045 | nestedLoops = *Fortran::semantics::GetIntValue(*nLoops); |
| 3046 | |
| 3047 | mlir::IntegerAttr n; |
| 3048 | if (nestedLoops > 1) |
| 3049 | n = builder->getIntegerAttr(builder->getI64Type(), nestedLoops); |
| 3050 | |
Valentin Clement (バレンタイン クレメン) | 37143fe | 2024-11-12 16:49:44 -0800 | [diff] [blame] | 3051 | const auto &launchConfig = std::get<std::optional< |
| 3052 | Fortran::parser::CUFKernelDoConstruct::LaunchConfiguration>>(dir.t); |
| 3053 | |
Iman Hosseini | 7665d3d | 2024-06-12 19:18:41 +0100 | [diff] [blame] | 3054 | const std::list<Fortran::parser::CUFReduction> &cufreds = |
Valentin Clement (バレンタイン クレメン) | 37143fe | 2024-11-12 16:49:44 -0800 | [diff] [blame] | 3055 | std::get<2>(dir.t); |
Iman Hosseini | 7665d3d | 2024-06-12 19:18:41 +0100 | [diff] [blame] | 3056 | |
| 3057 | llvm::SmallVector<mlir::Value> reduceOperands; |
| 3058 | llvm::SmallVector<mlir::Attribute> reduceAttrs; |
| 3059 | |
| 3060 | for (const Fortran::parser::CUFReduction &cufred : cufreds) { |
| 3061 | fir::ReduceOperationEnum redOpEnum = getReduceOperationEnum( |
| 3062 | std::get<Fortran::parser::ReductionOperator>(cufred.t)); |
| 3063 | const std::list<Fortran::parser::Scalar<Fortran::parser::Variable>> |
| 3064 | &scalarvars = std::get<1>(cufred.t); |
| 3065 | for (const Fortran::parser::Scalar<Fortran::parser::Variable> &scalarvar : |
| 3066 | scalarvars) { |
| 3067 | auto reduce_attr = |
| 3068 | fir::ReduceAttr::get(builder->getContext(), redOpEnum); |
| 3069 | reduceAttrs.push_back(reduce_attr); |
| 3070 | const Fortran::parser::Variable &var = scalarvar.thing; |
| 3071 | if (const auto *iDesignator = std::get_if< |
| 3072 | Fortran::common::Indirection<Fortran::parser::Designator>>( |
| 3073 | &var.u)) { |
| 3074 | const Fortran::parser::Designator &designator = iDesignator->value(); |
| 3075 | if (const auto *name = |
| 3076 | Fortran::semantics::getDesignatorNameIfDataRef(designator)) { |
| 3077 | auto val = getSymbolAddress(*name->symbol); |
| 3078 | reduceOperands.push_back(val); |
| 3079 | } |
| 3080 | } |
| 3081 | } |
| 3082 | } |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3083 | |
Valentin Clement (バレンタイン クレメン) | f6a2a55 | 2024-03-18 19:46:11 -0700 | [diff] [blame] | 3084 | auto isOnlyStars = |
| 3085 | [&](const std::list<Fortran::parser::CUFKernelDoConstruct::StarOrExpr> |
| 3086 | &list) -> bool { |
| 3087 | for (const Fortran::parser::CUFKernelDoConstruct::StarOrExpr &expr : |
| 3088 | list) { |
| 3089 | if (expr.v) |
| 3090 | return false; |
| 3091 | } |
| 3092 | return true; |
| 3093 | }; |
| 3094 | |
| 3095 | mlir::Value zero = |
| 3096 | builder->createIntegerConstant(loc, builder->getI32Type(), 0); |
| 3097 | |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3098 | llvm::SmallVector<mlir::Value> gridValues; |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3099 | llvm::SmallVector<mlir::Value> blockValues; |
Valentin Clement (バレンタイン クレメン) | 37143fe | 2024-11-12 16:49:44 -0800 | [diff] [blame] | 3100 | mlir::Value streamValue; |
| 3101 | |
| 3102 | if (launchConfig) { |
| 3103 | const std::list<Fortran::parser::CUFKernelDoConstruct::StarOrExpr> &grid = |
| 3104 | std::get<0>(launchConfig->t); |
| 3105 | const std::list<Fortran::parser::CUFKernelDoConstruct::StarOrExpr> |
| 3106 | &block = std::get<1>(launchConfig->t); |
| 3107 | const std::optional<Fortran::parser::ScalarIntExpr> &stream = |
| 3108 | std::get<2>(launchConfig->t); |
| 3109 | if (!isOnlyStars(grid)) { |
| 3110 | for (const Fortran::parser::CUFKernelDoConstruct::StarOrExpr &expr : |
| 3111 | grid) { |
| 3112 | if (expr.v) { |
| 3113 | gridValues.push_back(fir::getBase( |
| 3114 | genExprValue(*Fortran::semantics::GetExpr(*expr.v), stmtCtx))); |
| 3115 | } else { |
| 3116 | gridValues.push_back(zero); |
| 3117 | } |
Valentin Clement (バレンタイン クレメン) | f6a2a55 | 2024-03-18 19:46:11 -0700 | [diff] [blame] | 3118 | } |
Peter Klausler | 60fa2b0 | 2024-03-15 13:57:42 -0700 | [diff] [blame] | 3119 | } |
Valentin Clement (バレンタイン クレメン) | 37143fe | 2024-11-12 16:49:44 -0800 | [diff] [blame] | 3120 | if (!isOnlyStars(block)) { |
| 3121 | for (const Fortran::parser::CUFKernelDoConstruct::StarOrExpr &expr : |
| 3122 | block) { |
| 3123 | if (expr.v) { |
| 3124 | blockValues.push_back(fir::getBase( |
| 3125 | genExprValue(*Fortran::semantics::GetExpr(*expr.v), stmtCtx))); |
| 3126 | } else { |
| 3127 | blockValues.push_back(zero); |
| 3128 | } |
| 3129 | } |
| 3130 | } |
| 3131 | |
| 3132 | if (stream) |
| 3133 | streamValue = builder->createConvert( |
| 3134 | loc, builder->getI32Type(), |
| 3135 | fir::getBase( |
| 3136 | genExprValue(*Fortran::semantics::GetExpr(*stream), stmtCtx))); |
Peter Klausler | 60fa2b0 | 2024-03-15 13:57:42 -0700 | [diff] [blame] | 3137 | } |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3138 | |
| 3139 | const auto &outerDoConstruct = |
| 3140 | std::get<std::optional<Fortran::parser::DoConstruct>>(kernel.t); |
| 3141 | |
| 3142 | llvm::SmallVector<mlir::Location> locs; |
| 3143 | locs.push_back(loc); |
| 3144 | llvm::SmallVector<mlir::Value> lbs, ubs, steps; |
| 3145 | |
| 3146 | mlir::Type idxTy = builder->getIndexType(); |
| 3147 | |
| 3148 | llvm::SmallVector<mlir::Type> ivTypes; |
| 3149 | llvm::SmallVector<mlir::Location> ivLocs; |
| 3150 | llvm::SmallVector<mlir::Value> ivValues; |
Valentin Clement (バレンタイン クレメン) | f724540 | 2024-05-07 08:29:21 -0700 | [diff] [blame] | 3151 | Fortran::lower::pft::Evaluation *loopEval = |
| 3152 | &getEval().getFirstNestedEvaluation(); |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3153 | if (outerDoConstruct->IsDoConcurrent()) { |
| 3154 | // Handle DO CONCURRENT |
| 3155 | locs.push_back( |
| 3156 | genLocation(Fortran::parser::FindSourceLocation(outerDoConstruct))); |
| 3157 | const Fortran::parser::LoopControl *loopControl = |
| 3158 | &*outerDoConstruct->GetLoopControl(); |
| 3159 | const auto &concurrent = |
| 3160 | std::get<Fortran::parser::LoopControl::Concurrent>(loopControl->u); |
| 3161 | |
| 3162 | if (!std::get<std::list<Fortran::parser::LocalitySpec>>(concurrent.t) |
| 3163 | .empty()) |
| 3164 | TODO(loc, "DO CONCURRENT with locality spec"); |
| 3165 | |
| 3166 | const auto &concurrentHeader = |
| 3167 | std::get<Fortran::parser::ConcurrentHeader>(concurrent.t); |
| 3168 | const auto &controls = |
| 3169 | std::get<std::list<Fortran::parser::ConcurrentControl>>( |
| 3170 | concurrentHeader.t); |
| 3171 | |
| 3172 | for (const auto &control : controls) { |
| 3173 | mlir::Value lb = fir::getBase(genExprValue( |
| 3174 | *Fortran::semantics::GetExpr(std::get<1>(control.t)), stmtCtx)); |
| 3175 | mlir::Value ub = fir::getBase(genExprValue( |
| 3176 | *Fortran::semantics::GetExpr(std::get<2>(control.t)), stmtCtx)); |
| 3177 | mlir::Value step; |
| 3178 | |
| 3179 | if (const auto &expr = |
| 3180 | std::get<std::optional<Fortran::parser::ScalarIntExpr>>( |
| 3181 | control.t)) |
| 3182 | step = fir::getBase( |
| 3183 | genExprValue(*Fortran::semantics::GetExpr(*expr), stmtCtx)); |
| 3184 | else |
| 3185 | step = builder->create<mlir::arith::ConstantIndexOp>( |
| 3186 | loc, 1); // Use index type directly |
| 3187 | |
| 3188 | // Ensure lb, ub, and step are of index type using fir.convert |
Zhen Wang | d1abbb4 | 2025-03-05 14:50:42 -0800 | [diff] [blame] | 3189 | lb = builder->create<fir::ConvertOp>(loc, idxTy, lb); |
| 3190 | ub = builder->create<fir::ConvertOp>(loc, idxTy, ub); |
| 3191 | step = builder->create<fir::ConvertOp>(loc, idxTy, step); |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3192 | |
| 3193 | lbs.push_back(lb); |
| 3194 | ubs.push_back(ub); |
| 3195 | steps.push_back(step); |
| 3196 | |
| 3197 | const auto &name = std::get<Fortran::parser::Name>(control.t); |
| 3198 | |
| 3199 | // Handle induction variable |
| 3200 | mlir::Value ivValue = getSymbolAddress(*name.symbol); |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3201 | |
| 3202 | if (!ivValue) { |
| 3203 | // DO CONCURRENT induction variables are not mapped yet since they are |
| 3204 | // local to the DO CONCURRENT scope. |
| 3205 | mlir::OpBuilder::InsertPoint insPt = builder->saveInsertionPoint(); |
| 3206 | builder->setInsertionPointToStart(builder->getAllocaBlock()); |
| 3207 | ivValue = builder->createTemporaryAlloc( |
Zhen Wang | d1abbb4 | 2025-03-05 14:50:42 -0800 | [diff] [blame] | 3208 | loc, idxTy, toStringRef(name.symbol->name())); |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3209 | builder->restoreInsertionPoint(insPt); |
| 3210 | } |
| 3211 | |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3212 | // Bind the symbol to the declared variable |
| 3213 | bindSymbol(*name.symbol, ivValue); |
Zhen Wang | 8f0d8d2 | 2025-04-06 19:31:09 -0700 | [diff] [blame] | 3214 | Fortran::lower::SymbolBox hsb = localSymbols.lookupSymbol(*name.symbol); |
| 3215 | fir::ExtendedValue extIvValue = symBoxToExtendedValue(hsb); |
| 3216 | ivValue = fir::getBase(extIvValue); |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3217 | ivValues.push_back(ivValue); |
Zhen Wang | d1abbb4 | 2025-03-05 14:50:42 -0800 | [diff] [blame] | 3218 | ivTypes.push_back(idxTy); |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3219 | ivLocs.push_back(loc); |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3220 | } |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3221 | } else { |
| 3222 | for (unsigned i = 0; i < nestedLoops; ++i) { |
| 3223 | const Fortran::parser::LoopControl *loopControl; |
| 3224 | mlir::Location crtLoc = loc; |
| 3225 | if (i == 0) { |
| 3226 | loopControl = &*outerDoConstruct->GetLoopControl(); |
| 3227 | crtLoc = genLocation( |
| 3228 | Fortran::parser::FindSourceLocation(outerDoConstruct)); |
| 3229 | } else { |
| 3230 | auto *doCons = loopEval->getIf<Fortran::parser::DoConstruct>(); |
| 3231 | assert(doCons && "expect do construct"); |
| 3232 | loopControl = &*doCons->GetLoopControl(); |
| 3233 | crtLoc = genLocation(Fortran::parser::FindSourceLocation(*doCons)); |
| 3234 | } |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3235 | |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3236 | locs.push_back(crtLoc); |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3237 | |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3238 | const Fortran::parser::LoopControl::Bounds *bounds = |
| 3239 | std::get_if<Fortran::parser::LoopControl::Bounds>(&loopControl->u); |
| 3240 | assert(bounds && "Expected bounds on the loop construct"); |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3241 | |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3242 | Fortran::semantics::Symbol &ivSym = |
| 3243 | bounds->name.thing.symbol->GetUltimate(); |
| 3244 | ivValues.push_back(getSymbolAddress(ivSym)); |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3245 | |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3246 | lbs.push_back(builder->createConvert( |
Valentin Clement (バレンタイン クレメン) | 0469bb9 | 2024-12-10 09:48:15 -0800 | [diff] [blame] | 3247 | crtLoc, idxTy, |
| 3248 | fir::getBase(genExprValue( |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3249 | *Fortran::semantics::GetExpr(bounds->lower), stmtCtx)))); |
| 3250 | ubs.push_back(builder->createConvert( |
| 3251 | crtLoc, idxTy, |
| 3252 | fir::getBase(genExprValue( |
| 3253 | *Fortran::semantics::GetExpr(bounds->upper), stmtCtx)))); |
| 3254 | if (bounds->step) |
| 3255 | steps.push_back(builder->createConvert( |
| 3256 | crtLoc, idxTy, |
| 3257 | fir::getBase(genExprValue( |
| 3258 | *Fortran::semantics::GetExpr(bounds->step), stmtCtx)))); |
| 3259 | else // If `step` is not present, assume it is `1`. |
| 3260 | steps.push_back(builder->createIntegerConstant(loc, idxTy, 1)); |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3261 | |
Zhen Wang | a67566b | 2025-02-20 14:05:44 -0800 | [diff] [blame] | 3262 | ivTypes.push_back(idxTy); |
| 3263 | ivLocs.push_back(crtLoc); |
| 3264 | if (i < nestedLoops - 1) |
| 3265 | loopEval = &*std::next(loopEval->getNestedEvaluations().begin()); |
| 3266 | } |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3267 | } |
| 3268 | |
Iman Hosseini | 7665d3d | 2024-06-12 19:18:41 +0100 | [diff] [blame] | 3269 | auto op = builder->create<cuf::KernelOp>( |
| 3270 | loc, gridValues, blockValues, streamValue, lbs, ubs, steps, n, |
| 3271 | mlir::ValueRange(reduceOperands), builder->getArrayAttr(reduceAttrs)); |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3272 | builder->createBlock(&op.getRegion(), op.getRegion().end(), ivTypes, |
| 3273 | ivLocs); |
| 3274 | mlir::Block &b = op.getRegion().back(); |
| 3275 | builder->setInsertionPointToStart(&b); |
| 3276 | |
Valentin Clement (バレンタイン クレメン) | c81b430 | 2024-09-04 08:43:13 -0700 | [diff] [blame] | 3277 | Fortran::lower::pft::Evaluation *crtEval = &getEval(); |
| 3278 | if (crtEval->lowerAsUnstructured()) |
| 3279 | Fortran::lower::createEmptyRegionBlocks<fir::FirEndOp>( |
| 3280 | *builder, crtEval->getNestedEvaluations()); |
| 3281 | builder->setInsertionPointToStart(&b); |
| 3282 | |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3283 | for (auto [arg, value] : llvm::zip( |
| 3284 | op.getLoopRegions().front()->front().getArguments(), ivValues)) { |
| 3285 | mlir::Value convArg = |
| 3286 | builder->createConvert(loc, fir::unwrapRefType(value.getType()), arg); |
| 3287 | builder->create<fir::StoreOp>(loc, convArg, value); |
| 3288 | } |
| 3289 | |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3290 | if (crtEval->lowerAsStructured()) { |
| 3291 | crtEval = &crtEval->getFirstNestedEvaluation(); |
| 3292 | for (int64_t i = 1; i < nestedLoops; i++) |
| 3293 | crtEval = &*std::next(crtEval->getNestedEvaluations().begin()); |
| 3294 | } |
| 3295 | |
| 3296 | // Generate loop body |
| 3297 | for (Fortran::lower::pft::Evaluation &e : crtEval->getNestedEvaluations()) |
| 3298 | genFIR(e); |
| 3299 | |
Valentin Clement (バレンタイン クレメン) | f815d1f | 2024-04-30 08:27:28 -0700 | [diff] [blame] | 3300 | builder->create<fir::FirEndOp>(loc); |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3301 | builder->setInsertionPointAfter(op); |
Valentin Clement (バレンタイン クレメン) | b3189b1 | 2024-02-27 11:23:17 -0800 | [diff] [blame] | 3302 | } |
| 3303 | |
Shraiysh Vaishay | e0f549a | 2022-03-10 22:40:23 +0530 | [diff] [blame] | 3304 | void genFIR(const Fortran::parser::OpenMPConstruct &omp) { |
| 3305 | mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); |
Krzysztof Parzyszek | aeb4821 | 2023-12-15 09:01:08 -0600 | [diff] [blame] | 3306 | genOpenMPConstruct(*this, localSymbols, bridge.getSemanticsContext(), |
| 3307 | getEval(), omp); |
Shraiysh Vaishay | e0f549a | 2022-03-10 22:40:23 +0530 | [diff] [blame] | 3308 | builder->restoreInsertionPoint(insertPt); |
Sergio Afonso | 29aa749 | 2023-03-29 18:13:48 +0100 | [diff] [blame] | 3309 | |
| 3310 | // Register if a target region was found |
| 3311 | ompDeviceCodeFound = |
| 3312 | ompDeviceCodeFound || Fortran::lower::isOpenMPTargetConstruct(omp); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3313 | } |
| 3314 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 3315 | void genFIR(const Fortran::parser::OpenMPDeclarativeConstruct &ompDecl) { |
Peixin-Qiao | b6b8d34 | 2022-04-28 09:40:30 +0800 | [diff] [blame] | 3316 | mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); |
Sergio Afonso | 29aa749 | 2023-03-29 18:13:48 +0100 | [diff] [blame] | 3317 | // Register if a declare target construct intended for a target device was |
| 3318 | // found |
| 3319 | ompDeviceCodeFound = |
| 3320 | ompDeviceCodeFound || |
Krzysztof Parzyszek | 1af073a | 2024-02-12 19:15:55 -0600 | [diff] [blame] | 3321 | Fortran::lower::isOpenMPDeviceDeclareTarget( |
| 3322 | *this, bridge.getSemanticsContext(), getEval(), ompDecl); |
agozillon | afb05cd | 2024-03-05 17:27:16 +0100 | [diff] [blame] | 3323 | Fortran::lower::gatherOpenMPDeferredDeclareTargets( |
| 3324 | *this, bridge.getSemanticsContext(), getEval(), ompDecl, |
| 3325 | ompDeferredDeclareTarget); |
Krzysztof Parzyszek | c5a9e35 | 2024-01-15 08:01:41 -0600 | [diff] [blame] | 3326 | genOpenMPDeclarativeConstruct( |
| 3327 | *this, localSymbols, bridge.getSemanticsContext(), getEval(), ompDecl); |
Peixin-Qiao | b6b8d34 | 2022-04-28 09:40:30 +0800 | [diff] [blame] | 3328 | builder->restoreInsertionPoint(insertPt); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3329 | } |
| 3330 | |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3331 | /// Generate FIR for a SELECT CASE statement. |
Peter Klausler | fc97d2e | 2024-12-18 07:02:37 -0800 | [diff] [blame] | 3332 | /// The selector may have CHARACTER, INTEGER, UNSIGNED, or LOGICAL type. |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3333 | void genFIR(const Fortran::parser::SelectCaseStmt &stmt) { |
| 3334 | Fortran::lower::pft::Evaluation &eval = getEval(); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3335 | Fortran::lower::pft::Evaluation *parentConstruct = eval.parentConstruct; |
| 3336 | assert(!activeConstructStack.empty() && |
| 3337 | &activeConstructStack.back().eval == parentConstruct && |
| 3338 | "select case construct is not active"); |
| 3339 | Fortran::lower::StatementContext &stmtCtx = |
| 3340 | activeConstructStack.back().stmtCtx; |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3341 | const Fortran::lower::SomeExpr *expr = Fortran::semantics::GetExpr( |
| 3342 | std::get<Fortran::parser::Scalar<Fortran::parser::Expr>>(stmt.t)); |
| 3343 | bool isCharSelector = isCharacterCategory(expr->GetType()->category()); |
| 3344 | bool isLogicalSelector = isLogicalCategory(expr->GetType()->category()); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3345 | mlir::MLIRContext *context = builder->getContext(); |
| 3346 | mlir::Location loc = toLocation(); |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3347 | auto charValue = [&](const Fortran::lower::SomeExpr *expr) { |
| 3348 | fir::ExtendedValue exv = genExprAddr(*expr, stmtCtx, &loc); |
| 3349 | return exv.match( |
| 3350 | [&](const fir::CharBoxValue &cbv) { |
| 3351 | return fir::factory::CharacterExprHelper{*builder, loc} |
| 3352 | .createEmboxChar(cbv.getAddr(), cbv.getLen()); |
| 3353 | }, |
| 3354 | [&](auto) { |
| 3355 | fir::emitFatalError(loc, "not a character"); |
| 3356 | return mlir::Value{}; |
| 3357 | }); |
| 3358 | }; |
| 3359 | mlir::Value selector; |
| 3360 | if (isCharSelector) { |
| 3361 | selector = charValue(expr); |
| 3362 | } else { |
| 3363 | selector = createFIRExpr(loc, expr, stmtCtx); |
| 3364 | if (isLogicalSelector) |
| 3365 | selector = builder->createConvert(loc, builder->getI1Type(), selector); |
| 3366 | } |
| 3367 | mlir::Type selectType = selector.getType(); |
Peter Klausler | fc97d2e | 2024-12-18 07:02:37 -0800 | [diff] [blame] | 3368 | if (selectType.isUnsignedInteger()) |
| 3369 | selectType = mlir::IntegerType::get( |
| 3370 | builder->getContext(), selectType.getIntOrFloatBitWidth(), |
| 3371 | mlir::IntegerType::SignednessSemantics::Signless); |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3372 | llvm::SmallVector<mlir::Attribute> attrList; |
| 3373 | llvm::SmallVector<mlir::Value> valueList; |
| 3374 | llvm::SmallVector<mlir::Block *> blockList; |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3375 | mlir::Block *defaultBlock = parentConstruct->constructExit->block; |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3376 | using CaseValue = Fortran::parser::Scalar<Fortran::parser::ConstantExpr>; |
| 3377 | auto addValue = [&](const CaseValue &caseValue) { |
| 3378 | const Fortran::lower::SomeExpr *expr = |
| 3379 | Fortran::semantics::GetExpr(caseValue.thing); |
| 3380 | if (isCharSelector) |
| 3381 | valueList.push_back(charValue(expr)); |
| 3382 | else if (isLogicalSelector) |
| 3383 | valueList.push_back(builder->createConvert( |
| 3384 | loc, selectType, createFIRExpr(toLocation(), expr, stmtCtx))); |
Peter Klausler | fc97d2e | 2024-12-18 07:02:37 -0800 | [diff] [blame] | 3385 | else { |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3386 | valueList.push_back(builder->createIntegerConstant( |
| 3387 | loc, selectType, *Fortran::evaluate::ToInt64(*expr))); |
Peter Klausler | fc97d2e | 2024-12-18 07:02:37 -0800 | [diff] [blame] | 3388 | } |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3389 | }; |
| 3390 | for (Fortran::lower::pft::Evaluation *e = eval.controlSuccessor; e; |
| 3391 | e = e->controlSuccessor) { |
| 3392 | const auto &caseStmt = e->getIf<Fortran::parser::CaseStmt>(); |
| 3393 | assert(e->block && "missing CaseStmt block"); |
| 3394 | const auto &caseSelector = |
| 3395 | std::get<Fortran::parser::CaseSelector>(caseStmt->t); |
| 3396 | const auto *caseValueRangeList = |
| 3397 | std::get_if<std::list<Fortran::parser::CaseValueRange>>( |
| 3398 | &caseSelector.u); |
| 3399 | if (!caseValueRangeList) { |
| 3400 | defaultBlock = e->block; |
| 3401 | continue; |
| 3402 | } |
| 3403 | for (const Fortran::parser::CaseValueRange &caseValueRange : |
| 3404 | *caseValueRangeList) { |
| 3405 | blockList.push_back(e->block); |
| 3406 | if (const auto *caseValue = std::get_if<CaseValue>(&caseValueRange.u)) { |
| 3407 | attrList.push_back(fir::PointIntervalAttr::get(context)); |
| 3408 | addValue(*caseValue); |
| 3409 | continue; |
| 3410 | } |
| 3411 | const auto &caseRange = |
| 3412 | std::get<Fortran::parser::CaseValueRange::Range>(caseValueRange.u); |
| 3413 | if (caseRange.lower && caseRange.upper) { |
| 3414 | attrList.push_back(fir::ClosedIntervalAttr::get(context)); |
| 3415 | addValue(*caseRange.lower); |
| 3416 | addValue(*caseRange.upper); |
| 3417 | } else if (caseRange.lower) { |
| 3418 | attrList.push_back(fir::LowerBoundAttr::get(context)); |
| 3419 | addValue(*caseRange.lower); |
| 3420 | } else { |
| 3421 | attrList.push_back(fir::UpperBoundAttr::get(context)); |
| 3422 | addValue(*caseRange.upper); |
| 3423 | } |
| 3424 | } |
| 3425 | } |
| 3426 | // Skip a logical default block that can never be referenced. |
| 3427 | if (isLogicalSelector && attrList.size() == 2) |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3428 | defaultBlock = parentConstruct->constructExit->block; |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3429 | attrList.push_back(mlir::UnitAttr::get(context)); |
| 3430 | blockList.push_back(defaultBlock); |
| 3431 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3432 | // Generate a fir::SelectCaseOp. Explicit branch code is better for the |
| 3433 | // LOGICAL type. The CHARACTER type does not have downstream SelectOp |
| 3434 | // support. The -no-structured-fir option can be used to force generation |
| 3435 | // of INTEGER type branch code. |
| 3436 | if (!isLogicalSelector && !isCharSelector && |
| 3437 | !getEval().forceAsUnstructured()) { |
| 3438 | // The selector is in an ssa register. Any temps that may have been |
| 3439 | // generated while evaluating it can be cleaned up now. |
| 3440 | stmtCtx.finalizeAndReset(); |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3441 | builder->create<fir::SelectCaseOp>(loc, selector, attrList, valueList, |
| 3442 | blockList); |
| 3443 | return; |
| 3444 | } |
| 3445 | |
| 3446 | // Generate a sequence of case value comparisons and branches. |
| 3447 | auto caseValue = valueList.begin(); |
| 3448 | auto caseBlock = blockList.begin(); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3449 | for (mlir::Attribute attr : attrList) { |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 3450 | if (mlir::isa<mlir::UnitAttr>(attr)) { |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3451 | genBranch(*caseBlock++); |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3452 | break; |
| 3453 | } |
| 3454 | auto genCond = [&](mlir::Value rhs, |
| 3455 | mlir::arith::CmpIPredicate pred) -> mlir::Value { |
| 3456 | if (!isCharSelector) |
| 3457 | return builder->create<mlir::arith::CmpIOp>(loc, pred, selector, rhs); |
| 3458 | fir::factory::CharacterExprHelper charHelper{*builder, loc}; |
| 3459 | std::pair<mlir::Value, mlir::Value> lhsVal = |
| 3460 | charHelper.createUnboxChar(selector); |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3461 | std::pair<mlir::Value, mlir::Value> rhsVal = |
| 3462 | charHelper.createUnboxChar(rhs); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3463 | return fir::runtime::genCharCompare(*builder, loc, pred, lhsVal.first, |
| 3464 | lhsVal.second, rhsVal.first, |
| 3465 | rhsVal.second); |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3466 | }; |
| 3467 | mlir::Block *newBlock = insertBlock(*caseBlock); |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 3468 | if (mlir::isa<fir::ClosedIntervalAttr>(attr)) { |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3469 | mlir::Block *newBlock2 = insertBlock(*caseBlock); |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3470 | mlir::Value cond = |
| 3471 | genCond(*caseValue++, mlir::arith::CmpIPredicate::sge); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3472 | genConditionalBranch(cond, newBlock, newBlock2); |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3473 | builder->setInsertionPointToEnd(newBlock); |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3474 | mlir::Value cond2 = |
| 3475 | genCond(*caseValue++, mlir::arith::CmpIPredicate::sle); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3476 | genConditionalBranch(cond2, *caseBlock++, newBlock2); |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3477 | builder->setInsertionPointToEnd(newBlock2); |
| 3478 | continue; |
| 3479 | } |
| 3480 | mlir::arith::CmpIPredicate pred; |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 3481 | if (mlir::isa<fir::PointIntervalAttr>(attr)) { |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3482 | pred = mlir::arith::CmpIPredicate::eq; |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 3483 | } else if (mlir::isa<fir::LowerBoundAttr>(attr)) { |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3484 | pred = mlir::arith::CmpIPredicate::sge; |
| 3485 | } else { |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 3486 | assert(mlir::isa<fir::UpperBoundAttr>(attr) && "unexpected predicate"); |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3487 | pred = mlir::arith::CmpIPredicate::sle; |
| 3488 | } |
| 3489 | mlir::Value cond = genCond(*caseValue++, pred); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3490 | genConditionalBranch(cond, *caseBlock++, newBlock); |
Valentin Clement | 308fc3f | 2022-03-18 15:39:57 +0100 | [diff] [blame] | 3491 | builder->setInsertionPointToEnd(newBlock); |
| 3492 | } |
| 3493 | assert(caseValue == valueList.end() && caseBlock == blockList.end() && |
| 3494 | "select case list mismatch"); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3495 | } |
| 3496 | |
Valentin Clement | b3eb0e1 | 2022-03-08 18:47:28 +0100 | [diff] [blame] | 3497 | fir::ExtendedValue |
| 3498 | genAssociateSelector(const Fortran::lower::SomeExpr &selector, |
| 3499 | Fortran::lower::StatementContext &stmtCtx) { |
Jean Perier | e5921ef | 2023-02-27 09:05:11 +0100 | [diff] [blame] | 3500 | if (lowerToHighLevelFIR()) |
| 3501 | return genExprAddr(selector, stmtCtx); |
Eric Schweitz | 1bffc75 | 2022-04-22 13:59:17 -0700 | [diff] [blame] | 3502 | return Fortran::lower::isArraySectionWithoutVectorSubscript(selector) |
Valentin Clement | b3eb0e1 | 2022-03-08 18:47:28 +0100 | [diff] [blame] | 3503 | ? Fortran::lower::createSomeArrayBox(*this, selector, |
| 3504 | localSymbols, stmtCtx) |
| 3505 | : genExprAddr(selector, stmtCtx); |
| 3506 | } |
| 3507 | |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3508 | void genFIR(const Fortran::parser::AssociateConstruct &) { |
Valentin Clement | a49bf0a | 2022-03-08 22:08:02 +0100 | [diff] [blame] | 3509 | Fortran::lower::pft::Evaluation &eval = getEval(); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3510 | Fortran::lower::StatementContext stmtCtx; |
| 3511 | pushActiveConstruct(eval, stmtCtx); |
Valentin Clement | a49bf0a | 2022-03-08 22:08:02 +0100 | [diff] [blame] | 3512 | for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) { |
vdonaldson | cda8270 | 2024-05-03 09:11:10 -0400 | [diff] [blame] | 3513 | setCurrentPosition(e.position); |
Valentin Clement | a49bf0a | 2022-03-08 22:08:02 +0100 | [diff] [blame] | 3514 | if (auto *stmt = e.getIf<Fortran::parser::AssociateStmt>()) { |
| 3515 | if (eval.lowerAsUnstructured()) |
| 3516 | maybeStartBlock(e.block); |
| 3517 | localSymbols.pushScope(); |
| 3518 | for (const Fortran::parser::Association &assoc : |
| 3519 | std::get<std::list<Fortran::parser::Association>>(stmt->t)) { |
| 3520 | Fortran::semantics::Symbol &sym = |
| 3521 | *std::get<Fortran::parser::Name>(assoc.t).symbol; |
| 3522 | const Fortran::lower::SomeExpr &selector = |
| 3523 | *sym.get<Fortran::semantics::AssocEntityDetails>().expr(); |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 3524 | addSymbol(sym, genAssociateSelector(selector, stmtCtx)); |
Valentin Clement | a49bf0a | 2022-03-08 22:08:02 +0100 | [diff] [blame] | 3525 | } |
| 3526 | } else if (e.getIf<Fortran::parser::EndAssociateStmt>()) { |
| 3527 | if (eval.lowerAsUnstructured()) |
| 3528 | maybeStartBlock(e.block); |
Valentin Clement | a49bf0a | 2022-03-08 22:08:02 +0100 | [diff] [blame] | 3529 | localSymbols.popScope(); |
| 3530 | } else { |
| 3531 | genFIR(e); |
| 3532 | } |
| 3533 | } |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3534 | popActiveConstruct(); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3535 | } |
| 3536 | |
| 3537 | void genFIR(const Fortran::parser::BlockConstruct &blockConstruct) { |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3538 | Fortran::lower::pft::Evaluation &eval = getEval(); |
| 3539 | Fortran::lower::StatementContext stmtCtx; |
| 3540 | pushActiveConstruct(eval, stmtCtx); |
| 3541 | for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) { |
vdonaldson | cda8270 | 2024-05-03 09:11:10 -0400 | [diff] [blame] | 3542 | setCurrentPosition(e.position); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3543 | if (e.getIf<Fortran::parser::BlockStmt>()) { |
| 3544 | if (eval.lowerAsUnstructured()) |
| 3545 | maybeStartBlock(e.block); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3546 | const Fortran::parser::CharBlock &endPosition = |
| 3547 | eval.getLastNestedEvaluation().position; |
| 3548 | localSymbols.pushScope(); |
Tom Eccles | 5aaf384b | 2024-09-16 12:33:37 +0100 | [diff] [blame] | 3549 | mlir::Value stackPtr = builder->genStackSave(toLocation()); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3550 | mlir::Location endLoc = genLocation(endPosition); |
Tom Eccles | 5aaf384b | 2024-09-16 12:33:37 +0100 | [diff] [blame] | 3551 | stmtCtx.attachCleanup( |
| 3552 | [=]() { builder->genStackRestore(endLoc, stackPtr); }); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3553 | Fortran::semantics::Scope &scope = |
| 3554 | bridge.getSemanticsContext().FindScope(endPosition); |
| 3555 | scopeBlockIdMap.try_emplace(&scope, ++blockId); |
| 3556 | Fortran::lower::AggregateStoreMap storeMap; |
| 3557 | for (const Fortran::lower::pft::Variable &var : |
jeanPerier | bfcd053 | 2023-10-17 09:11:53 +0200 | [diff] [blame] | 3558 | Fortran::lower::pft::getScopeVariableList(scope)) { |
| 3559 | // Do no instantiate again variables from the block host |
| 3560 | // that appears in specification of block variables. |
| 3561 | if (!var.hasSymbol() || !lookupSymbol(var.getSymbol())) |
| 3562 | instantiateVar(var, storeMap); |
| 3563 | } |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3564 | } else if (e.getIf<Fortran::parser::EndBlockStmt>()) { |
| 3565 | if (eval.lowerAsUnstructured()) |
| 3566 | maybeStartBlock(e.block); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3567 | localSymbols.popScope(); |
| 3568 | } else { |
| 3569 | genFIR(e); |
| 3570 | } |
| 3571 | } |
| 3572 | popActiveConstruct(); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3573 | } |
| 3574 | |
| 3575 | void genFIR(const Fortran::parser::ChangeTeamConstruct &construct) { |
Pete Steinfeld | 5db4779 | 2023-10-16 12:37:57 -0700 | [diff] [blame] | 3576 | TODO(toLocation(), "coarray: ChangeTeamConstruct"); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3577 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3578 | void genFIR(const Fortran::parser::ChangeTeamStmt &stmt) { |
Pete Steinfeld | 5db4779 | 2023-10-16 12:37:57 -0700 | [diff] [blame] | 3579 | TODO(toLocation(), "coarray: ChangeTeamStmt"); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3580 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3581 | void genFIR(const Fortran::parser::EndChangeTeamStmt &stmt) { |
Pete Steinfeld | 5db4779 | 2023-10-16 12:37:57 -0700 | [diff] [blame] | 3582 | TODO(toLocation(), "coarray: EndChangeTeamStmt"); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3583 | } |
| 3584 | |
| 3585 | void genFIR(const Fortran::parser::CriticalConstruct &criticalConstruct) { |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 3586 | setCurrentPositionAt(criticalConstruct); |
Pete Steinfeld | 5db4779 | 2023-10-16 12:37:57 -0700 | [diff] [blame] | 3587 | TODO(toLocation(), "coarray: CriticalConstruct"); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3588 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3589 | void genFIR(const Fortran::parser::CriticalStmt &) { |
Pete Steinfeld | 5db4779 | 2023-10-16 12:37:57 -0700 | [diff] [blame] | 3590 | TODO(toLocation(), "coarray: CriticalStmt"); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3591 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3592 | void genFIR(const Fortran::parser::EndCriticalStmt &) { |
Pete Steinfeld | 5db4779 | 2023-10-16 12:37:57 -0700 | [diff] [blame] | 3593 | TODO(toLocation(), "coarray: EndCriticalStmt"); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3594 | } |
| 3595 | |
| 3596 | void genFIR(const Fortran::parser::SelectRankConstruct &selectRankConstruct) { |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 3597 | setCurrentPositionAt(selectRankConstruct); |
jeanPerier | d1aa9ba | 2024-06-03 17:20:07 +0200 | [diff] [blame] | 3598 | genCaseOrRankConstruct(); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3599 | } |
jeanPerier | d1aa9ba | 2024-06-03 17:20:07 +0200 | [diff] [blame] | 3600 | |
| 3601 | void genFIR(const Fortran::parser::SelectRankStmt &selectRankStmt) { |
| 3602 | // Generate a fir.select_case with the selector rank. The RANK(*) case, |
| 3603 | // if any, is handles with a conditional branch before the fir.select_case. |
| 3604 | mlir::Type rankType = builder->getIntegerType(8); |
| 3605 | mlir::MLIRContext *context = builder->getContext(); |
| 3606 | mlir::Location loc = toLocation(); |
| 3607 | // Build block list for fir.select_case, and identify RANK(*) block, if any. |
| 3608 | // Default block must be placed last in the fir.select_case block list. |
| 3609 | mlir::Block *rankStarBlock = nullptr; |
| 3610 | Fortran::lower::pft::Evaluation &eval = getEval(); |
| 3611 | mlir::Block *defaultBlock = eval.parentConstruct->constructExit->block; |
| 3612 | llvm::SmallVector<mlir::Attribute> attrList; |
| 3613 | llvm::SmallVector<mlir::Value> valueList; |
| 3614 | llvm::SmallVector<mlir::Block *> blockList; |
| 3615 | for (Fortran::lower::pft::Evaluation *e = eval.controlSuccessor; e; |
| 3616 | e = e->controlSuccessor) { |
| 3617 | if (const auto *rankCaseStmt = |
| 3618 | e->getIf<Fortran::parser::SelectRankCaseStmt>()) { |
| 3619 | const auto &rank = std::get<Fortran::parser::SelectRankCaseStmt::Rank>( |
| 3620 | rankCaseStmt->t); |
| 3621 | assert(e->block && "missing SelectRankCaseStmt block"); |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 3622 | Fortran::common::visit( |
jeanPerier | d1aa9ba | 2024-06-03 17:20:07 +0200 | [diff] [blame] | 3623 | Fortran::common::visitors{ |
| 3624 | [&](const Fortran::parser::ScalarIntConstantExpr &rankExpr) { |
| 3625 | blockList.emplace_back(e->block); |
| 3626 | attrList.emplace_back(fir::PointIntervalAttr::get(context)); |
| 3627 | std::optional<std::int64_t> rankCst = |
| 3628 | Fortran::evaluate::ToInt64( |
| 3629 | Fortran::semantics::GetExpr(rankExpr)); |
| 3630 | assert(rankCst.has_value() && |
| 3631 | "rank expr must be constant integer"); |
| 3632 | valueList.emplace_back( |
| 3633 | builder->createIntegerConstant(loc, rankType, *rankCst)); |
| 3634 | }, |
| 3635 | [&](const Fortran::parser::Star &) { |
| 3636 | rankStarBlock = e->block; |
| 3637 | }, |
| 3638 | [&](const Fortran::parser::Default &) { |
| 3639 | defaultBlock = e->block; |
| 3640 | }}, |
| 3641 | rank.u); |
| 3642 | } |
| 3643 | } |
| 3644 | attrList.push_back(mlir::UnitAttr::get(context)); |
| 3645 | blockList.push_back(defaultBlock); |
| 3646 | |
| 3647 | // Lower selector. |
| 3648 | assert(!activeConstructStack.empty() && "must be inside construct"); |
| 3649 | assert(!activeConstructStack.back().selector && |
| 3650 | "selector should not yet be set"); |
| 3651 | Fortran::lower::StatementContext &stmtCtx = |
| 3652 | activeConstructStack.back().stmtCtx; |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 3653 | const Fortran::lower::SomeExpr *selectorExpr = Fortran::common::visit( |
| 3654 | [](const auto &x) { return Fortran::semantics::GetExpr(x); }, |
| 3655 | std::get<Fortran::parser::Selector>(selectRankStmt.t).u); |
jeanPerier | d1aa9ba | 2024-06-03 17:20:07 +0200 | [diff] [blame] | 3656 | assert(selectorExpr && "failed to retrieve selector expr"); |
| 3657 | hlfir::Entity selector = Fortran::lower::convertExprToHLFIR( |
| 3658 | loc, *this, *selectorExpr, localSymbols, stmtCtx); |
| 3659 | activeConstructStack.back().selector = selector; |
| 3660 | |
| 3661 | // Deal with assumed-size first. They must fall into RANK(*) if present, or |
| 3662 | // the default case (F'2023 11.1.10.2.). The selector cannot be an |
| 3663 | // assumed-size if it is allocatable or pointer, so the check is skipped. |
| 3664 | if (!Fortran::evaluate::IsAllocatableOrPointerObject(*selectorExpr)) { |
| 3665 | mlir::Value isAssumedSize = builder->create<fir::IsAssumedSizeOp>( |
| 3666 | loc, builder->getI1Type(), selector); |
| 3667 | // Create new block to hold the fir.select_case for the non assumed-size |
| 3668 | // cases. |
| 3669 | mlir::Block *selectCaseBlock = insertBlock(blockList[0]); |
| 3670 | mlir::Block *assumedSizeBlock = |
| 3671 | rankStarBlock ? rankStarBlock : defaultBlock; |
| 3672 | builder->create<mlir::cf::CondBranchOp>(loc, isAssumedSize, |
| 3673 | assumedSizeBlock, std::nullopt, |
| 3674 | selectCaseBlock, std::nullopt); |
| 3675 | startBlock(selectCaseBlock); |
| 3676 | } |
| 3677 | // Create fir.select_case for the other rank cases. |
| 3678 | mlir::Value rank = builder->create<fir::BoxRankOp>(loc, rankType, selector); |
| 3679 | stmtCtx.finalizeAndReset(); |
| 3680 | builder->create<fir::SelectCaseOp>(loc, rank, attrList, valueList, |
| 3681 | blockList); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3682 | } |
jeanPerier | d1aa9ba | 2024-06-03 17:20:07 +0200 | [diff] [blame] | 3683 | |
| 3684 | // Get associating entity symbol inside case statement scope. |
| 3685 | static const Fortran::semantics::Symbol & |
| 3686 | getAssociatingEntitySymbol(const Fortran::semantics::Scope &scope) { |
| 3687 | const Fortran::semantics::Symbol *assocSym = nullptr; |
| 3688 | for (const auto &sym : scope.GetSymbols()) { |
| 3689 | if (sym->has<Fortran::semantics::AssocEntityDetails>()) { |
| 3690 | assert(!assocSym && |
| 3691 | "expect only one associating entity symbol in this scope"); |
| 3692 | assocSym = &*sym; |
| 3693 | } |
| 3694 | } |
| 3695 | assert(assocSym && "should contain associating entity symbol"); |
| 3696 | return *assocSym; |
| 3697 | } |
| 3698 | |
| 3699 | void genFIR(const Fortran::parser::SelectRankCaseStmt &stmt) { |
| 3700 | assert(!activeConstructStack.empty() && |
| 3701 | "must be inside select rank construct"); |
| 3702 | // Pop previous associating entity mapping, if any, and push scope for new |
| 3703 | // mapping. |
| 3704 | if (activeConstructStack.back().pushedScope) |
| 3705 | localSymbols.popScope(); |
| 3706 | localSymbols.pushScope(); |
| 3707 | activeConstructStack.back().pushedScope = true; |
| 3708 | const Fortran::semantics::Symbol &assocEntitySymbol = |
| 3709 | getAssociatingEntitySymbol( |
| 3710 | bridge.getSemanticsContext().FindScope(getEval().position)); |
| 3711 | const auto &details = |
| 3712 | assocEntitySymbol.get<Fortran::semantics::AssocEntityDetails>(); |
| 3713 | assert(!activeConstructStack.empty() && |
| 3714 | activeConstructStack.back().selector.has_value() && |
| 3715 | "selector must have been created"); |
| 3716 | // Get lowered value for the selector. |
| 3717 | hlfir::Entity selector = *activeConstructStack.back().selector; |
| 3718 | assert(selector.isVariable() && "assumed-rank selector are variables"); |
| 3719 | // Cook selector mlir::Value according to rank case and map it to |
| 3720 | // associating entity symbol. |
| 3721 | Fortran::lower::StatementContext stmtCtx; |
| 3722 | mlir::Location loc = toLocation(); |
| 3723 | if (details.IsAssumedRank()) { |
| 3724 | fir::ExtendedValue selectorExv = Fortran::lower::translateToExtendedValue( |
| 3725 | loc, *builder, selector, stmtCtx); |
| 3726 | addSymbol(assocEntitySymbol, selectorExv); |
| 3727 | } else if (details.IsAssumedSize()) { |
| 3728 | // Create rank-1 assumed-size from descriptor. Assumed-size are contiguous |
| 3729 | // so a new entity can be built from scratch using the base address, type |
| 3730 | // parameters and dynamic type. The selector cannot be a |
| 3731 | // POINTER/ALLOCATBLE as per F'2023 C1160. |
| 3732 | fir::ExtendedValue newExv; |
| 3733 | llvm::SmallVector assumeSizeExtents{ |
| 3734 | builder->createMinusOneInteger(loc, builder->getIndexType())}; |
| 3735 | mlir::Value baseAddr = |
| 3736 | hlfir::genVariableRawAddress(loc, *builder, selector); |
| 3737 | mlir::Type eleType = |
| 3738 | fir::unwrapSequenceType(fir::unwrapRefType(baseAddr.getType())); |
| 3739 | mlir::Type rank1Type = |
| 3740 | fir::ReferenceType::get(builder->getVarLenSeqTy(eleType, 1)); |
| 3741 | baseAddr = builder->createConvert(loc, rank1Type, baseAddr); |
| 3742 | if (selector.isCharacter()) { |
| 3743 | mlir::Value len = hlfir::genCharLength(loc, *builder, selector); |
| 3744 | newExv = fir::CharArrayBoxValue{baseAddr, len, assumeSizeExtents}; |
| 3745 | } else if (selector.isDerivedWithLengthParameters()) { |
| 3746 | TODO(loc, "RANK(*) with parameterized derived type selector"); |
| 3747 | } else if (selector.isPolymorphic()) { |
| 3748 | TODO(loc, "RANK(*) with polymorphic selector"); |
| 3749 | } else { |
| 3750 | // Simple intrinsic or derived type. |
| 3751 | newExv = fir::ArrayBoxValue{baseAddr, assumeSizeExtents}; |
| 3752 | } |
| 3753 | addSymbol(assocEntitySymbol, newExv); |
| 3754 | } else { |
| 3755 | int rank = details.rank().value(); |
| 3756 | auto boxTy = |
| 3757 | mlir::cast<fir::BaseBoxType>(fir::unwrapRefType(selector.getType())); |
| 3758 | mlir::Type newBoxType = boxTy.getBoxTypeWithNewShape(rank); |
| 3759 | if (fir::isa_ref_type(selector.getType())) |
| 3760 | newBoxType = fir::ReferenceType::get(newBoxType); |
| 3761 | // Give rank info to value via cast, and get rid of the box if not needed |
| 3762 | // (simple scalars, contiguous arrays... This is done by |
| 3763 | // translateVariableToExtendedValue). |
| 3764 | hlfir::Entity rankedBox{ |
| 3765 | builder->createConvert(loc, newBoxType, selector)}; |
| 3766 | bool isSimplyContiguous = Fortran::evaluate::IsSimplyContiguous( |
| 3767 | assocEntitySymbol, getFoldingContext()); |
| 3768 | fir::ExtendedValue newExv = Fortran::lower::translateToExtendedValue( |
| 3769 | loc, *builder, rankedBox, stmtCtx, isSimplyContiguous); |
| 3770 | |
| 3771 | // Non deferred length parameters of character allocatable/pointer |
| 3772 | // MutableBoxValue should be properly set before binding it to a symbol in |
| 3773 | // order to get correct assignment semantics. |
| 3774 | if (const fir::MutableBoxValue *mutableBox = |
| 3775 | newExv.getBoxOf<fir::MutableBoxValue>()) { |
| 3776 | if (selector.isCharacter()) { |
| 3777 | auto dynamicType = |
| 3778 | Fortran::evaluate::DynamicType::From(assocEntitySymbol); |
| 3779 | if (!dynamicType.value().HasDeferredTypeParameter()) { |
| 3780 | llvm::SmallVector<mlir::Value> lengthParams; |
| 3781 | hlfir::genLengthParameters(loc, *builder, selector, lengthParams); |
| 3782 | newExv = fir::MutableBoxValue{rankedBox, lengthParams, |
| 3783 | mutableBox->getMutableProperties()}; |
| 3784 | } |
| 3785 | } |
| 3786 | } |
| 3787 | addSymbol(assocEntitySymbol, newExv); |
| 3788 | } |
| 3789 | // Statements inside rank case are lowered by SelectRankConstruct visit. |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 3790 | } |
| 3791 | |
| 3792 | void genFIR(const Fortran::parser::SelectTypeConstruct &selectTypeConstruct) { |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3793 | mlir::MLIRContext *context = builder->getContext(); |
| 3794 | Fortran::lower::StatementContext stmtCtx; |
| 3795 | fir::ExtendedValue selector; |
| 3796 | llvm::SmallVector<mlir::Attribute> attrList; |
| 3797 | llvm::SmallVector<mlir::Block *> blockList; |
| 3798 | unsigned typeGuardIdx = 0; |
Valentin Clement | a459a24 | 2023-01-19 17:32:02 +0100 | [diff] [blame] | 3799 | std::size_t defaultAttrPos = std::numeric_limits<size_t>::max(); |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3800 | bool hasLocalScope = false; |
Valentin Clement | b0de872 | 2023-02-16 09:05:12 +0100 | [diff] [blame] | 3801 | llvm::SmallVector<const Fortran::semantics::Scope *> typeCaseScopes; |
| 3802 | |
| 3803 | const auto &typeCaseList = |
| 3804 | std::get<std::list<Fortran::parser::SelectTypeConstruct::TypeCase>>( |
| 3805 | selectTypeConstruct.t); |
| 3806 | for (const auto &typeCase : typeCaseList) { |
| 3807 | const auto &stmt = |
| 3808 | std::get<Fortran::parser::Statement<Fortran::parser::TypeGuardStmt>>( |
| 3809 | typeCase.t); |
| 3810 | const Fortran::semantics::Scope &scope = |
| 3811 | bridge.getSemanticsContext().FindScope(stmt.source); |
| 3812 | typeCaseScopes.push_back(&scope); |
| 3813 | } |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3814 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 3815 | pushActiveConstruct(getEval(), stmtCtx); |
Krzysztof Parzyszek | c1b5b7c | 2024-05-21 08:19:54 -0500 | [diff] [blame] | 3816 | llvm::SmallVector<Fortran::lower::pft::Evaluation *> exits, fallThroughs; |
| 3817 | collectFinalEvaluations(getEval(), exits, fallThroughs); |
| 3818 | Fortran::lower::pft::Evaluation &constructExit = *getEval().constructExit; |
| 3819 | |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3820 | for (Fortran::lower::pft::Evaluation &eval : |
| 3821 | getEval().getNestedEvaluations()) { |
vdonaldson | cda8270 | 2024-05-03 09:11:10 -0400 | [diff] [blame] | 3822 | setCurrentPosition(eval.position); |
| 3823 | mlir::Location loc = toLocation(); |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3824 | if (auto *selectTypeStmt = |
| 3825 | eval.getIf<Fortran::parser::SelectTypeStmt>()) { |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 3826 | // A genFIR(SelectTypeStmt) call would have unwanted side effects. |
| 3827 | maybeStartBlock(eval.block); |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3828 | // Retrieve the selector |
| 3829 | const auto &s = std::get<Fortran::parser::Selector>(selectTypeStmt->t); |
| 3830 | if (const auto *v = std::get_if<Fortran::parser::Variable>(&s.u)) |
| 3831 | selector = genExprBox(loc, *Fortran::semantics::GetExpr(*v), stmtCtx); |
Valentin Clement | f5cca3c | 2023-02-16 20:59:54 +0100 | [diff] [blame] | 3832 | else if (const auto *e = std::get_if<Fortran::parser::Expr>(&s.u)) |
| 3833 | selector = genExprBox(loc, *Fortran::semantics::GetExpr(*e), stmtCtx); |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3834 | |
| 3835 | // Going through the controlSuccessor first to create the |
| 3836 | // fir.select_type operation. |
| 3837 | mlir::Block *defaultBlock = eval.parentConstruct->constructExit->block; |
| 3838 | for (Fortran::lower::pft::Evaluation *e = eval.controlSuccessor; e; |
| 3839 | e = e->controlSuccessor) { |
| 3840 | const auto &typeGuardStmt = |
| 3841 | e->getIf<Fortran::parser::TypeGuardStmt>(); |
| 3842 | const auto &guard = |
| 3843 | std::get<Fortran::parser::TypeGuardStmt::Guard>(typeGuardStmt->t); |
| 3844 | assert(e->block && "missing TypeGuardStmt block"); |
| 3845 | // CLASS DEFAULT |
| 3846 | if (std::holds_alternative<Fortran::parser::Default>(guard.u)) { |
| 3847 | defaultBlock = e->block; |
Valentin Clement | a459a24 | 2023-01-19 17:32:02 +0100 | [diff] [blame] | 3848 | // Keep track of the actual position of the CLASS DEFAULT type guard |
| 3849 | // in the SELECT TYPE construct. |
| 3850 | defaultAttrPos = attrList.size(); |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3851 | continue; |
| 3852 | } |
| 3853 | |
| 3854 | blockList.push_back(e->block); |
| 3855 | if (const auto *typeSpec = |
| 3856 | std::get_if<Fortran::parser::TypeSpec>(&guard.u)) { |
| 3857 | // TYPE IS |
| 3858 | mlir::Type ty; |
| 3859 | if (std::holds_alternative<Fortran::parser::IntrinsicTypeSpec>( |
| 3860 | typeSpec->u)) { |
| 3861 | const Fortran::semantics::IntrinsicTypeSpec *intrinsic = |
| 3862 | typeSpec->declTypeSpec->AsIntrinsic(); |
| 3863 | int kind = |
| 3864 | Fortran::evaluate::ToInt64(intrinsic->kind()).value_or(kind); |
| 3865 | llvm::SmallVector<Fortran::lower::LenParameterTy> params; |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3866 | ty = genType(intrinsic->category(), kind, params); |
| 3867 | } else { |
| 3868 | const Fortran::semantics::DerivedTypeSpec *derived = |
| 3869 | typeSpec->declTypeSpec->AsDerived(); |
| 3870 | ty = genType(*derived); |
| 3871 | } |
| 3872 | attrList.push_back(fir::ExactTypeAttr::get(ty)); |
| 3873 | } else if (const auto *derived = |
| 3874 | std::get_if<Fortran::parser::DerivedTypeSpec>( |
| 3875 | &guard.u)) { |
| 3876 | // CLASS IS |
| 3877 | assert(derived->derivedTypeSpec && "derived type spec is null"); |
| 3878 | mlir::Type ty = genType(*(derived->derivedTypeSpec)); |
| 3879 | attrList.push_back(fir::SubclassAttr::get(ty)); |
| 3880 | } |
| 3881 | } |
| 3882 | attrList.push_back(mlir::UnitAttr::get(context)); |
| 3883 | blockList.push_back(defaultBlock); |
| 3884 | builder->create<fir::SelectTypeOp>(loc, fir::getBase(selector), |
| 3885 | attrList, blockList); |
Valentin Clement | a459a24 | 2023-01-19 17:32:02 +0100 | [diff] [blame] | 3886 | |
| 3887 | // If the actual position of CLASS DEFAULT type guard is not the last |
| 3888 | // one, it needs to be put back at its correct position for the rest of |
| 3889 | // the processing. TypeGuardStmt are processed in the same order they |
| 3890 | // appear in the Fortran code. |
| 3891 | if (defaultAttrPos < attrList.size() - 1) { |
| 3892 | auto attrIt = attrList.begin(); |
| 3893 | attrIt = attrIt + defaultAttrPos; |
| 3894 | auto blockIt = blockList.begin(); |
| 3895 | blockIt = blockIt + defaultAttrPos; |
| 3896 | attrList.insert(attrIt, mlir::UnitAttr::get(context)); |
| 3897 | blockList.insert(blockIt, defaultBlock); |
| 3898 | attrList.pop_back(); |
| 3899 | blockList.pop_back(); |
| 3900 | } |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3901 | } else if (auto *typeGuardStmt = |
| 3902 | eval.getIf<Fortran::parser::TypeGuardStmt>()) { |
| 3903 | // Map the type guard local symbol for the selector to a more precise |
| 3904 | // typed entity in the TypeGuardStmt when necessary. |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 3905 | genFIR(eval); |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3906 | const auto &guard = |
| 3907 | std::get<Fortran::parser::TypeGuardStmt::Guard>(typeGuardStmt->t); |
| 3908 | if (hasLocalScope) |
| 3909 | localSymbols.popScope(); |
| 3910 | localSymbols.pushScope(); |
| 3911 | hasLocalScope = true; |
| 3912 | assert(attrList.size() >= typeGuardIdx && |
| 3913 | "TypeGuard attribute missing"); |
| 3914 | mlir::Attribute typeGuardAttr = attrList[typeGuardIdx]; |
| 3915 | mlir::Block *typeGuardBlock = blockList[typeGuardIdx]; |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3916 | mlir::OpBuilder::InsertPoint crtInsPt = builder->saveInsertionPoint(); |
| 3917 | builder->setInsertionPointToStart(typeGuardBlock); |
| 3918 | |
| 3919 | auto addAssocEntitySymbol = [&](fir::ExtendedValue exv) { |
Valentin Clement | b0de872 | 2023-02-16 09:05:12 +0100 | [diff] [blame] | 3920 | for (auto &symbol : typeCaseScopes[typeGuardIdx]->GetSymbols()) { |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3921 | if (symbol->GetUltimate() |
| 3922 | .detailsIf<Fortran::semantics::AssocEntityDetails>()) { |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 3923 | addSymbol(symbol, exv); |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3924 | break; |
| 3925 | } |
| 3926 | } |
| 3927 | }; |
| 3928 | |
Valentin Clement | 9379ca0 | 2022-12-15 12:02:11 +0100 | [diff] [blame] | 3929 | mlir::Type baseTy = fir::getBase(selector).getType(); |
| 3930 | bool isPointer = fir::isPointerType(baseTy); |
| 3931 | bool isAllocatable = fir::isAllocatableType(baseTy); |
| 3932 | bool isArray = |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 3933 | mlir::isa<fir::SequenceType>(fir::dyn_cast_ptrOrBoxEleTy(baseTy)); |
Valentin Clement | 9379ca0 | 2022-12-15 12:02:11 +0100 | [diff] [blame] | 3934 | const fir::BoxValue *selectorBox = selector.getBoxOf<fir::BoxValue>(); |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3935 | if (std::holds_alternative<Fortran::parser::Default>(guard.u)) { |
| 3936 | // CLASS DEFAULT |
| 3937 | addAssocEntitySymbol(selector); |
| 3938 | } else if (const auto *typeSpec = |
| 3939 | std::get_if<Fortran::parser::TypeSpec>(&guard.u)) { |
| 3940 | // TYPE IS |
| 3941 | fir::ExactTypeAttr attr = |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 3942 | mlir::dyn_cast<fir::ExactTypeAttr>(typeGuardAttr); |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3943 | mlir::Value exactValue; |
Valentin Clement | 9379ca0 | 2022-12-15 12:02:11 +0100 | [diff] [blame] | 3944 | mlir::Type addrTy = attr.getType(); |
| 3945 | if (isArray) { |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 3946 | auto seqTy = mlir::dyn_cast<fir::SequenceType>( |
| 3947 | fir::dyn_cast_ptrOrBoxEleTy(baseTy)); |
Valentin Clement | 9379ca0 | 2022-12-15 12:02:11 +0100 | [diff] [blame] | 3948 | addrTy = fir::SequenceType::get(seqTy.getShape(), attr.getType()); |
| 3949 | } |
| 3950 | if (isPointer) |
| 3951 | addrTy = fir::PointerType::get(addrTy); |
| 3952 | if (isAllocatable) |
| 3953 | addrTy = fir::HeapType::get(addrTy); |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3954 | if (std::holds_alternative<Fortran::parser::IntrinsicTypeSpec>( |
| 3955 | typeSpec->u)) { |
Valentin Clement | 9379ca0 | 2022-12-15 12:02:11 +0100 | [diff] [blame] | 3956 | mlir::Type refTy = fir::ReferenceType::get(addrTy); |
| 3957 | if (isPointer || isAllocatable) |
| 3958 | refTy = addrTy; |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3959 | exactValue = builder->create<fir::BoxAddrOp>( |
Valentin Clement | 9379ca0 | 2022-12-15 12:02:11 +0100 | [diff] [blame] | 3960 | loc, refTy, fir::getBase(selector)); |
Valentin Clement | c44292f | 2022-12-02 09:52:06 +0100 | [diff] [blame] | 3961 | const Fortran::semantics::IntrinsicTypeSpec *intrinsic = |
| 3962 | typeSpec->declTypeSpec->AsIntrinsic(); |
Valentin Clement | 9379ca0 | 2022-12-15 12:02:11 +0100 | [diff] [blame] | 3963 | if (isArray) { |
| 3964 | mlir::Value exact = builder->create<fir::ConvertOp>( |
| 3965 | loc, fir::BoxType::get(addrTy), fir::getBase(selector)); |
| 3966 | addAssocEntitySymbol(selectorBox->clone(exact)); |
| 3967 | } else if (intrinsic->category() == |
| 3968 | Fortran::common::TypeCategory::Character) { |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 3969 | auto charTy = mlir::dyn_cast<fir::CharacterType>(attr.getType()); |
Valentin Clement | c44292f | 2022-12-02 09:52:06 +0100 | [diff] [blame] | 3970 | mlir::Value charLen = |
| 3971 | fir::factory::CharacterExprHelper(*builder, loc) |
| 3972 | .readLengthFromBox(fir::getBase(selector), charTy); |
| 3973 | addAssocEntitySymbol(fir::CharBoxValue(exactValue, charLen)); |
| 3974 | } else { |
| 3975 | addAssocEntitySymbol(exactValue); |
| 3976 | } |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3977 | } else if (std::holds_alternative<Fortran::parser::DerivedTypeSpec>( |
| 3978 | typeSpec->u)) { |
| 3979 | exactValue = builder->create<fir::ConvertOp>( |
Valentin Clement | 9379ca0 | 2022-12-15 12:02:11 +0100 | [diff] [blame] | 3980 | loc, fir::BoxType::get(addrTy), fir::getBase(selector)); |
| 3981 | addAssocEntitySymbol(selectorBox->clone(exactValue)); |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3982 | } |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 3983 | } else if (std::holds_alternative<Fortran::parser::DerivedTypeSpec>( |
| 3984 | guard.u)) { |
| 3985 | // CLASS IS |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 3986 | fir::SubclassAttr attr = |
| 3987 | mlir::dyn_cast<fir::SubclassAttr>(typeGuardAttr); |
Valentin Clement | 9379ca0 | 2022-12-15 12:02:11 +0100 | [diff] [blame] | 3988 | mlir::Type addrTy = attr.getType(); |
| 3989 | if (isArray) { |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 3990 | auto seqTy = mlir::dyn_cast<fir::SequenceType>( |
| 3991 | fir::dyn_cast_ptrOrBoxEleTy(baseTy)); |
Valentin Clement | 9379ca0 | 2022-12-15 12:02:11 +0100 | [diff] [blame] | 3992 | addrTy = fir::SequenceType::get(seqTy.getShape(), attr.getType()); |
| 3993 | } |
| 3994 | if (isPointer) |
| 3995 | addrTy = fir::PointerType::get(addrTy); |
| 3996 | if (isAllocatable) |
| 3997 | addrTy = fir::HeapType::get(addrTy); |
| 3998 | mlir::Type classTy = fir::ClassType::get(addrTy); |
| 3999 | if (classTy == baseTy) { |
| 4000 | addAssocEntitySymbol(selector); |
| 4001 | } else { |
| 4002 | mlir::Value derived = builder->create<fir::ConvertOp>( |
| 4003 | loc, classTy, fir::getBase(selector)); |
| 4004 | addAssocEntitySymbol(selectorBox->clone(derived)); |
| 4005 | } |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 4006 | } |
| 4007 | builder->restoreInsertionPoint(crtInsPt); |
| 4008 | ++typeGuardIdx; |
| 4009 | } else if (eval.getIf<Fortran::parser::EndSelectStmt>()) { |
Carlos Eduardo Seo | 9ceb0a7 | 2023-05-20 05:16:50 +0000 | [diff] [blame] | 4010 | maybeStartBlock(eval.block); |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 4011 | if (hasLocalScope) |
| 4012 | localSymbols.popScope(); |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 4013 | } else { |
| 4014 | genFIR(eval); |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 4015 | } |
Krzysztof Parzyszek | c1b5b7c | 2024-05-21 08:19:54 -0500 | [diff] [blame] | 4016 | if (blockIsUnterminated()) { |
| 4017 | if (llvm::is_contained(exits, &eval)) |
| 4018 | genConstructExitBranch(constructExit); |
| 4019 | else if (llvm::is_contained(fallThroughs, &eval)) |
| 4020 | genBranch(eval.lexicalSuccessor->block); |
| 4021 | } |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 4022 | } |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 4023 | popActiveConstruct(); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4024 | } |
| 4025 | |
| 4026 | //===--------------------------------------------------------------------===// |
| 4027 | // IO statements (see io.h) |
| 4028 | //===--------------------------------------------------------------------===// |
| 4029 | |
| 4030 | void genFIR(const Fortran::parser::BackspaceStmt &stmt) { |
Valentin Clement | 46f46a3 | 2022-03-02 17:58:38 +0100 | [diff] [blame] | 4031 | mlir::Value iostat = genBackspaceStatement(*this, stmt); |
| 4032 | genIoConditionBranches(getEval(), stmt.v, iostat); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4033 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4034 | void genFIR(const Fortran::parser::CloseStmt &stmt) { |
Valentin Clement | db48f7b | 2022-03-02 17:55:10 +0100 | [diff] [blame] | 4035 | mlir::Value iostat = genCloseStatement(*this, stmt); |
| 4036 | genIoConditionBranches(getEval(), stmt.v, iostat); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4037 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4038 | void genFIR(const Fortran::parser::EndfileStmt &stmt) { |
Valentin Clement | 46f46a3 | 2022-03-02 17:58:38 +0100 | [diff] [blame] | 4039 | mlir::Value iostat = genEndfileStatement(*this, stmt); |
| 4040 | genIoConditionBranches(getEval(), stmt.v, iostat); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4041 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4042 | void genFIR(const Fortran::parser::FlushStmt &stmt) { |
Valentin Clement | 46f46a3 | 2022-03-02 17:58:38 +0100 | [diff] [blame] | 4043 | mlir::Value iostat = genFlushStatement(*this, stmt); |
| 4044 | genIoConditionBranches(getEval(), stmt.v, iostat); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4045 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4046 | void genFIR(const Fortran::parser::InquireStmt &stmt) { |
Valentin Clement | 7e32cad | 2022-03-02 18:02:41 +0100 | [diff] [blame] | 4047 | mlir::Value iostat = genInquireStatement(*this, stmt); |
| 4048 | if (const auto *specs = |
| 4049 | std::get_if<std::list<Fortran::parser::InquireSpec>>(&stmt.u)) |
| 4050 | genIoConditionBranches(getEval(), *specs, iostat); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4051 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4052 | void genFIR(const Fortran::parser::OpenStmt &stmt) { |
Valentin Clement | db48f7b | 2022-03-02 17:55:10 +0100 | [diff] [blame] | 4053 | mlir::Value iostat = genOpenStatement(*this, stmt); |
| 4054 | genIoConditionBranches(getEval(), stmt.v, iostat); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4055 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4056 | void genFIR(const Fortran::parser::PrintStmt &stmt) { |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 4057 | genPrintStatement(*this, stmt); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4058 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4059 | void genFIR(const Fortran::parser::ReadStmt &stmt) { |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 4060 | mlir::Value iostat = genReadStatement(*this, stmt); |
| 4061 | genIoConditionBranches(getEval(), stmt.controls, iostat); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4062 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4063 | void genFIR(const Fortran::parser::RewindStmt &stmt) { |
Valentin Clement | 46f46a3 | 2022-03-02 17:58:38 +0100 | [diff] [blame] | 4064 | mlir::Value iostat = genRewindStatement(*this, stmt); |
| 4065 | genIoConditionBranches(getEval(), stmt.v, iostat); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4066 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4067 | void genFIR(const Fortran::parser::WaitStmt &stmt) { |
Valentin Clement | 46f46a3 | 2022-03-02 17:58:38 +0100 | [diff] [blame] | 4068 | mlir::Value iostat = genWaitStatement(*this, stmt); |
| 4069 | genIoConditionBranches(getEval(), stmt.v, iostat); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4070 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4071 | void genFIR(const Fortran::parser::WriteStmt &stmt) { |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 4072 | mlir::Value iostat = genWriteStatement(*this, stmt); |
| 4073 | genIoConditionBranches(getEval(), stmt.controls, iostat); |
| 4074 | } |
| 4075 | |
| 4076 | template <typename A> |
| 4077 | void genIoConditionBranches(Fortran::lower::pft::Evaluation &eval, |
| 4078 | const A &specList, mlir::Value iostat) { |
| 4079 | if (!iostat) |
| 4080 | return; |
| 4081 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 4082 | Fortran::parser::Label endLabel{}; |
| 4083 | Fortran::parser::Label eorLabel{}; |
| 4084 | Fortran::parser::Label errLabel{}; |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 4085 | bool hasIostat{}; |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 4086 | for (const auto &spec : specList) { |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 4087 | Fortran::common::visit( |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 4088 | Fortran::common::visitors{ |
| 4089 | [&](const Fortran::parser::EndLabel &label) { |
| 4090 | endLabel = label.v; |
| 4091 | }, |
| 4092 | [&](const Fortran::parser::EorLabel &label) { |
| 4093 | eorLabel = label.v; |
| 4094 | }, |
| 4095 | [&](const Fortran::parser::ErrLabel &label) { |
| 4096 | errLabel = label.v; |
| 4097 | }, |
| 4098 | [&](const Fortran::parser::StatVariable &) { hasIostat = true; }, |
| 4099 | [](const auto &) {}}, |
| 4100 | spec.u); |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 4101 | } |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 4102 | if (!endLabel && !eorLabel && !errLabel) |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 4103 | return; |
| 4104 | |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 4105 | // An ERR specifier branch is taken on any positive error value rather than |
| 4106 | // some single specific value. If ERR and IOSTAT specifiers are given and |
| 4107 | // END and EOR specifiers are allowed, the latter two specifiers must have |
| 4108 | // explicit branch targets to allow the ERR branch to be implemented as a |
| 4109 | // default/else target. A label=0 target for an absent END or EOR specifier |
| 4110 | // indicates that these specifiers have a fallthrough target. END and EOR |
| 4111 | // specifiers may appear on READ and WAIT statements. |
| 4112 | bool allSpecifiersRequired = errLabel && hasIostat && |
| 4113 | (eval.isA<Fortran::parser::ReadStmt>() || |
| 4114 | eval.isA<Fortran::parser::WaitStmt>()); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 4115 | mlir::Value selector = |
| 4116 | builder->createConvert(toLocation(), builder->getIndexType(), iostat); |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 4117 | llvm::SmallVector<int64_t> valueList; |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 4118 | llvm::SmallVector<Fortran::parser::Label> labelList; |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 4119 | if (eorLabel || allSpecifiersRequired) { |
| 4120 | valueList.push_back(Fortran::runtime::io::IostatEor); |
| 4121 | labelList.push_back(eorLabel ? eorLabel : 0); |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 4122 | } |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 4123 | if (endLabel || allSpecifiersRequired) { |
| 4124 | valueList.push_back(Fortran::runtime::io::IostatEnd); |
| 4125 | labelList.push_back(endLabel ? endLabel : 0); |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 4126 | } |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 4127 | if (errLabel) { |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 4128 | // Must be last. Value 0 is interpreted as any positive value, or |
| 4129 | // equivalently as any value other than 0, IostatEor, or IostatEnd. |
| 4130 | valueList.push_back(0); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 4131 | labelList.push_back(errLabel); |
Valentin Clement | 8c22cb8 | 2022-03-01 21:47:40 +0100 | [diff] [blame] | 4132 | } |
V Donaldson | 5e52158 | 2023-03-31 09:36:16 -0700 | [diff] [blame] | 4133 | genMultiwayBranch(selector, valueList, labelList, eval.nonNopSuccessor()); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4134 | } |
| 4135 | |
| 4136 | //===--------------------------------------------------------------------===// |
| 4137 | // Memory allocation and deallocation |
| 4138 | //===--------------------------------------------------------------------===// |
| 4139 | |
| 4140 | void genFIR(const Fortran::parser::AllocateStmt &stmt) { |
Valentin Clement | c5cf1b9 | 2022-03-07 21:22:28 +0100 | [diff] [blame] | 4141 | Fortran::lower::genAllocateStmt(*this, stmt, toLocation()); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4142 | } |
| 4143 | |
| 4144 | void genFIR(const Fortran::parser::DeallocateStmt &stmt) { |
Valentin Clement | c5cf1b9 | 2022-03-07 21:22:28 +0100 | [diff] [blame] | 4145 | Fortran::lower::genDeallocateStmt(*this, stmt, toLocation()); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4146 | } |
| 4147 | |
Valentin Clement | 72276bd | 2022-03-10 20:19:57 +0100 | [diff] [blame] | 4148 | /// Nullify pointer object list |
| 4149 | /// |
| 4150 | /// For each pointer object, reset the pointer to a disassociated status. |
| 4151 | /// We do this by setting each pointer to null. |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4152 | void genFIR(const Fortran::parser::NullifyStmt &stmt) { |
Valentin Clement | 72276bd | 2022-03-10 20:19:57 +0100 | [diff] [blame] | 4153 | mlir::Location loc = toLocation(); |
| 4154 | for (auto &pointerObject : stmt.v) { |
| 4155 | const Fortran::lower::SomeExpr *expr = |
| 4156 | Fortran::semantics::GetExpr(pointerObject); |
| 4157 | assert(expr); |
Daniel Chen | af09219 | 2023-11-22 11:51:12 -0500 | [diff] [blame] | 4158 | if (Fortran::evaluate::IsProcedurePointer(*expr)) { |
| 4159 | Fortran::lower::StatementContext stmtCtx; |
| 4160 | hlfir::Entity pptr = Fortran::lower::convertExprToHLFIR( |
| 4161 | loc, *this, *expr, localSymbols, stmtCtx); |
| 4162 | auto boxTy{ |
| 4163 | Fortran::lower::getUntypedBoxProcType(builder->getContext())}; |
| 4164 | hlfir::Entity nullBoxProc( |
| 4165 | fir::factory::createNullBoxProc(*builder, loc, boxTy)); |
| 4166 | builder->createStoreWithConvert(loc, nullBoxProc, pptr); |
Daniel Chen | b081e9d | 2024-02-09 10:56:57 -0500 | [diff] [blame] | 4167 | } else { |
| 4168 | fir::MutableBoxValue box = genExprMutableBox(loc, *expr); |
| 4169 | fir::factory::disassociateMutableBox(*builder, loc, box); |
Valentin Clement (バレンタイン クレメン) | 9165848 | 2025-01-03 14:37:14 -0800 | [diff] [blame] | 4170 | cuf::genPointerSync(box.getAddr(), *builder); |
Daniel Chen | af09219 | 2023-11-22 11:51:12 -0500 | [diff] [blame] | 4171 | } |
Valentin Clement | 72276bd | 2022-03-10 20:19:57 +0100 | [diff] [blame] | 4172 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4173 | } |
| 4174 | |
| 4175 | //===--------------------------------------------------------------------===// |
| 4176 | |
Katherine Rasmussen | a2d7af7 | 2024-01-02 10:40:47 -0800 | [diff] [blame] | 4177 | void genFIR(const Fortran::parser::NotifyWaitStmt &stmt) { |
| 4178 | genNotifyWaitStatement(*this, stmt); |
| 4179 | } |
| 4180 | |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4181 | void genFIR(const Fortran::parser::EventPostStmt &stmt) { |
Valentin Clement | 534b228 | 2022-03-28 13:36:10 +0200 | [diff] [blame] | 4182 | genEventPostStatement(*this, stmt); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4183 | } |
| 4184 | |
| 4185 | void genFIR(const Fortran::parser::EventWaitStmt &stmt) { |
Valentin Clement | 534b228 | 2022-03-28 13:36:10 +0200 | [diff] [blame] | 4186 | genEventWaitStatement(*this, stmt); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4187 | } |
| 4188 | |
| 4189 | void genFIR(const Fortran::parser::FormTeamStmt &stmt) { |
Valentin Clement | 534b228 | 2022-03-28 13:36:10 +0200 | [diff] [blame] | 4190 | genFormTeamStatement(*this, getEval(), stmt); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4191 | } |
| 4192 | |
| 4193 | void genFIR(const Fortran::parser::LockStmt &stmt) { |
Valentin Clement | 534b228 | 2022-03-28 13:36:10 +0200 | [diff] [blame] | 4194 | genLockStatement(*this, stmt); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 4195 | } |
| 4196 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 4197 | fir::ExtendedValue |
| 4198 | genInitializerExprValue(const Fortran::lower::SomeExpr &expr, |
| 4199 | Fortran::lower::StatementContext &stmtCtx) { |
| 4200 | return Fortran::lower::createSomeInitializerExpression( |
| 4201 | toLocation(), *this, expr, localSymbols, stmtCtx); |
| 4202 | } |
| 4203 | |
Valentin Clement | 7a6a165 | 2022-03-10 18:43:40 +0100 | [diff] [blame] | 4204 | /// Return true if the current context is a conditionalized and implied |
| 4205 | /// iteration space. |
| 4206 | bool implicitIterationSpace() { return !implicitIterSpace.empty(); } |
| 4207 | |
| 4208 | /// Return true if context is currently an explicit iteration space. A scalar |
| 4209 | /// assignment expression may be contextually within a user-defined iteration |
| 4210 | /// space, transforming it into an array expression. |
| 4211 | bool explicitIterationSpace() { return explicitIterSpace.isActive(); } |
| 4212 | |
Valentin Clement | f9704f0 | 2022-02-24 21:09:40 +0100 | [diff] [blame] | 4213 | /// Generate an array assignment. |
| 4214 | /// This is an assignment expression with rank > 0. The assignment may or may |
| 4215 | /// not be in a WHERE and/or FORALL context. |
Eric Schweitz | 1bffc75 | 2022-04-22 13:59:17 -0700 | [diff] [blame] | 4216 | /// In a FORALL context, the assignment may be a pointer assignment and the \p |
| 4217 | /// lbounds and \p ubounds parameters should only be used in such a pointer |
| 4218 | /// assignment case. (If both are None then the array assignment cannot be a |
| 4219 | /// pointer assignment.) |
| 4220 | void genArrayAssignment( |
| 4221 | const Fortran::evaluate::Assignment &assign, |
Jean Perier | e6238ab | 2022-09-20 10:39:39 +0200 | [diff] [blame] | 4222 | Fortran::lower::StatementContext &localStmtCtx, |
Kazu Hirata | c092158 | 2023-01-07 22:26:48 -0800 | [diff] [blame] | 4223 | std::optional<llvm::SmallVector<mlir::Value>> lbounds = std::nullopt, |
| 4224 | std::optional<llvm::SmallVector<mlir::Value>> ubounds = std::nullopt) { |
Jean Perier | e6238ab | 2022-09-20 10:39:39 +0200 | [diff] [blame] | 4225 | |
| 4226 | Fortran::lower::StatementContext &stmtCtx = |
| 4227 | explicitIterationSpace() |
| 4228 | ? explicitIterSpace.stmtContext() |
| 4229 | : (implicitIterationSpace() ? implicitIterSpace.stmtContext() |
| 4230 | : localStmtCtx); |
Eric Schweitz | 1bffc75 | 2022-04-22 13:59:17 -0700 | [diff] [blame] | 4231 | if (Fortran::lower::isWholeAllocatable(assign.lhs)) { |
Valentin Clement | f9704f0 | 2022-02-24 21:09:40 +0100 | [diff] [blame] | 4232 | // Assignment to allocatables may require the lhs to be |
| 4233 | // deallocated/reallocated. See Fortran 2018 10.2.1.3 p3 |
| 4234 | Fortran::lower::createAllocatableArrayAssignment( |
| 4235 | *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace, |
| 4236 | localSymbols, stmtCtx); |
| 4237 | return; |
| 4238 | } |
| 4239 | |
Kazu Hirata | 5413bf1 | 2022-06-20 11:33:56 -0700 | [diff] [blame] | 4240 | if (lbounds) { |
Eric Schweitz | 1bffc75 | 2022-04-22 13:59:17 -0700 | [diff] [blame] | 4241 | // Array of POINTER entities, with elemental assignment. |
| 4242 | if (!Fortran::lower::isWholePointer(assign.lhs)) |
| 4243 | fir::emitFatalError(toLocation(), "pointer assignment to non-pointer"); |
| 4244 | |
| 4245 | Fortran::lower::createArrayOfPointerAssignment( |
| 4246 | *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace, |
Kazu Hirata | ed8fcea | 2022-06-20 23:35:53 -0700 | [diff] [blame] | 4247 | *lbounds, ubounds, localSymbols, stmtCtx); |
Eric Schweitz | 1bffc75 | 2022-04-22 13:59:17 -0700 | [diff] [blame] | 4248 | return; |
| 4249 | } |
| 4250 | |
Valentin Clement | 7a6a165 | 2022-03-10 18:43:40 +0100 | [diff] [blame] | 4251 | if (!implicitIterationSpace() && !explicitIterationSpace()) { |
| 4252 | // No masks and the iteration space is implied by the array, so create a |
| 4253 | // simple array assignment. |
| 4254 | Fortran::lower::createSomeArrayAssignment(*this, assign.lhs, assign.rhs, |
| 4255 | localSymbols, stmtCtx); |
| 4256 | return; |
| 4257 | } |
| 4258 | |
| 4259 | // If there is an explicit iteration space, generate an array assignment |
| 4260 | // with a user-specified iteration space and possibly with masks. These |
| 4261 | // assignments may *appear* to be scalar expressions, but the scalar |
| 4262 | // expression is evaluated at all points in the user-defined space much like |
| 4263 | // an ordinary array assignment. More specifically, the semantics inside the |
| 4264 | // FORALL much more closely resembles that of WHERE than a scalar |
| 4265 | // assignment. |
| 4266 | // Otherwise, generate a masked array assignment. The iteration space is |
| 4267 | // implied by the lhs array expression. |
| 4268 | Fortran::lower::createAnyMaskedArrayAssignment( |
| 4269 | *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace, |
Jean Perier | e6238ab | 2022-09-20 10:39:39 +0200 | [diff] [blame] | 4270 | localSymbols, stmtCtx); |
Valentin Clement | f9704f0 | 2022-02-24 21:09:40 +0100 | [diff] [blame] | 4271 | } |
| 4272 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 4273 | #if !defined(NDEBUG) |
| 4274 | static bool isFuncResultDesignator(const Fortran::lower::SomeExpr &expr) { |
| 4275 | const Fortran::semantics::Symbol *sym = |
| 4276 | Fortran::evaluate::GetFirstSymbol(expr); |
| 4277 | return sym && sym->IsFuncResult(); |
| 4278 | } |
| 4279 | #endif |
| 4280 | |
Eric Schweitz | 1bffc75 | 2022-04-22 13:59:17 -0700 | [diff] [blame] | 4281 | inline fir::MutableBoxValue |
| 4282 | genExprMutableBox(mlir::Location loc, |
| 4283 | const Fortran::lower::SomeExpr &expr) override final { |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4284 | if (lowerToHighLevelFIR()) |
| 4285 | return Fortran::lower::convertExprToMutableBox(loc, *this, expr, |
| 4286 | localSymbols); |
Eric Schweitz | 1bffc75 | 2022-04-22 13:59:17 -0700 | [diff] [blame] | 4287 | return Fortran::lower::createMutableBox(loc, *this, expr, localSymbols); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 4288 | } |
| 4289 | |
Valentin Clement | dda0163 | 2023-02-07 09:15:54 +0100 | [diff] [blame] | 4290 | // Create the [newRank] array with the lower bounds to be passed to the |
| 4291 | // runtime as a descriptor. |
| 4292 | mlir::Value createLboundArray(llvm::ArrayRef<mlir::Value> lbounds, |
| 4293 | mlir::Location loc) { |
| 4294 | mlir::Type indexTy = builder->getIndexType(); |
| 4295 | mlir::Type boundArrayTy = fir::SequenceType::get( |
| 4296 | {static_cast<int64_t>(lbounds.size())}, builder->getI64Type()); |
| 4297 | mlir::Value boundArray = builder->create<fir::AllocaOp>(loc, boundArrayTy); |
| 4298 | mlir::Value array = builder->create<fir::UndefOp>(loc, boundArrayTy); |
| 4299 | for (unsigned i = 0; i < lbounds.size(); ++i) { |
| 4300 | array = builder->create<fir::InsertValueOp>( |
| 4301 | loc, boundArrayTy, array, lbounds[i], |
| 4302 | builder->getArrayAttr({builder->getIntegerAttr( |
| 4303 | builder->getIndexType(), static_cast<int>(i))})); |
| 4304 | } |
| 4305 | builder->create<fir::StoreOp>(loc, array, boundArray); |
| 4306 | mlir::Type boxTy = fir::BoxType::get(boundArrayTy); |
| 4307 | mlir::Value ext = |
| 4308 | builder->createIntegerConstant(loc, indexTy, lbounds.size()); |
| 4309 | llvm::SmallVector<mlir::Value> shapes = {ext}; |
| 4310 | mlir::Value shapeOp = builder->genShape(loc, shapes); |
| 4311 | return builder->create<fir::EmboxOp>(loc, boxTy, boundArray, shapeOp); |
| 4312 | } |
| 4313 | |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4314 | // Generate pointer assignment with possibly empty bounds-spec. R1035: a |
| 4315 | // bounds-spec is a lower bound value. |
| 4316 | void genPointerAssignment( |
| 4317 | mlir::Location loc, const Fortran::evaluate::Assignment &assign, |
| 4318 | const Fortran::evaluate::Assignment::BoundsSpec &lbExprs) { |
| 4319 | Fortran::lower::StatementContext stmtCtx; |
Daniel Chen | af09219 | 2023-11-22 11:51:12 -0500 | [diff] [blame] | 4320 | |
Peter Klausler | c759334 | 2024-06-03 12:58:39 -0700 | [diff] [blame] | 4321 | if (!lowerToHighLevelFIR() && |
| 4322 | Fortran::evaluate::IsProcedureDesignator(assign.rhs)) |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4323 | TODO(loc, "procedure pointer assignment"); |
Daniel Chen | af09219 | 2023-11-22 11:51:12 -0500 | [diff] [blame] | 4324 | if (Fortran::evaluate::IsProcedurePointer(assign.lhs)) { |
| 4325 | hlfir::Entity lhs = Fortran::lower::convertExprToHLFIR( |
| 4326 | loc, *this, assign.lhs, localSymbols, stmtCtx); |
Daniel Chen | bd8bec2 | 2024-01-31 11:24:17 -0500 | [diff] [blame] | 4327 | if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>( |
| 4328 | assign.rhs)) { |
| 4329 | // rhs is null(). rhs being null(pptr) is handled in genNull. |
Daniel Chen | 4998587 | 2024-03-26 11:29:24 -0400 | [diff] [blame] | 4330 | auto boxTy{ |
| 4331 | Fortran::lower::getUntypedBoxProcType(builder->getContext())}; |
Daniel Chen | af09219 | 2023-11-22 11:51:12 -0500 | [diff] [blame] | 4332 | hlfir::Entity rhs( |
| 4333 | fir::factory::createNullBoxProc(*builder, loc, boxTy)); |
| 4334 | builder->createStoreWithConvert(loc, rhs, lhs); |
| 4335 | return; |
| 4336 | } |
| 4337 | hlfir::Entity rhs(getBase(Fortran::lower::convertExprToAddress( |
| 4338 | loc, *this, assign.rhs, localSymbols, stmtCtx))); |
| 4339 | builder->createStoreWithConvert(loc, rhs, lhs); |
| 4340 | return; |
| 4341 | } |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4342 | |
| 4343 | std::optional<Fortran::evaluate::DynamicType> lhsType = |
| 4344 | assign.lhs.GetType(); |
| 4345 | // Delegate pointer association to unlimited polymorphic pointer |
| 4346 | // to the runtime. element size, type code, attribute and of |
| 4347 | // course base_addr might need to be updated. |
| 4348 | if (lhsType && lhsType->IsPolymorphic()) { |
| 4349 | if (!lowerToHighLevelFIR() && explicitIterationSpace()) |
| 4350 | TODO(loc, "polymorphic pointer assignment in FORALL"); |
Valentin Clement | dda0163 | 2023-02-07 09:15:54 +0100 | [diff] [blame] | 4351 | llvm::SmallVector<mlir::Value> lbounds; |
| 4352 | for (const Fortran::evaluate::ExtentExpr &lbExpr : lbExprs) |
| 4353 | lbounds.push_back( |
| 4354 | fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx))); |
Jean Perier | 04a920b7 | 2023-04-03 09:18:41 +0200 | [diff] [blame] | 4355 | fir::MutableBoxValue lhsMutableBox = genExprMutableBox(loc, assign.lhs); |
| 4356 | if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>( |
| 4357 | assign.rhs)) { |
| 4358 | fir::factory::disassociateMutableBox(*builder, loc, lhsMutableBox); |
| 4359 | return; |
| 4360 | } |
| 4361 | mlir::Value lhs = lhsMutableBox.getAddr(); |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4362 | mlir::Value rhs = fir::getBase(genExprBox(loc, assign.rhs, stmtCtx)); |
Valentin Clement | dda0163 | 2023-02-07 09:15:54 +0100 | [diff] [blame] | 4363 | if (!lbounds.empty()) { |
| 4364 | mlir::Value boundsDesc = createLboundArray(lbounds, loc); |
| 4365 | Fortran::lower::genPointerAssociateLowerBounds(*builder, loc, lhs, rhs, |
| 4366 | boundsDesc); |
| 4367 | return; |
| 4368 | } |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4369 | Fortran::lower::genPointerAssociate(*builder, loc, lhs, rhs); |
| 4370 | return; |
| 4371 | } |
| 4372 | |
| 4373 | llvm::SmallVector<mlir::Value> lbounds; |
| 4374 | for (const Fortran::evaluate::ExtentExpr &lbExpr : lbExprs) |
| 4375 | lbounds.push_back(fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx))); |
| 4376 | if (!lowerToHighLevelFIR() && explicitIterationSpace()) { |
| 4377 | // Pointer assignment in FORALL context. Copy the rhs box value |
| 4378 | // into the lhs box variable. |
| 4379 | genArrayAssignment(assign, stmtCtx, lbounds); |
| 4380 | return; |
| 4381 | } |
| 4382 | fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs); |
| 4383 | Fortran::lower::associateMutableBox(*this, loc, lhs, assign.rhs, lbounds, |
| 4384 | stmtCtx); |
| 4385 | } |
Valentin Clement | 3b73fc3 | 2023-02-06 21:06:44 +0100 | [diff] [blame] | 4386 | |
jeanPerier | 3ff3b29 | 2025-03-14 10:51:46 +0100 | [diff] [blame] | 4387 | void genForallPointerAssignment(mlir::Location loc, |
| 4388 | const Fortran::evaluate::Assignment &assign) { |
| 4389 | // Lower pointer assignment inside forall with hlfir.region_assign with |
| 4390 | // descriptor address/value and later implemented with a store. |
| 4391 | // The RHS is fully prepared in lowering, so that all that is left |
| 4392 | // in hlfir.region_assign code generation is the store. |
jeanPerier | 7302e1b | 2025-03-05 11:24:04 +0100 | [diff] [blame] | 4393 | auto regionAssignOp = builder->create<hlfir::RegionAssignOp>(loc); |
| 4394 | |
| 4395 | // Lower LHS in its own region. |
| 4396 | builder->createBlock(®ionAssignOp.getLhsRegion()); |
| 4397 | Fortran::lower::StatementContext lhsContext; |
| 4398 | hlfir::Entity lhs = Fortran::lower::convertExprToHLFIR( |
| 4399 | loc, *this, assign.lhs, localSymbols, lhsContext); |
jeanPerier | 7302e1b | 2025-03-05 11:24:04 +0100 | [diff] [blame] | 4400 | auto lhsYieldOp = builder->create<hlfir::YieldOp>(loc, lhs); |
| 4401 | Fortran::lower::genCleanUpInRegionIfAny( |
| 4402 | loc, *builder, lhsYieldOp.getCleanup(), lhsContext); |
| 4403 | |
| 4404 | // Lower RHS in its own region. |
| 4405 | builder->createBlock(®ionAssignOp.getRhsRegion()); |
| 4406 | Fortran::lower::StatementContext rhsContext; |
jeanPerier | 40e245a | 2025-03-07 10:28:02 +0100 | [diff] [blame] | 4407 | mlir::Value rhs = |
| 4408 | genForallPointerAssignmentRhs(loc, lhs, assign, rhsContext); |
| 4409 | auto rhsYieldOp = builder->create<hlfir::YieldOp>(loc, rhs); |
| 4410 | Fortran::lower::genCleanUpInRegionIfAny( |
| 4411 | loc, *builder, rhsYieldOp.getCleanup(), rhsContext); |
| 4412 | |
| 4413 | builder->setInsertionPointAfter(regionAssignOp); |
| 4414 | } |
| 4415 | |
jeanPerier | 3ff3b29 | 2025-03-14 10:51:46 +0100 | [diff] [blame] | 4416 | mlir::Value lowerToIndexValue(mlir::Location loc, |
| 4417 | const Fortran::evaluate::ExtentExpr &expr, |
| 4418 | Fortran::lower::StatementContext &stmtCtx) { |
| 4419 | mlir::Value val = fir::getBase(genExprValue(toEvExpr(expr), stmtCtx)); |
| 4420 | return builder->createConvert(loc, builder->getIndexType(), val); |
| 4421 | } |
| 4422 | |
jeanPerier | 40e245a | 2025-03-07 10:28:02 +0100 | [diff] [blame] | 4423 | mlir::Value |
| 4424 | genForallPointerAssignmentRhs(mlir::Location loc, mlir::Value lhs, |
| 4425 | const Fortran::evaluate::Assignment &assign, |
| 4426 | Fortran::lower::StatementContext &rhsContext) { |
jeanPerier | 3ff3b29 | 2025-03-14 10:51:46 +0100 | [diff] [blame] | 4427 | if (Fortran::evaluate::IsProcedureDesignator(assign.lhs)) { |
| 4428 | if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>( |
| 4429 | assign.rhs)) |
| 4430 | return fir::factory::createNullBoxProc( |
| 4431 | *builder, loc, fir::unwrapRefType(lhs.getType())); |
jeanPerier | 40e245a | 2025-03-07 10:28:02 +0100 | [diff] [blame] | 4432 | return fir::getBase(Fortran::lower::convertExprToAddress( |
| 4433 | loc, *this, assign.rhs, localSymbols, rhsContext)); |
jeanPerier | 3ff3b29 | 2025-03-14 10:51:46 +0100 | [diff] [blame] | 4434 | } |
jeanPerier | 40e245a | 2025-03-07 10:28:02 +0100 | [diff] [blame] | 4435 | // Data target. |
jeanPerier | 3ff3b29 | 2025-03-14 10:51:46 +0100 | [diff] [blame] | 4436 | auto lhsBoxType = |
| 4437 | llvm::cast<fir::BaseBoxType>(fir::unwrapRefType(lhs.getType())); |
| 4438 | // For NULL, create disassociated descriptor whose dynamic type is |
| 4439 | // the static type of the LHS. |
| 4440 | if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>( |
| 4441 | assign.rhs)) |
| 4442 | return fir::factory::createUnallocatedBox(*builder, loc, lhsBoxType, |
| 4443 | std::nullopt); |
jeanPerier | 7302e1b | 2025-03-05 11:24:04 +0100 | [diff] [blame] | 4444 | hlfir::Entity rhs = Fortran::lower::convertExprToHLFIR( |
| 4445 | loc, *this, assign.rhs, localSymbols, rhsContext); |
| 4446 | // Create pointer descriptor value from the RHS. |
| 4447 | if (rhs.isMutableBox()) |
| 4448 | rhs = hlfir::Entity{builder->create<fir::LoadOp>(loc, rhs)}; |
jeanPerier | 3ff3b29 | 2025-03-14 10:51:46 +0100 | [diff] [blame] | 4449 | mlir::Value rhsBox = hlfir::genVariableBox( |
| 4450 | loc, *builder, rhs, lhsBoxType.getBoxTypeWithNewShape(rhs.getRank())); |
| 4451 | // Apply lower bounds or reshaping if any. |
| 4452 | if (const auto *lbExprs = |
| 4453 | std::get_if<Fortran::evaluate::Assignment::BoundsSpec>(&assign.u); |
| 4454 | lbExprs && !lbExprs->empty()) { |
| 4455 | // Override target lower bounds with the LHS bounds spec. |
| 4456 | llvm::SmallVector<mlir::Value> lbounds; |
| 4457 | for (const Fortran::evaluate::ExtentExpr &lbExpr : *lbExprs) |
| 4458 | lbounds.push_back(lowerToIndexValue(loc, lbExpr, rhsContext)); |
| 4459 | mlir::Value shift = builder->genShift(loc, lbounds); |
| 4460 | rhsBox = builder->create<fir::ReboxOp>(loc, lhsBoxType, rhsBox, shift, |
| 4461 | /*slice=*/mlir::Value{}); |
| 4462 | } else if (const auto *boundExprs = |
| 4463 | std::get_if<Fortran::evaluate::Assignment::BoundsRemapping>( |
| 4464 | &assign.u); |
| 4465 | boundExprs && !boundExprs->empty()) { |
| 4466 | // Reshape the target according to the LHS bounds remapping. |
| 4467 | llvm::SmallVector<mlir::Value> lbounds; |
| 4468 | llvm::SmallVector<mlir::Value> extents; |
| 4469 | mlir::Type indexTy = builder->getIndexType(); |
| 4470 | mlir::Value zero = builder->createIntegerConstant(loc, indexTy, 0); |
| 4471 | mlir::Value one = builder->createIntegerConstant(loc, indexTy, 1); |
| 4472 | for (const auto &[lbExpr, ubExpr] : *boundExprs) { |
| 4473 | lbounds.push_back(lowerToIndexValue(loc, lbExpr, rhsContext)); |
| 4474 | mlir::Value ub = lowerToIndexValue(loc, ubExpr, rhsContext); |
| 4475 | extents.push_back(fir::factory::computeExtent( |
| 4476 | *builder, loc, lbounds.back(), ub, zero, one)); |
| 4477 | } |
| 4478 | mlir::Value shape = builder->genShape(loc, lbounds, extents); |
| 4479 | rhsBox = builder->create<fir::ReboxOp>(loc, lhsBoxType, rhsBox, shape, |
| 4480 | /*slice=*/mlir::Value{}); |
| 4481 | } |
| 4482 | return rhsBox; |
jeanPerier | 7302e1b | 2025-03-05 11:24:04 +0100 | [diff] [blame] | 4483 | } |
| 4484 | |
Valentin Clement | 3b73fc3 | 2023-02-06 21:06:44 +0100 | [diff] [blame] | 4485 | // Create the 2 x newRank array with the bounds to be passed to the runtime as |
| 4486 | // a descriptor. |
| 4487 | mlir::Value createBoundArray(llvm::ArrayRef<mlir::Value> lbounds, |
| 4488 | llvm::ArrayRef<mlir::Value> ubounds, |
| 4489 | mlir::Location loc) { |
| 4490 | assert(lbounds.size() && ubounds.size()); |
| 4491 | mlir::Type indexTy = builder->getIndexType(); |
| 4492 | mlir::Type boundArrayTy = fir::SequenceType::get( |
| 4493 | {2, static_cast<int64_t>(lbounds.size())}, builder->getI64Type()); |
| 4494 | mlir::Value boundArray = builder->create<fir::AllocaOp>(loc, boundArrayTy); |
| 4495 | mlir::Value array = builder->create<fir::UndefOp>(loc, boundArrayTy); |
| 4496 | for (unsigned i = 0; i < lbounds.size(); ++i) { |
| 4497 | array = builder->create<fir::InsertValueOp>( |
| 4498 | loc, boundArrayTy, array, lbounds[i], |
| 4499 | builder->getArrayAttr( |
| 4500 | {builder->getIntegerAttr(builder->getIndexType(), 0), |
| 4501 | builder->getIntegerAttr(builder->getIndexType(), |
| 4502 | static_cast<int>(i))})); |
| 4503 | array = builder->create<fir::InsertValueOp>( |
| 4504 | loc, boundArrayTy, array, ubounds[i], |
| 4505 | builder->getArrayAttr( |
| 4506 | {builder->getIntegerAttr(builder->getIndexType(), 1), |
| 4507 | builder->getIntegerAttr(builder->getIndexType(), |
| 4508 | static_cast<int>(i))})); |
| 4509 | } |
| 4510 | builder->create<fir::StoreOp>(loc, array, boundArray); |
| 4511 | mlir::Type boxTy = fir::BoxType::get(boundArrayTy); |
| 4512 | mlir::Value ext = |
| 4513 | builder->createIntegerConstant(loc, indexTy, lbounds.size()); |
| 4514 | mlir::Value c2 = builder->createIntegerConstant(loc, indexTy, 2); |
| 4515 | llvm::SmallVector<mlir::Value> shapes = {c2, ext}; |
| 4516 | mlir::Value shapeOp = builder->genShape(loc, shapes); |
| 4517 | return builder->create<fir::EmboxOp>(loc, boxTy, boundArray, shapeOp); |
| 4518 | } |
| 4519 | |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4520 | // Pointer assignment with bounds-remapping. R1036: a bounds-remapping is a |
| 4521 | // pair, lower bound and upper bound. |
| 4522 | void genPointerAssignment( |
| 4523 | mlir::Location loc, const Fortran::evaluate::Assignment &assign, |
| 4524 | const Fortran::evaluate::Assignment::BoundsRemapping &boundExprs) { |
| 4525 | Fortran::lower::StatementContext stmtCtx; |
| 4526 | llvm::SmallVector<mlir::Value> lbounds; |
| 4527 | llvm::SmallVector<mlir::Value> ubounds; |
| 4528 | for (const std::pair<Fortran::evaluate::ExtentExpr, |
| 4529 | Fortran::evaluate::ExtentExpr> &pair : boundExprs) { |
| 4530 | const Fortran::evaluate::ExtentExpr &lbExpr = pair.first; |
| 4531 | const Fortran::evaluate::ExtentExpr &ubExpr = pair.second; |
| 4532 | lbounds.push_back(fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx))); |
| 4533 | ubounds.push_back(fir::getBase(genExprValue(toEvExpr(ubExpr), stmtCtx))); |
| 4534 | } |
| 4535 | |
| 4536 | std::optional<Fortran::evaluate::DynamicType> lhsType = |
| 4537 | assign.lhs.GetType(); |
| 4538 | std::optional<Fortran::evaluate::DynamicType> rhsType = |
| 4539 | assign.rhs.GetType(); |
| 4540 | // Polymorphic lhs/rhs need more care. See F2018 10.2.2.3. |
| 4541 | if ((lhsType && lhsType->IsPolymorphic()) || |
| 4542 | (rhsType && rhsType->IsPolymorphic())) { |
| 4543 | if (!lowerToHighLevelFIR() && explicitIterationSpace()) |
| 4544 | TODO(loc, "polymorphic pointer assignment in FORALL"); |
| 4545 | |
Jean Perier | 04a920b7 | 2023-04-03 09:18:41 +0200 | [diff] [blame] | 4546 | fir::MutableBoxValue lhsMutableBox = genExprMutableBox(loc, assign.lhs); |
| 4547 | if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>( |
| 4548 | assign.rhs)) { |
| 4549 | fir::factory::disassociateMutableBox(*builder, loc, lhsMutableBox); |
| 4550 | return; |
| 4551 | } |
| 4552 | mlir::Value lhs = lhsMutableBox.getAddr(); |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4553 | mlir::Value rhs = fir::getBase(genExprBox(loc, assign.rhs, stmtCtx)); |
Valentin Clement | 3b73fc3 | 2023-02-06 21:06:44 +0100 | [diff] [blame] | 4554 | mlir::Value boundsDesc = createBoundArray(lbounds, ubounds, loc); |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4555 | Fortran::lower::genPointerAssociateRemapping(*builder, loc, lhs, rhs, |
| 4556 | boundsDesc); |
| 4557 | return; |
| 4558 | } |
| 4559 | if (!lowerToHighLevelFIR() && explicitIterationSpace()) { |
| 4560 | // Pointer assignment in FORALL context. Copy the rhs box value |
| 4561 | // into the lhs box variable. |
| 4562 | genArrayAssignment(assign, stmtCtx, lbounds, ubounds); |
| 4563 | return; |
| 4564 | } |
| 4565 | fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs); |
| 4566 | if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>( |
| 4567 | assign.rhs)) { |
| 4568 | fir::factory::disassociateMutableBox(*builder, loc, lhs); |
| 4569 | return; |
| 4570 | } |
jeanPerier | e769fb8 | 2024-02-15 09:06:42 +0100 | [diff] [blame] | 4571 | if (lowerToHighLevelFIR()) { |
| 4572 | fir::ExtendedValue rhs = genExprAddr(assign.rhs, stmtCtx); |
| 4573 | fir::factory::associateMutableBoxWithRemap(*builder, loc, lhs, rhs, |
| 4574 | lbounds, ubounds); |
| 4575 | return; |
| 4576 | } |
| 4577 | // Legacy lowering below. |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4578 | // Do not generate a temp in case rhs is an array section. |
| 4579 | fir::ExtendedValue rhs = |
| 4580 | Fortran::lower::isArraySectionWithoutVectorSubscript(assign.rhs) |
| 4581 | ? Fortran::lower::createSomeArrayBox(*this, assign.rhs, |
| 4582 | localSymbols, stmtCtx) |
| 4583 | : genExprAddr(assign.rhs, stmtCtx); |
| 4584 | fir::factory::associateMutableBoxWithRemap(*builder, loc, lhs, rhs, lbounds, |
| 4585 | ubounds); |
jeanPerier | e769fb8 | 2024-02-15 09:06:42 +0100 | [diff] [blame] | 4586 | if (explicitIterationSpace()) { |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4587 | mlir::ValueRange inners = explicitIterSpace.getInnerArgs(); |
| 4588 | if (!inners.empty()) |
| 4589 | builder->create<fir::ResultOp>(loc, inners); |
| 4590 | } |
| 4591 | } |
| 4592 | |
jeanPerier | 7046202 | 2023-10-27 09:07:48 +0200 | [diff] [blame] | 4593 | /// Given converted LHS and RHS of the assignment, materialize any |
| 4594 | /// implicit conversion of the RHS to the LHS type. The front-end |
| 4595 | /// usually already makes those explicit, except for non-standard |
| 4596 | /// LOGICAL <-> INTEGER, or if the LHS is a whole allocatable |
| 4597 | /// (making the conversion explicit in the front-end would prevent |
| 4598 | /// propagation of the LHS lower bound in the reallocation). |
| 4599 | /// If array temporaries or values are created, the cleanups are |
| 4600 | /// added in the statement context. |
| 4601 | hlfir::Entity genImplicitConvert(const Fortran::evaluate::Assignment &assign, |
| 4602 | hlfir::Entity rhs, bool preserveLowerBounds, |
| 4603 | Fortran::lower::StatementContext &stmtCtx) { |
Slava Zakharin | ec2c0e0 | 2023-05-04 08:47:28 -0700 | [diff] [blame] | 4604 | mlir::Location loc = toLocation(); |
| 4605 | auto &builder = getFirOpBuilder(); |
jeanPerier | 7046202 | 2023-10-27 09:07:48 +0200 | [diff] [blame] | 4606 | mlir::Type toType = genType(assign.lhs); |
| 4607 | auto valueAndPair = hlfir::genTypeAndKindConvert(loc, builder, rhs, toType, |
| 4608 | preserveLowerBounds); |
| 4609 | if (valueAndPair.second) |
| 4610 | stmtCtx.attachCleanup(*valueAndPair.second); |
| 4611 | return hlfir::Entity{valueAndPair.first}; |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4612 | } |
| 4613 | |
Jean Perier | 6716923 | 2023-06-26 13:06:43 +0200 | [diff] [blame] | 4614 | bool firstDummyIsPointerOrAllocatable( |
| 4615 | const Fortran::evaluate::ProcedureRef &userDefinedAssignment) { |
| 4616 | using DummyAttr = Fortran::evaluate::characteristics::DummyDataObject::Attr; |
| 4617 | if (auto procedure = |
| 4618 | Fortran::evaluate::characteristics::Procedure::Characterize( |
Peter Klausler | cb26391 | 2024-04-22 15:21:45 -0700 | [diff] [blame] | 4619 | userDefinedAssignment.proc(), getFoldingContext(), |
| 4620 | /*emitError=*/false)) |
Jean Perier | 6716923 | 2023-06-26 13:06:43 +0200 | [diff] [blame] | 4621 | if (!procedure->dummyArguments.empty()) |
| 4622 | if (const auto *dataArg = std::get_if< |
| 4623 | Fortran::evaluate::characteristics::DummyDataObject>( |
| 4624 | &procedure->dummyArguments[0].u)) |
| 4625 | return dataArg->attrs.test(DummyAttr::Pointer) || |
| 4626 | dataArg->attrs.test(DummyAttr::Allocatable); |
| 4627 | return false; |
| 4628 | } |
| 4629 | |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4630 | void genCUDADataTransfer(fir::FirOpBuilder &builder, mlir::Location loc, |
| 4631 | const Fortran::evaluate::Assignment &assign, |
| 4632 | hlfir::Entity &lhs, hlfir::Entity &rhs) { |
Valentin Clement (バレンタイン クレメン) | 8e8dccd | 2024-06-19 13:35:02 -0700 | [diff] [blame] | 4633 | bool lhsIsDevice = Fortran::evaluate::HasCUDADeviceAttrs(assign.lhs); |
| 4634 | bool rhsIsDevice = Fortran::evaluate::HasCUDADeviceAttrs(assign.rhs); |
Valentin Clement (バレンタイン クレメン) | 1fc3ce1c | 2024-05-21 11:23:55 -0700 | [diff] [blame] | 4635 | |
Valentin Clement (バレンタイン クレメン) | 900cd62 | 2024-08-27 10:03:15 -0700 | [diff] [blame] | 4636 | auto getRefFromValue = [](mlir::Value val) -> mlir::Value { |
Valentin Clement (バレンタイン クレメン) | 1fc3ce1c | 2024-05-21 11:23:55 -0700 | [diff] [blame] | 4637 | if (auto loadOp = |
| 4638 | mlir::dyn_cast_or_null<fir::LoadOp>(val.getDefiningOp())) |
| 4639 | return loadOp.getMemref(); |
Valentin Clement (バレンタイン クレメン) | 900cd62 | 2024-08-27 10:03:15 -0700 | [diff] [blame] | 4640 | if (!mlir::isa<fir::BaseBoxType>(val.getType())) |
| 4641 | return val; |
| 4642 | if (auto declOp = |
| 4643 | mlir::dyn_cast_or_null<hlfir::DeclareOp>(val.getDefiningOp())) { |
| 4644 | if (!declOp.getShape()) |
| 4645 | return val; |
| 4646 | if (mlir::isa<fir::ReferenceType>(declOp.getMemref().getType())) |
Valentin Clement (バレンタイン クレメン) | ccbee71 | 2024-08-27 17:36:31 -0700 | [diff] [blame] | 4647 | return declOp.getResults()[1]; |
Valentin Clement (バレンタイン クレメン) | 900cd62 | 2024-08-27 10:03:15 -0700 | [diff] [blame] | 4648 | } |
Valentin Clement (バレンタイン クレメン) | 1fc3ce1c | 2024-05-21 11:23:55 -0700 | [diff] [blame] | 4649 | return val; |
| 4650 | }; |
| 4651 | |
Valentin Clement (バレンタイン クレメン) | 900cd62 | 2024-08-27 10:03:15 -0700 | [diff] [blame] | 4652 | auto getShapeFromDecl = [](mlir::Value val) -> mlir::Value { |
| 4653 | if (!mlir::isa<fir::BaseBoxType>(val.getType())) |
| 4654 | return {}; |
| 4655 | if (auto declOp = |
| 4656 | mlir::dyn_cast_or_null<hlfir::DeclareOp>(val.getDefiningOp())) |
| 4657 | return declOp.getShape(); |
| 4658 | return {}; |
| 4659 | }; |
| 4660 | |
| 4661 | mlir::Value rhsVal = getRefFromValue(rhs.getBase()); |
| 4662 | mlir::Value lhsVal = getRefFromValue(lhs.getBase()); |
| 4663 | // Get shape from the rhs if available otherwise get it from lhs. |
| 4664 | mlir::Value shape = getShapeFromDecl(rhs.getBase()); |
| 4665 | if (!shape) |
| 4666 | shape = getShapeFromDecl(lhs.getBase()); |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4667 | |
| 4668 | // device = host |
Valentin Clement (バレンタイン クレメン) | 4e6745c | 2024-03-25 11:53:39 -0700 | [diff] [blame] | 4669 | if (lhsIsDevice && !rhsIsDevice) { |
Valentin Clement (バレンタイン クレメン) | 45daa4f | 2024-05-17 09:37:53 -0700 | [diff] [blame] | 4670 | auto transferKindAttr = cuf::DataTransferKindAttr::get( |
| 4671 | builder.getContext(), cuf::DataTransferKind::HostDevice); |
Valentin Clement (バレンタイン クレメン) | 4e6745c | 2024-03-25 11:53:39 -0700 | [diff] [blame] | 4672 | if (!rhs.isVariable()) { |
Valentin Clement (バレンタイン クレメン) | 3ad7108c | 2024-07-17 08:39:18 -0700 | [diff] [blame] | 4673 | mlir::Value base = rhs; |
| 4674 | if (auto convertOp = |
| 4675 | mlir::dyn_cast<fir::ConvertOp>(rhs.getDefiningOp())) |
| 4676 | base = convertOp.getValue(); |
Valentin Clement (バレンタイン クレメン) | 0bc710f | 2024-05-21 12:42:30 -0700 | [diff] [blame] | 4677 | // Special case if the rhs is a constant. |
Valentin Clement (バレンタイン クレメン) | 3ad7108c | 2024-07-17 08:39:18 -0700 | [diff] [blame] | 4678 | if (matchPattern(base.getDefiningOp(), mlir::m_Constant())) { |
Valentin Clement (バレンタイン クレメン) | 900cd62 | 2024-08-27 10:03:15 -0700 | [diff] [blame] | 4679 | builder.create<cuf::DataTransferOp>(loc, base, lhsVal, shape, |
| 4680 | transferKindAttr); |
Valentin Clement (バレンタイン クレメン) | 0bc710f | 2024-05-21 12:42:30 -0700 | [diff] [blame] | 4681 | } else { |
| 4682 | auto associate = hlfir::genAssociateExpr( |
| 4683 | loc, builder, rhs, rhs.getType(), ".cuf_host_tmp"); |
| 4684 | builder.create<cuf::DataTransferOp>(loc, associate.getBase(), lhsVal, |
Valentin Clement (バレンタイン クレメン) | 900cd62 | 2024-08-27 10:03:15 -0700 | [diff] [blame] | 4685 | shape, transferKindAttr); |
Valentin Clement (バレンタイン クレメン) | 0bc710f | 2024-05-21 12:42:30 -0700 | [diff] [blame] | 4686 | builder.create<hlfir::EndAssociateOp>(loc, associate); |
| 4687 | } |
Valentin Clement (バレンタイン クレメン) | 4e6745c | 2024-03-25 11:53:39 -0700 | [diff] [blame] | 4688 | } else { |
Valentin Clement (バレンタイン クレメン) | 900cd62 | 2024-08-27 10:03:15 -0700 | [diff] [blame] | 4689 | builder.create<cuf::DataTransferOp>(loc, rhsVal, lhsVal, shape, |
| 4690 | transferKindAttr); |
Valentin Clement (バレンタイン クレメン) | 4e6745c | 2024-03-25 11:53:39 -0700 | [diff] [blame] | 4691 | } |
| 4692 | return; |
| 4693 | } |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4694 | |
| 4695 | // host = device |
| 4696 | if (!lhsIsDevice && rhsIsDevice) { |
Valentin Clement (バレンタイン クレメン) | 45daa4f | 2024-05-17 09:37:53 -0700 | [diff] [blame] | 4697 | auto transferKindAttr = cuf::DataTransferKindAttr::get( |
| 4698 | builder.getContext(), cuf::DataTransferKind::DeviceHost); |
Valentin Clement (バレンタイン クレメン) | 900cd62 | 2024-08-27 10:03:15 -0700 | [diff] [blame] | 4699 | builder.create<cuf::DataTransferOp>(loc, rhsVal, lhsVal, shape, |
Valentin Clement (バレンタイン クレメン) | 1fc3ce1c | 2024-05-21 11:23:55 -0700 | [diff] [blame] | 4700 | transferKindAttr); |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4701 | return; |
| 4702 | } |
| 4703 | |
Valentin Clement (バレンタイン クレメン) | 1fc3ce1c | 2024-05-21 11:23:55 -0700 | [diff] [blame] | 4704 | // device = device |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4705 | if (lhsIsDevice && rhsIsDevice) { |
| 4706 | assert(rhs.isVariable() && "CUDA Fortran assignment rhs is not legal"); |
Valentin Clement (バレンタイン クレメン) | 45daa4f | 2024-05-17 09:37:53 -0700 | [diff] [blame] | 4707 | auto transferKindAttr = cuf::DataTransferKindAttr::get( |
| 4708 | builder.getContext(), cuf::DataTransferKind::DeviceDevice); |
Valentin Clement (バレンタイン クレメン) | 900cd62 | 2024-08-27 10:03:15 -0700 | [diff] [blame] | 4709 | builder.create<cuf::DataTransferOp>(loc, rhsVal, lhsVal, shape, |
Valentin Clement (バレンタイン クレメン) | 1fc3ce1c | 2024-05-21 11:23:55 -0700 | [diff] [blame] | 4710 | transferKindAttr); |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4711 | return; |
| 4712 | } |
| 4713 | llvm_unreachable("Unhandled CUDA data transfer"); |
| 4714 | } |
| 4715 | |
| 4716 | llvm::SmallVector<mlir::Value> |
| 4717 | genCUDAImplicitDataTransfer(fir::FirOpBuilder &builder, mlir::Location loc, |
| 4718 | const Fortran::evaluate::Assignment &assign) { |
| 4719 | llvm::SmallVector<mlir::Value> temps; |
| 4720 | localSymbols.pushScope(); |
Valentin Clement (バレンタイン クレメン) | 45daa4f | 2024-05-17 09:37:53 -0700 | [diff] [blame] | 4721 | auto transferKindAttr = cuf::DataTransferKindAttr::get( |
| 4722 | builder.getContext(), cuf::DataTransferKind::DeviceHost); |
Jie Fu | 3f2f700 | 2024-04-06 07:31:53 +0800 | [diff] [blame] | 4723 | [[maybe_unused]] unsigned nbDeviceResidentObject = 0; |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4724 | for (const Fortran::semantics::Symbol &sym : |
| 4725 | Fortran::evaluate::CollectSymbols(assign.rhs)) { |
| 4726 | if (const auto *details = |
| 4727 | sym.GetUltimate() |
| 4728 | .detailsIf<Fortran::semantics::ObjectEntityDetails>()) { |
Valentin Clement (バレンタイン クレメン) | 8e8dccd | 2024-06-19 13:35:02 -0700 | [diff] [blame] | 4729 | if (details->cudaDataAttr() && |
| 4730 | *details->cudaDataAttr() != Fortran::common::CUDADataAttr::Pinned) { |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4731 | if (sym.owner().IsDerivedType() && IsAllocatable(sym.GetUltimate())) |
| 4732 | TODO(loc, "Device resident allocatable derived-type component"); |
| 4733 | // TODO: This should probably being checked in semantic and give a |
| 4734 | // proper error. |
| 4735 | assert( |
| 4736 | nbDeviceResidentObject <= 1 && |
| 4737 | "Only one reference to the device resident object is supported"); |
| 4738 | auto addr = getSymbolAddress(sym); |
| 4739 | hlfir::Entity entity{addr}; |
| 4740 | auto [temp, cleanup] = |
| 4741 | hlfir::createTempFromMold(loc, builder, entity); |
| 4742 | auto needCleanup = fir::getIntIfConstant(cleanup); |
Valentin Clement (バレンタイン クレメン) | 9b6504e | 2024-07-11 17:15:54 -0700 | [diff] [blame] | 4743 | if (needCleanup && *needCleanup) { |
| 4744 | if (auto declareOp = |
| 4745 | mlir::dyn_cast<hlfir::DeclareOp>(temp.getDefiningOp())) |
| 4746 | temps.push_back(declareOp.getMemref()); |
| 4747 | else |
| 4748 | temps.push_back(temp); |
| 4749 | } |
Valentin Clement (バレンタイン クレメン) | 09cdfd6 | 2024-04-25 08:50:52 -0700 | [diff] [blame] | 4750 | addSymbol(sym, |
| 4751 | hlfir::translateToExtendedValue(loc, builder, temp).first, |
| 4752 | /*forced=*/true); |
Valentin Clement (バレンタイン クレメン) | 7af61d5 | 2024-08-26 09:50:17 -0700 | [diff] [blame] | 4753 | builder.create<cuf::DataTransferOp>( |
| 4754 | loc, addr, temp, /*shape=*/mlir::Value{}, transferKindAttr); |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4755 | ++nbDeviceResidentObject; |
| 4756 | } |
| 4757 | } |
| 4758 | } |
| 4759 | return temps; |
Valentin Clement (バレンタイン クレメン) | 4e6745c | 2024-03-25 11:53:39 -0700 | [diff] [blame] | 4760 | } |
| 4761 | |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4762 | void genDataAssignment( |
| 4763 | const Fortran::evaluate::Assignment &assign, |
| 4764 | const Fortran::evaluate::ProcedureRef *userDefinedAssignment) { |
| 4765 | mlir::Location loc = getCurrentLocation(); |
| 4766 | fir::FirOpBuilder &builder = getFirOpBuilder(); |
Valentin Clement (バレンタイン クレメン) | 8a6a0f1 | 2024-03-18 17:11:04 -0700 | [diff] [blame] | 4767 | |
Valentin Clement (バレンタイン クレメン) | 478e516 | 2025-03-06 19:19:51 -0800 | [diff] [blame] | 4768 | bool isInDeviceContext = cuf::isCUDADeviceContext(builder.getRegion()); |
Valentin Clement (バレンタイン クレメン) | 0a41c8e | 2024-08-29 11:27:42 -0700 | [diff] [blame] | 4769 | |
Valentin Clement (バレンタイン クレメン) | d1fd369 | 2025-03-02 16:12:01 -0800 | [diff] [blame] | 4770 | bool isCUDATransfer = |
| 4771 | IsCUDADataTransfer(assign.lhs, assign.rhs) && !isInDeviceContext; |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4772 | bool hasCUDAImplicitTransfer = |
Valentin Clement (バレンタイン クレメン) | d1fd369 | 2025-03-02 16:12:01 -0800 | [diff] [blame] | 4773 | isCUDATransfer && |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4774 | Fortran::evaluate::HasCUDAImplicitTransfer(assign.rhs); |
| 4775 | llvm::SmallVector<mlir::Value> implicitTemps; |
Valentin Clement (バレンタイン クレメン) | 3433e41 | 2024-11-26 17:04:00 -0800 | [diff] [blame] | 4776 | |
Valentin Clement (バレンタイン クレメン) | 5cfd5d1 | 2024-04-25 08:50:34 -0700 | [diff] [blame] | 4777 | if (hasCUDAImplicitTransfer && !isInDeviceContext) |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4778 | implicitTemps = genCUDAImplicitDataTransfer(builder, loc, assign); |
Valentin Clement (バレンタイン クレメン) | 8a6a0f1 | 2024-03-18 17:11:04 -0700 | [diff] [blame] | 4779 | |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4780 | // Gather some information about the assignment that will impact how it is |
| 4781 | // lowered. |
| 4782 | const bool isWholeAllocatableAssignment = |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 4783 | !userDefinedAssignment && !isInsideHlfirWhere() && |
Slava Zakharin | 9d33874 | 2024-12-17 09:06:05 -0800 | [diff] [blame] | 4784 | Fortran::lower::isWholeAllocatable(assign.lhs) && |
| 4785 | bridge.getLoweringOptions().getReallocateLHS(); |
Jean Perier | 6716923 | 2023-06-26 13:06:43 +0200 | [diff] [blame] | 4786 | const bool isUserDefAssignToPointerOrAllocatable = |
| 4787 | userDefinedAssignment && |
| 4788 | firstDummyIsPointerOrAllocatable(*userDefinedAssignment); |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4789 | std::optional<Fortran::evaluate::DynamicType> lhsType = |
| 4790 | assign.lhs.GetType(); |
| 4791 | const bool keepLhsLengthInAllocatableAssignment = |
| 4792 | isWholeAllocatableAssignment && lhsType.has_value() && |
| 4793 | lhsType->category() == Fortran::common::TypeCategory::Character && |
| 4794 | !lhsType->HasDeferredTypeParameter(); |
| 4795 | const bool lhsHasVectorSubscripts = |
| 4796 | Fortran::evaluate::HasVectorSubscript(assign.lhs); |
| 4797 | |
| 4798 | // Helper to generate the code evaluating the right-hand side. |
| 4799 | auto evaluateRhs = [&](Fortran::lower::StatementContext &stmtCtx) { |
| 4800 | hlfir::Entity rhs = Fortran::lower::convertExprToHLFIR( |
| 4801 | loc, *this, assign.rhs, localSymbols, stmtCtx); |
| 4802 | // Load trivial scalar RHS to allow the loads to be hoisted outside of |
| 4803 | // loops early if possible. This also dereferences pointer and |
| 4804 | // allocatable RHS: the target is being assigned from. |
| 4805 | rhs = hlfir::loadTrivialScalar(loc, builder, rhs); |
jeanPerier | 7046202 | 2023-10-27 09:07:48 +0200 | [diff] [blame] | 4806 | // In intrinsic assignments, the LHS type may not match the RHS type, in |
| 4807 | // which case an implicit conversion of the LHS must be done. The |
| 4808 | // front-end usually makes it explicit, unless it cannot (whole |
| 4809 | // allocatable LHS or Logical<->Integer assignment extension). Recognize |
| 4810 | // any type mismatches here and insert explicit scalar convert or |
| 4811 | // ElementalOp for array assignment. Preserve the RHS lower bounds on the |
| 4812 | // converted entity in case of assignment to whole allocatables so to |
| 4813 | // propagate the lower bounds to the LHS in case of reallocation. |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4814 | if (!userDefinedAssignment) |
jeanPerier | 7046202 | 2023-10-27 09:07:48 +0200 | [diff] [blame] | 4815 | rhs = genImplicitConvert(assign, rhs, isWholeAllocatableAssignment, |
| 4816 | stmtCtx); |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4817 | return rhs; |
| 4818 | }; |
| 4819 | |
| 4820 | // Helper to generate the code evaluating the left-hand side. |
| 4821 | auto evaluateLhs = [&](Fortran::lower::StatementContext &stmtCtx) { |
| 4822 | hlfir::Entity lhs = Fortran::lower::convertExprToHLFIR( |
| 4823 | loc, *this, assign.lhs, localSymbols, stmtCtx); |
| 4824 | // Dereference pointer LHS: the target is being assigned to. |
| 4825 | // Same for allocatables outside of whole allocatable assignments. |
Jean Perier | 6716923 | 2023-06-26 13:06:43 +0200 | [diff] [blame] | 4826 | if (!isWholeAllocatableAssignment && |
| 4827 | !isUserDefAssignToPointerOrAllocatable) |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4828 | lhs = hlfir::derefPointersAndAllocatables(loc, builder, lhs); |
| 4829 | return lhs; |
| 4830 | }; |
| 4831 | |
| 4832 | if (!isInsideHlfirForallOrWhere() && !lhsHasVectorSubscripts && |
| 4833 | !userDefinedAssignment) { |
| 4834 | Fortran::lower::StatementContext localStmtCtx; |
| 4835 | hlfir::Entity rhs = evaluateRhs(localStmtCtx); |
| 4836 | hlfir::Entity lhs = evaluateLhs(localStmtCtx); |
Valentin Clement (バレンタイン クレメン) | eb5907d | 2024-04-26 13:31:34 -0700 | [diff] [blame] | 4837 | if (isCUDATransfer && !hasCUDAImplicitTransfer) |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4838 | genCUDADataTransfer(builder, loc, assign, lhs, rhs); |
| 4839 | else |
Valentin Clement (バレンタイン クレメン) | 4e6745c | 2024-03-25 11:53:39 -0700 | [diff] [blame] | 4840 | builder.create<hlfir::AssignOp>(loc, rhs, lhs, |
| 4841 | isWholeAllocatableAssignment, |
| 4842 | keepLhsLengthInAllocatableAssignment); |
Valentin Clement (バレンタイン クレメン) | 5cfd5d1 | 2024-04-25 08:50:34 -0700 | [diff] [blame] | 4843 | if (hasCUDAImplicitTransfer && !isInDeviceContext) { |
Valentin Clement (バレンタイン クレメン) | 953aa10 | 2024-04-05 09:11:37 -0700 | [diff] [blame] | 4844 | localSymbols.popScope(); |
| 4845 | for (mlir::Value temp : implicitTemps) |
| 4846 | builder.create<fir::FreeMemOp>(loc, temp); |
Valentin Clement (バレンタイン クレメン) | 4e6745c | 2024-03-25 11:53:39 -0700 | [diff] [blame] | 4847 | } |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4848 | return; |
| 4849 | } |
| 4850 | // Assignments inside Forall, Where, or assignments to a vector subscripted |
| 4851 | // left-hand side requires using an hlfir.region_assign in HLFIR. The |
| 4852 | // right-hand side and left-hand side must be evaluated inside the |
| 4853 | // hlfir.region_assign regions. |
| 4854 | auto regionAssignOp = builder.create<hlfir::RegionAssignOp>(loc); |
| 4855 | |
| 4856 | // Lower RHS in its own region. |
| 4857 | builder.createBlock(®ionAssignOp.getRhsRegion()); |
| 4858 | Fortran::lower::StatementContext rhsContext; |
| 4859 | hlfir::Entity rhs = evaluateRhs(rhsContext); |
| 4860 | auto rhsYieldOp = builder.create<hlfir::YieldOp>(loc, rhs); |
jeanPerier | c7c5666 | 2024-05-14 13:34:46 +0200 | [diff] [blame] | 4861 | Fortran::lower::genCleanUpInRegionIfAny( |
| 4862 | loc, builder, rhsYieldOp.getCleanup(), rhsContext); |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4863 | // Lower LHS in its own region. |
| 4864 | builder.createBlock(®ionAssignOp.getLhsRegion()); |
| 4865 | Fortran::lower::StatementContext lhsContext; |
Jean Perier | 6716923 | 2023-06-26 13:06:43 +0200 | [diff] [blame] | 4866 | mlir::Value lhsYield = nullptr; |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4867 | if (!lhsHasVectorSubscripts) { |
| 4868 | hlfir::Entity lhs = evaluateLhs(lhsContext); |
| 4869 | auto lhsYieldOp = builder.create<hlfir::YieldOp>(loc, lhs); |
jeanPerier | c7c5666 | 2024-05-14 13:34:46 +0200 | [diff] [blame] | 4870 | Fortran::lower::genCleanUpInRegionIfAny( |
| 4871 | loc, builder, lhsYieldOp.getCleanup(), lhsContext); |
Jean Perier | 6716923 | 2023-06-26 13:06:43 +0200 | [diff] [blame] | 4872 | lhsYield = lhs; |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4873 | } else { |
Jean Perier | c7ff45a | 2023-05-09 09:22:24 +0200 | [diff] [blame] | 4874 | hlfir::ElementalAddrOp elementalAddr = |
| 4875 | Fortran::lower::convertVectorSubscriptedExprToElementalAddr( |
| 4876 | loc, *this, assign.lhs, localSymbols, lhsContext); |
jeanPerier | c7c5666 | 2024-05-14 13:34:46 +0200 | [diff] [blame] | 4877 | Fortran::lower::genCleanUpInRegionIfAny( |
| 4878 | loc, builder, elementalAddr.getCleanup(), lhsContext); |
Jean Perier | 6716923 | 2023-06-26 13:06:43 +0200 | [diff] [blame] | 4879 | lhsYield = elementalAddr.getYieldOp().getEntity(); |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4880 | } |
Jean Perier | 6716923 | 2023-06-26 13:06:43 +0200 | [diff] [blame] | 4881 | assert(lhsYield && "must have been set"); |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4882 | |
| 4883 | // Add "realloc" flag to hlfir.region_assign. |
| 4884 | if (isWholeAllocatableAssignment) |
| 4885 | TODO(loc, "assignment to a whole allocatable inside FORALL"); |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4886 | |
Jean Perier | 6716923 | 2023-06-26 13:06:43 +0200 | [diff] [blame] | 4887 | // Generate the hlfir.region_assign userDefinedAssignment region. |
| 4888 | if (userDefinedAssignment) { |
| 4889 | mlir::Type rhsType = rhs.getType(); |
| 4890 | mlir::Type lhsType = lhsYield.getType(); |
| 4891 | if (userDefinedAssignment->IsElemental()) { |
| 4892 | rhsType = hlfir::getEntityElementType(rhs); |
| 4893 | lhsType = hlfir::getEntityElementType(hlfir::Entity{lhsYield}); |
| 4894 | } |
| 4895 | builder.createBlock(®ionAssignOp.getUserDefinedAssignment(), |
| 4896 | mlir::Region::iterator{}, {rhsType, lhsType}, |
| 4897 | {loc, loc}); |
| 4898 | auto end = builder.create<fir::FirEndOp>(loc); |
| 4899 | builder.setInsertionPoint(end); |
| 4900 | hlfir::Entity lhsBlockArg{regionAssignOp.getUserAssignmentLhs()}; |
| 4901 | hlfir::Entity rhsBlockArg{regionAssignOp.getUserAssignmentRhs()}; |
| 4902 | Fortran::lower::convertUserDefinedAssignmentToHLFIR( |
| 4903 | loc, *this, *userDefinedAssignment, lhsBlockArg, rhsBlockArg, |
| 4904 | localSymbols); |
| 4905 | } |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4906 | builder.setInsertionPointAfter(regionAssignOp); |
Slava Zakharin | ec2c0e0 | 2023-05-04 08:47:28 -0700 | [diff] [blame] | 4907 | } |
| 4908 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 4909 | /// Shared for both assignments and pointer assignments. |
| 4910 | void genAssignment(const Fortran::evaluate::Assignment &assign) { |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 4911 | mlir::Location loc = toLocation(); |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4912 | if (lowerToHighLevelFIR()) { |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 4913 | Fortran::common::visit( |
Jean Perier | dd73bfa | 2022-11-15 12:01:21 +0100 | [diff] [blame] | 4914 | Fortran::common::visitors{ |
Jean Perier | dd73bfa | 2022-11-15 12:01:21 +0100 | [diff] [blame] | 4915 | [&](const Fortran::evaluate::Assignment::Intrinsic &) { |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4916 | genDataAssignment(assign, /*userDefinedAssignment=*/nullptr); |
Jean Perier | dd73bfa | 2022-11-15 12:01:21 +0100 | [diff] [blame] | 4917 | }, |
Jean Perier | dd73bfa | 2022-11-15 12:01:21 +0100 | [diff] [blame] | 4918 | [&](const Fortran::evaluate::ProcedureRef &procRef) { |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4919 | genDataAssignment(assign, /*userDefinedAssignment=*/&procRef); |
Jean Perier | dd73bfa | 2022-11-15 12:01:21 +0100 | [diff] [blame] | 4920 | }, |
Jean Perier | dd73bfa | 2022-11-15 12:01:21 +0100 | [diff] [blame] | 4921 | [&](const Fortran::evaluate::Assignment::BoundsSpec &lbExprs) { |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4922 | if (isInsideHlfirForallOrWhere()) |
jeanPerier | 3ff3b29 | 2025-03-14 10:51:46 +0100 | [diff] [blame] | 4923 | genForallPointerAssignment(loc, assign); |
jeanPerier | 7302e1b | 2025-03-05 11:24:04 +0100 | [diff] [blame] | 4924 | else |
| 4925 | genPointerAssignment(loc, assign, lbExprs); |
Jean Perier | dd73bfa | 2022-11-15 12:01:21 +0100 | [diff] [blame] | 4926 | }, |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4927 | [&](const Fortran::evaluate::Assignment::BoundsRemapping |
| 4928 | &boundExprs) { |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 4929 | if (isInsideHlfirForallOrWhere()) |
jeanPerier | 3ff3b29 | 2025-03-14 10:51:46 +0100 | [diff] [blame] | 4930 | genForallPointerAssignment(loc, assign); |
| 4931 | else |
| 4932 | genPointerAssignment(loc, assign, boundExprs); |
Jean Perier | dd73bfa | 2022-11-15 12:01:21 +0100 | [diff] [blame] | 4933 | }, |
| 4934 | }, |
| 4935 | assign.u); |
| 4936 | return; |
| 4937 | } |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 4938 | if (explicitIterationSpace()) { |
| 4939 | Fortran::lower::createArrayLoads(*this, explicitIterSpace, localSymbols); |
| 4940 | explicitIterSpace.genLoopNest(); |
| 4941 | } |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 4942 | Fortran::lower::StatementContext stmtCtx; |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 4943 | Fortran::common::visit( |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 4944 | Fortran::common::visitors{ |
| 4945 | // [1] Plain old assignment. |
| 4946 | [&](const Fortran::evaluate::Assignment::Intrinsic &) { |
| 4947 | const Fortran::semantics::Symbol *sym = |
| 4948 | Fortran::evaluate::GetLastSymbol(assign.lhs); |
| 4949 | |
| 4950 | if (!sym) |
| 4951 | TODO(loc, "assignment to pointer result of function reference"); |
| 4952 | |
| 4953 | std::optional<Fortran::evaluate::DynamicType> lhsType = |
| 4954 | assign.lhs.GetType(); |
| 4955 | assert(lhsType && "lhs cannot be typeless"); |
Valentin Clement | 33c29a8 | 2023-02-21 10:14:00 +0100 | [diff] [blame] | 4956 | std::optional<Fortran::evaluate::DynamicType> rhsType = |
| 4957 | assign.rhs.GetType(); |
Valentin Clement | 97492fd1a | 2023-01-31 13:46:12 +0100 | [diff] [blame] | 4958 | |
Valentin Clement | 33c29a8 | 2023-02-21 10:14:00 +0100 | [diff] [blame] | 4959 | // Assignment to/from polymorphic entities are done with the |
| 4960 | // runtime. |
| 4961 | if (lhsType->IsPolymorphic() || |
| 4962 | lhsType->IsUnlimitedPolymorphic() || |
Peter Steinfeld | 18983df | 2023-02-22 10:51:54 -0800 | [diff] [blame] | 4963 | (rhsType && (rhsType->IsPolymorphic() || |
| 4964 | rhsType->IsUnlimitedPolymorphic()))) { |
Valentin Clement | 33c29a8 | 2023-02-21 10:14:00 +0100 | [diff] [blame] | 4965 | mlir::Value lhs; |
| 4966 | if (Fortran::lower::isWholeAllocatable(assign.lhs)) |
| 4967 | lhs = genExprMutableBox(loc, assign.lhs).getAddr(); |
| 4968 | else |
| 4969 | lhs = fir::getBase(genExprBox(loc, assign.lhs, stmtCtx)); |
Valentin Clement | f8ea349 | 2022-12-02 15:51:01 +0100 | [diff] [blame] | 4970 | mlir::Value rhs = |
| 4971 | fir::getBase(genExprBox(loc, assign.rhs, stmtCtx)); |
Valentin Clement | 4f3c9854 | 2023-03-06 09:35:36 +0100 | [diff] [blame] | 4972 | if ((lhsType->IsPolymorphic() || |
| 4973 | lhsType->IsUnlimitedPolymorphic()) && |
| 4974 | Fortran::lower::isWholeAllocatable(assign.lhs)) |
| 4975 | fir::runtime::genAssignPolymorphic(*builder, loc, lhs, rhs); |
| 4976 | else |
| 4977 | fir::runtime::genAssign(*builder, loc, lhs, rhs); |
Valentin Clement | f8ea349 | 2022-12-02 15:51:01 +0100 | [diff] [blame] | 4978 | return; |
| 4979 | } |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 4980 | |
| 4981 | // Note: No ad-hoc handling for pointers is required here. The |
| 4982 | // target will be assigned as per 2018 10.2.1.3 p2. genExprAddr |
| 4983 | // on a pointer returns the target address and not the address of |
| 4984 | // the pointer variable. |
| 4985 | |
| 4986 | if (assign.lhs.Rank() > 0 || explicitIterationSpace()) { |
Valentin Clement | 97492fd1a | 2023-01-31 13:46:12 +0100 | [diff] [blame] | 4987 | if (isDerivedCategory(lhsType->category()) && |
| 4988 | Fortran::semantics::IsFinalizable( |
| 4989 | lhsType->GetDerivedTypeSpec())) |
| 4990 | TODO(loc, "derived-type finalization with array assignment"); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 4991 | // Array assignment |
| 4992 | // See Fortran 2018 10.2.1.3 p5, p6, and p7 |
| 4993 | genArrayAssignment(assign, stmtCtx); |
| 4994 | return; |
| 4995 | } |
| 4996 | |
| 4997 | // Scalar assignment |
| 4998 | const bool isNumericScalar = |
| 4999 | isNumericScalarCategory(lhsType->category()); |
Kelvin Li | ef93417 | 2023-05-23 19:02:49 -0400 | [diff] [blame] | 5000 | const bool isVector = |
| 5001 | isDerivedCategory(lhsType->category()) && |
| 5002 | lhsType->GetDerivedTypeSpec().IsVectorType(); |
| 5003 | fir::ExtendedValue rhs = (isNumericScalar || isVector) |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5004 | ? genExprValue(assign.rhs, stmtCtx) |
| 5005 | : genExprAddr(assign.rhs, stmtCtx); |
Eric Schweitz | 1bffc75 | 2022-04-22 13:59:17 -0700 | [diff] [blame] | 5006 | const bool lhsIsWholeAllocatable = |
| 5007 | Fortran::lower::isWholeAllocatable(assign.lhs); |
Kazu Hirata | c092158 | 2023-01-07 22:26:48 -0800 | [diff] [blame] | 5008 | std::optional<fir::factory::MutableBoxReallocation> lhsRealloc; |
| 5009 | std::optional<fir::MutableBoxValue> lhsMutableBox; |
Valentin Clement | 97492fd1a | 2023-01-31 13:46:12 +0100 | [diff] [blame] | 5010 | |
Valentin Clement | 7f0074a | 2023-02-03 12:21:59 +0100 | [diff] [blame] | 5011 | // Set flag to know if the LHS needs finalization. Polymorphic, |
| 5012 | // unlimited polymorphic assignment will be done with genAssign. |
| 5013 | // Assign runtime function performs the finalization. |
| 5014 | bool needFinalization = !lhsType->IsPolymorphic() && |
| 5015 | !lhsType->IsUnlimitedPolymorphic() && |
| 5016 | (isDerivedCategory(lhsType->category()) && |
| 5017 | Fortran::semantics::IsFinalizable( |
| 5018 | lhsType->GetDerivedTypeSpec())); |
Valentin Clement | 97492fd1a | 2023-01-31 13:46:12 +0100 | [diff] [blame] | 5019 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5020 | auto lhs = [&]() -> fir::ExtendedValue { |
| 5021 | if (lhsIsWholeAllocatable) { |
| 5022 | lhsMutableBox = genExprMutableBox(loc, assign.lhs); |
Valentin Clement | 7f0074a | 2023-02-03 12:21:59 +0100 | [diff] [blame] | 5023 | // Finalize if needed. |
| 5024 | if (needFinalization) { |
| 5025 | mlir::Value isAllocated = |
| 5026 | fir::factory::genIsAllocatedOrAssociatedTest( |
| 5027 | *builder, loc, *lhsMutableBox); |
| 5028 | builder->genIfThen(loc, isAllocated) |
| 5029 | .genThen([&]() { |
| 5030 | fir::runtime::genDerivedTypeDestroy( |
| 5031 | *builder, loc, fir::getBase(*lhsMutableBox)); |
| 5032 | }) |
| 5033 | .end(); |
| 5034 | needFinalization = false; |
| 5035 | } |
| 5036 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5037 | llvm::SmallVector<mlir::Value> lengthParams; |
| 5038 | if (const fir::CharBoxValue *charBox = rhs.getCharBox()) |
| 5039 | lengthParams.push_back(charBox->getLen()); |
Eric Schweitz | 1bffc75 | 2022-04-22 13:59:17 -0700 | [diff] [blame] | 5040 | else if (fir::isDerivedWithLenParameters(rhs)) |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5041 | TODO(loc, "assignment to derived type allocatable with " |
Valentin Clement | 0dd4fb0 | 2022-07-01 10:36:45 +0200 | [diff] [blame] | 5042 | "LEN parameters"); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5043 | lhsRealloc = fir::factory::genReallocIfNeeded( |
| 5044 | *builder, loc, *lhsMutableBox, |
Kazu Hirata | 9a41739 | 2022-12-03 12:14:21 -0800 | [diff] [blame] | 5045 | /*shape=*/std::nullopt, lengthParams); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5046 | return lhsRealloc->newValue; |
| 5047 | } |
| 5048 | return genExprAddr(assign.lhs, stmtCtx); |
| 5049 | }(); |
| 5050 | |
Kelvin Li | ef93417 | 2023-05-23 19:02:49 -0400 | [diff] [blame] | 5051 | if (isNumericScalar || isVector) { |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5052 | // Fortran 2018 10.2.1.3 p8 and p9 |
| 5053 | // Conversions should have been inserted by semantic analysis, |
| 5054 | // but they can be incorrect between the rhs and lhs. Correct |
| 5055 | // that here. |
| 5056 | mlir::Value addr = fir::getBase(lhs); |
| 5057 | mlir::Value val = fir::getBase(rhs); |
| 5058 | // A function with multiple entry points returning different |
| 5059 | // types tags all result variables with one of the largest |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5060 | // types to allow them to share the same storage. Assignment |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5061 | // to a result variable of one of the other types requires |
| 5062 | // conversion to the actual type. |
| 5063 | mlir::Type toTy = genType(assign.lhs); |
Mark Danial | a1c736e | 2023-08-22 12:10:08 -0400 | [diff] [blame] | 5064 | |
| 5065 | // If Cray pointee, need to handle the address |
| 5066 | // Array is handled in genCoordinateOp. |
| 5067 | if (sym->test(Fortran::semantics::Symbol::Flag::CrayPointee) && |
| 5068 | sym->Rank() == 0) { |
| 5069 | // get the corresponding Cray pointer |
| 5070 | |
jeanPerier | de7a50f | 2024-03-22 11:13:04 +0100 | [diff] [blame] | 5071 | const Fortran::semantics::Symbol &ptrSym = |
| 5072 | Fortran::semantics::GetCrayPointer(*sym); |
Mark Danial | a1c736e | 2023-08-22 12:10:08 -0400 | [diff] [blame] | 5073 | fir::ExtendedValue ptr = |
| 5074 | getSymbolExtendedValue(ptrSym, nullptr); |
| 5075 | mlir::Value ptrVal = fir::getBase(ptr); |
jeanPerier | de7a50f | 2024-03-22 11:13:04 +0100 | [diff] [blame] | 5076 | mlir::Type ptrTy = genType(ptrSym); |
Mark Danial | a1c736e | 2023-08-22 12:10:08 -0400 | [diff] [blame] | 5077 | |
| 5078 | fir::ExtendedValue pte = |
| 5079 | getSymbolExtendedValue(*sym, nullptr); |
| 5080 | mlir::Value pteVal = fir::getBase(pte); |
| 5081 | mlir::Value cnvrt = Fortran::lower::addCrayPointerInst( |
| 5082 | loc, *builder, ptrVal, ptrTy, pteVal.getType()); |
| 5083 | addr = builder->create<fir::LoadOp>(loc, cnvrt); |
| 5084 | } |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5085 | mlir::Value cast = |
Kelvin Li | ef93417 | 2023-05-23 19:02:49 -0400 | [diff] [blame] | 5086 | isVector ? val |
| 5087 | : builder->convertWithSemantics(loc, toTy, val); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5088 | if (fir::dyn_cast_ptrEleTy(addr.getType()) != toTy) { |
| 5089 | assert(isFuncResultDesignator(assign.lhs) && "type mismatch"); |
| 5090 | addr = builder->createConvert( |
| 5091 | toLocation(), builder->getRefType(toTy), addr); |
| 5092 | } |
| 5093 | builder->create<fir::StoreOp>(loc, cast, addr); |
| 5094 | } else if (isCharacterCategory(lhsType->category())) { |
| 5095 | // Fortran 2018 10.2.1.3 p10 and p11 |
| 5096 | fir::factory::CharacterExprHelper{*builder, loc}.createAssign( |
| 5097 | lhs, rhs); |
| 5098 | } else if (isDerivedCategory(lhsType->category())) { |
Valentin Clement | 6472a2e | 2023-03-14 16:01:36 +0100 | [diff] [blame] | 5099 | // Handle parent component. |
| 5100 | if (Fortran::lower::isParentComponent(assign.lhs)) { |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 5101 | if (!mlir::isa<fir::BaseBoxType>(fir::getBase(lhs).getType())) |
Valentin Clement | 6472a2e | 2023-03-14 16:01:36 +0100 | [diff] [blame] | 5102 | lhs = fir::getBase(builder->createBox(loc, lhs)); |
| 5103 | lhs = Fortran::lower::updateBoxForParentComponent(*this, lhs, |
| 5104 | assign.lhs); |
| 5105 | } |
| 5106 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5107 | // Fortran 2018 10.2.1.3 p13 and p14 |
| 5108 | // Recursively gen an assignment on each element pair. |
Valentin Clement | 7f0074a | 2023-02-03 12:21:59 +0100 | [diff] [blame] | 5109 | fir::factory::genRecordAssignment(*builder, loc, lhs, rhs, |
| 5110 | needFinalization); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5111 | } else { |
| 5112 | llvm_unreachable("unknown category"); |
| 5113 | } |
Peter Klausler | a823419 | 2022-12-19 12:41:25 -0800 | [diff] [blame] | 5114 | if (lhsIsWholeAllocatable) { |
| 5115 | assert(lhsRealloc.has_value()); |
Fangrui Song | 15a9a72 | 2022-12-17 22:22:47 +0000 | [diff] [blame] | 5116 | fir::factory::finalizeRealloc(*builder, loc, *lhsMutableBox, |
| 5117 | /*lbounds=*/std::nullopt, |
| 5118 | /*takeLboundsIfRealloc=*/false, |
| 5119 | *lhsRealloc); |
Peter Klausler | a823419 | 2022-12-19 12:41:25 -0800 | [diff] [blame] | 5120 | } |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5121 | }, |
| 5122 | |
| 5123 | // [2] User defined assignment. If the context is a scalar |
| 5124 | // expression then call the procedure. |
| 5125 | [&](const Fortran::evaluate::ProcedureRef &procRef) { |
| 5126 | Fortran::lower::StatementContext &ctx = |
| 5127 | explicitIterationSpace() ? explicitIterSpace.stmtContext() |
| 5128 | : stmtCtx; |
| 5129 | Fortran::lower::createSubroutineCall( |
| 5130 | *this, procRef, explicitIterSpace, implicitIterSpace, |
| 5131 | localSymbols, ctx, /*isUserDefAssignment=*/true); |
| 5132 | }, |
| 5133 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5134 | [&](const Fortran::evaluate::Assignment::BoundsSpec &lbExprs) { |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 5135 | return genPointerAssignment(loc, assign, lbExprs); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5136 | }, |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5137 | [&](const Fortran::evaluate::Assignment::BoundsRemapping |
| 5138 | &boundExprs) { |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 5139 | return genPointerAssignment(loc, assign, boundExprs); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5140 | }, |
| 5141 | }, |
| 5142 | assign.u); |
| 5143 | if (explicitIterationSpace()) |
| 5144 | Fortran::lower::createArrayMergeStores(*this, explicitIterSpace); |
| 5145 | } |
| 5146 | |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5147 | // Is the insertion point of the builder directly or indirectly set |
| 5148 | // inside any operation of type "Op"? |
| 5149 | template <typename... Op> |
| 5150 | bool isInsideOp() const { |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 5151 | mlir::Block *block = builder->getInsertionBlock(); |
| 5152 | mlir::Operation *op = block ? block->getParentOp() : nullptr; |
| 5153 | while (op) { |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5154 | if (mlir::isa<Op...>(op)) |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 5155 | return true; |
| 5156 | op = op->getParentOp(); |
| 5157 | } |
| 5158 | return false; |
| 5159 | } |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5160 | bool isInsideHlfirForallOrWhere() const { |
| 5161 | return isInsideOp<hlfir::ForallOp, hlfir::WhereOp>(); |
| 5162 | } |
| 5163 | bool isInsideHlfirWhere() const { return isInsideOp<hlfir::WhereOp>(); } |
Jean Perier | b87e655 | 2023-05-09 09:18:53 +0200 | [diff] [blame] | 5164 | |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5165 | void genFIR(const Fortran::parser::WhereConstruct &c) { |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5166 | mlir::Location loc = getCurrentLocation(); |
| 5167 | hlfir::WhereOp whereOp; |
| 5168 | |
| 5169 | if (!lowerToHighLevelFIR()) { |
| 5170 | implicitIterSpace.growStack(); |
| 5171 | } else { |
| 5172 | whereOp = builder->create<hlfir::WhereOp>(loc); |
| 5173 | builder->createBlock(&whereOp.getMaskRegion()); |
| 5174 | } |
| 5175 | |
| 5176 | // Lower the where mask. For HLFIR, this is done in the hlfir.where mask |
| 5177 | // region. |
Valentin Clement | 7a6a165 | 2022-03-10 18:43:40 +0100 | [diff] [blame] | 5178 | genNestedStatement( |
| 5179 | std::get< |
| 5180 | Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>( |
| 5181 | c.t)); |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5182 | |
| 5183 | // Lower WHERE body. For HLFIR, this is done in the hlfir.where body |
| 5184 | // region. |
| 5185 | if (whereOp) |
| 5186 | builder->createBlock(&whereOp.getBody()); |
| 5187 | |
Valentin Clement | 7a6a165 | 2022-03-10 18:43:40 +0100 | [diff] [blame] | 5188 | for (const auto &body : |
| 5189 | std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t)) |
| 5190 | genFIR(body); |
| 5191 | for (const auto &e : |
| 5192 | std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>( |
| 5193 | c.t)) |
| 5194 | genFIR(e); |
| 5195 | if (const auto &e = |
| 5196 | std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>( |
| 5197 | c.t); |
| 5198 | e.has_value()) |
| 5199 | genFIR(*e); |
| 5200 | genNestedStatement( |
| 5201 | std::get<Fortran::parser::Statement<Fortran::parser::EndWhereStmt>>( |
| 5202 | c.t)); |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5203 | |
| 5204 | if (whereOp) { |
| 5205 | // For HLFIR, create fir.end terminator in the last hlfir.elsewhere, or |
| 5206 | // in the hlfir.where if it had no elsewhere. |
| 5207 | builder->create<fir::FirEndOp>(loc); |
| 5208 | builder->setInsertionPointAfter(whereOp); |
| 5209 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5210 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5211 | void genFIR(const Fortran::parser::WhereBodyConstruct &body) { |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 5212 | Fortran::common::visit( |
Valentin Clement | 7a6a165 | 2022-03-10 18:43:40 +0100 | [diff] [blame] | 5213 | Fortran::common::visitors{ |
| 5214 | [&](const Fortran::parser::Statement< |
| 5215 | Fortran::parser::AssignmentStmt> &stmt) { |
| 5216 | genNestedStatement(stmt); |
| 5217 | }, |
| 5218 | [&](const Fortran::parser::Statement<Fortran::parser::WhereStmt> |
| 5219 | &stmt) { genNestedStatement(stmt); }, |
| 5220 | [&](const Fortran::common::Indirection< |
| 5221 | Fortran::parser::WhereConstruct> &c) { genFIR(c.value()); }, |
| 5222 | }, |
| 5223 | body.u); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5224 | } |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5225 | |
| 5226 | /// Lower a Where or Elsewhere mask into an hlfir mask region. |
| 5227 | void lowerWhereMaskToHlfir(mlir::Location loc, |
| 5228 | const Fortran::semantics::SomeExpr *maskExpr) { |
| 5229 | assert(maskExpr && "mask semantic analysis failed"); |
| 5230 | Fortran::lower::StatementContext maskContext; |
| 5231 | hlfir::Entity mask = Fortran::lower::convertExprToHLFIR( |
| 5232 | loc, *this, *maskExpr, localSymbols, maskContext); |
| 5233 | mask = hlfir::loadTrivialScalar(loc, *builder, mask); |
| 5234 | auto yieldOp = builder->create<hlfir::YieldOp>(loc, mask); |
jeanPerier | c7c5666 | 2024-05-14 13:34:46 +0200 | [diff] [blame] | 5235 | Fortran::lower::genCleanUpInRegionIfAny(loc, *builder, yieldOp.getCleanup(), |
| 5236 | maskContext); |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5237 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5238 | void genFIR(const Fortran::parser::WhereConstructStmt &stmt) { |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5239 | const Fortran::semantics::SomeExpr *maskExpr = Fortran::semantics::GetExpr( |
| 5240 | std::get<Fortran::parser::LogicalExpr>(stmt.t)); |
| 5241 | if (lowerToHighLevelFIR()) |
| 5242 | lowerWhereMaskToHlfir(getCurrentLocation(), maskExpr); |
| 5243 | else |
| 5244 | implicitIterSpace.append(maskExpr); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5245 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5246 | void genFIR(const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) { |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5247 | mlir::Location loc = getCurrentLocation(); |
| 5248 | hlfir::ElseWhereOp elsewhereOp; |
| 5249 | if (lowerToHighLevelFIR()) { |
| 5250 | elsewhereOp = builder->create<hlfir::ElseWhereOp>(loc); |
| 5251 | // Lower mask in the mask region. |
| 5252 | builder->createBlock(&elsewhereOp.getMaskRegion()); |
| 5253 | } |
Valentin Clement | 7a6a165 | 2022-03-10 18:43:40 +0100 | [diff] [blame] | 5254 | genNestedStatement( |
| 5255 | std::get< |
| 5256 | Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>( |
| 5257 | ew.t)); |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5258 | |
| 5259 | // For HLFIR, lower the body in the hlfir.elsewhere body region. |
| 5260 | if (elsewhereOp) |
| 5261 | builder->createBlock(&elsewhereOp.getBody()); |
| 5262 | |
Valentin Clement | 7a6a165 | 2022-03-10 18:43:40 +0100 | [diff] [blame] | 5263 | for (const auto &body : |
| 5264 | std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t)) |
| 5265 | genFIR(body); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5266 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5267 | void genFIR(const Fortran::parser::MaskedElsewhereStmt &stmt) { |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5268 | const auto *maskExpr = Fortran::semantics::GetExpr( |
| 5269 | std::get<Fortran::parser::LogicalExpr>(stmt.t)); |
| 5270 | if (lowerToHighLevelFIR()) |
| 5271 | lowerWhereMaskToHlfir(getCurrentLocation(), maskExpr); |
| 5272 | else |
| 5273 | implicitIterSpace.append(maskExpr); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5274 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5275 | void genFIR(const Fortran::parser::WhereConstruct::Elsewhere &ew) { |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5276 | if (lowerToHighLevelFIR()) { |
| 5277 | auto elsewhereOp = |
| 5278 | builder->create<hlfir::ElseWhereOp>(getCurrentLocation()); |
| 5279 | builder->createBlock(&elsewhereOp.getBody()); |
| 5280 | } |
Valentin Clement | 7a6a165 | 2022-03-10 18:43:40 +0100 | [diff] [blame] | 5281 | genNestedStatement( |
| 5282 | std::get<Fortran::parser::Statement<Fortran::parser::ElsewhereStmt>>( |
| 5283 | ew.t)); |
| 5284 | for (const auto &body : |
| 5285 | std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t)) |
| 5286 | genFIR(body); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5287 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5288 | void genFIR(const Fortran::parser::ElsewhereStmt &stmt) { |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5289 | if (!lowerToHighLevelFIR()) |
| 5290 | implicitIterSpace.append(nullptr); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5291 | } |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5292 | void genFIR(const Fortran::parser::EndWhereStmt &) { |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5293 | if (!lowerToHighLevelFIR()) |
| 5294 | implicitIterSpace.shrinkStack(); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5295 | } |
| 5296 | |
| 5297 | void genFIR(const Fortran::parser::WhereStmt &stmt) { |
Valentin Clement | 7a6a165 | 2022-03-10 18:43:40 +0100 | [diff] [blame] | 5298 | Fortran::lower::StatementContext stmtCtx; |
| 5299 | const auto &assign = std::get<Fortran::parser::AssignmentStmt>(stmt.t); |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5300 | const auto *mask = Fortran::semantics::GetExpr( |
| 5301 | std::get<Fortran::parser::LogicalExpr>(stmt.t)); |
| 5302 | if (lowerToHighLevelFIR()) { |
| 5303 | mlir::Location loc = getCurrentLocation(); |
| 5304 | auto whereOp = builder->create<hlfir::WhereOp>(loc); |
| 5305 | builder->createBlock(&whereOp.getMaskRegion()); |
| 5306 | lowerWhereMaskToHlfir(loc, mask); |
| 5307 | builder->createBlock(&whereOp.getBody()); |
| 5308 | genAssignment(*assign.typedAssignment->v); |
| 5309 | builder->create<fir::FirEndOp>(loc); |
| 5310 | builder->setInsertionPointAfter(whereOp); |
| 5311 | return; |
| 5312 | } |
Valentin Clement | 7a6a165 | 2022-03-10 18:43:40 +0100 | [diff] [blame] | 5313 | implicitIterSpace.growStack(); |
Jean Perier | 54c88fc | 2023-05-09 09:21:09 +0200 | [diff] [blame] | 5314 | implicitIterSpace.append(mask); |
Valentin Clement | 7a6a165 | 2022-03-10 18:43:40 +0100 | [diff] [blame] | 5315 | genAssignment(*assign.typedAssignment->v); |
| 5316 | implicitIterSpace.shrinkStack(); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5317 | } |
| 5318 | |
| 5319 | void genFIR(const Fortran::parser::PointerAssignmentStmt &stmt) { |
Valentin Clement | 72276bd | 2022-03-10 20:19:57 +0100 | [diff] [blame] | 5320 | genAssignment(*stmt.typedAssignment->v); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5321 | } |
| 5322 | |
| 5323 | void genFIR(const Fortran::parser::AssignmentStmt &stmt) { |
Valentin Clement | e641c29 | 2022-02-17 18:23:22 +0100 | [diff] [blame] | 5324 | genAssignment(*stmt.typedAssignment->v); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5325 | } |
| 5326 | |
| 5327 | void genFIR(const Fortran::parser::SyncAllStmt &stmt) { |
Valentin Clement | 534b228 | 2022-03-28 13:36:10 +0200 | [diff] [blame] | 5328 | genSyncAllStatement(*this, stmt); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5329 | } |
| 5330 | |
| 5331 | void genFIR(const Fortran::parser::SyncImagesStmt &stmt) { |
Valentin Clement | 534b228 | 2022-03-28 13:36:10 +0200 | [diff] [blame] | 5332 | genSyncImagesStatement(*this, stmt); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5333 | } |
| 5334 | |
| 5335 | void genFIR(const Fortran::parser::SyncMemoryStmt &stmt) { |
Valentin Clement | 534b228 | 2022-03-28 13:36:10 +0200 | [diff] [blame] | 5336 | genSyncMemoryStatement(*this, stmt); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5337 | } |
| 5338 | |
| 5339 | void genFIR(const Fortran::parser::SyncTeamStmt &stmt) { |
Valentin Clement | 534b228 | 2022-03-28 13:36:10 +0200 | [diff] [blame] | 5340 | genSyncTeamStatement(*this, stmt); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5341 | } |
| 5342 | |
| 5343 | void genFIR(const Fortran::parser::UnlockStmt &stmt) { |
Valentin Clement | 534b228 | 2022-03-28 13:36:10 +0200 | [diff] [blame] | 5344 | genUnlockStatement(*this, stmt); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5345 | } |
| 5346 | |
| 5347 | void genFIR(const Fortran::parser::AssignStmt &stmt) { |
Valentin Clement | 78a127a | 2022-03-08 20:17:48 +0100 | [diff] [blame] | 5348 | const Fortran::semantics::Symbol &symbol = |
| 5349 | *std::get<Fortran::parser::Name>(stmt.t).symbol; |
| 5350 | mlir::Location loc = toLocation(); |
| 5351 | mlir::Value labelValue = builder->createIntegerConstant( |
| 5352 | loc, genType(symbol), std::get<Fortran::parser::Label>(stmt.t)); |
| 5353 | builder->create<fir::StoreOp>(loc, labelValue, getSymbolAddress(symbol)); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5354 | } |
| 5355 | |
| 5356 | void genFIR(const Fortran::parser::FormatStmt &) { |
Valentin Clement | d8222d9 | 2022-03-14 18:15:16 +0100 | [diff] [blame] | 5357 | // do nothing. |
| 5358 | |
| 5359 | // FORMAT statements have no semantics. They may be lowered if used by a |
| 5360 | // data transfer statement. |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5361 | } |
| 5362 | |
| 5363 | void genFIR(const Fortran::parser::PauseStmt &stmt) { |
Valentin Clement | db01b12 | 2022-02-02 08:15:26 +0100 | [diff] [blame] | 5364 | genPauseStatement(*this, stmt); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5365 | } |
| 5366 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5367 | // call FAIL IMAGE in runtime |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5368 | void genFIR(const Fortran::parser::FailImageStmt &stmt) { |
Kiran Chandramohan | acd75440 | 2022-04-27 12:19:54 +0000 | [diff] [blame] | 5369 | genFailImageStatement(*this); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5370 | } |
| 5371 | |
Valentin Clement | aab4263 | 2022-02-01 20:53:00 +0100 | [diff] [blame] | 5372 | // call STOP, ERROR STOP in runtime |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5373 | void genFIR(const Fortran::parser::StopStmt &stmt) { |
Valentin Clement | aab4263 | 2022-02-01 20:53:00 +0100 | [diff] [blame] | 5374 | genStopStatement(*this, stmt); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5375 | } |
| 5376 | |
| 5377 | void genFIR(const Fortran::parser::ReturnStmt &stmt) { |
Valentin Clement | 85b89ed | 2022-02-10 18:35:16 +0100 | [diff] [blame] | 5378 | Fortran::lower::pft::FunctionLikeUnit *funit = |
| 5379 | getEval().getOwningProcedure(); |
| 5380 | assert(funit && "not inside main program, function or subroutine"); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5381 | for (auto it = activeConstructStack.rbegin(), |
| 5382 | rend = activeConstructStack.rend(); |
| 5383 | it != rend; ++it) { |
| 5384 | it->stmtCtx.finalizeAndKeep(); |
| 5385 | } |
Valentin Clement | 85b89ed | 2022-02-10 18:35:16 +0100 | [diff] [blame] | 5386 | if (funit->isMainProgram()) { |
khaki3 | ff7fca7 | 2024-11-15 08:44:42 -0800 | [diff] [blame] | 5387 | genExitRoutine(true); |
Valentin Clement | 85b89ed | 2022-02-10 18:35:16 +0100 | [diff] [blame] | 5388 | return; |
| 5389 | } |
| 5390 | mlir::Location loc = toLocation(); |
| 5391 | if (stmt.v) { |
Valentin Clement | 8b50353 | 2022-03-15 22:03:14 +0100 | [diff] [blame] | 5392 | // Alternate return statement - If this is a subroutine where some |
| 5393 | // alternate entries have alternate returns, but the active entry point |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5394 | // does not, ignore the alternate return value. Otherwise, assign it |
Valentin Clement | 8b50353 | 2022-03-15 22:03:14 +0100 | [diff] [blame] | 5395 | // to the compiler-generated result variable. |
| 5396 | const Fortran::semantics::Symbol &symbol = funit->getSubprogramSymbol(); |
| 5397 | if (Fortran::semantics::HasAlternateReturns(symbol)) { |
| 5398 | Fortran::lower::StatementContext stmtCtx; |
| 5399 | const Fortran::lower::SomeExpr *expr = |
| 5400 | Fortran::semantics::GetExpr(*stmt.v); |
| 5401 | assert(expr && "missing alternate return expression"); |
| 5402 | mlir::Value altReturnIndex = builder->createConvert( |
| 5403 | loc, builder->getIndexType(), createFIRExpr(loc, expr, stmtCtx)); |
| 5404 | builder->create<fir::StoreOp>(loc, altReturnIndex, |
| 5405 | getAltReturnResult(symbol)); |
| 5406 | } |
Valentin Clement | 85b89ed | 2022-02-10 18:35:16 +0100 | [diff] [blame] | 5407 | } |
| 5408 | // Branch to the last block of the SUBROUTINE, which has the actual return. |
| 5409 | if (!funit->finalBlock) { |
| 5410 | mlir::OpBuilder::InsertPoint insPt = builder->saveInsertionPoint(); |
Valentin Clement (バレンタイン クレメン) | a9a5af8 | 2023-11-30 14:25:03 -0800 | [diff] [blame] | 5411 | Fortran::lower::setInsertionPointAfterOpenACCLoopIfInside(*builder); |
Valentin Clement | 85b89ed | 2022-02-10 18:35:16 +0100 | [diff] [blame] | 5412 | funit->finalBlock = builder->createBlock(&builder->getRegion()); |
| 5413 | builder->restoreInsertionPoint(insPt); |
| 5414 | } |
Valentin Clement (バレンタイン クレメン) | a9a5af8 | 2023-11-30 14:25:03 -0800 | [diff] [blame] | 5415 | |
| 5416 | if (Fortran::lower::isInOpenACCLoop(*builder)) |
| 5417 | Fortran::lower::genEarlyReturnInOpenACCLoop(*builder, loc); |
| 5418 | else |
| 5419 | builder->create<mlir::cf::BranchOp>(loc, funit->finalBlock); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5420 | } |
| 5421 | |
| 5422 | void genFIR(const Fortran::parser::CycleStmt &) { |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5423 | genConstructExitBranch(*getEval().controlSuccessor); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5424 | } |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5425 | void genFIR(const Fortran::parser::ExitStmt &) { |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5426 | genConstructExitBranch(*getEval().controlSuccessor); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5427 | } |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5428 | void genFIR(const Fortran::parser::GotoStmt &) { |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5429 | genConstructExitBranch(*getEval().controlSuccessor); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5430 | } |
| 5431 | |
Valentin Clement | 8927530 | 2022-02-01 15:26:47 +0100 | [diff] [blame] | 5432 | // Nop statements - No code, or code is generated at the construct level. |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 5433 | // But note that the genFIR call immediately below that wraps one of these |
| 5434 | // calls does block management, possibly starting a new block, and possibly |
| 5435 | // generating a branch to end a block. So these calls may still be required |
| 5436 | // for that functionality. |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5437 | void genFIR(const Fortran::parser::AssociateStmt &) {} // nop |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5438 | void genFIR(const Fortran::parser::BlockStmt &) {} // nop |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5439 | void genFIR(const Fortran::parser::CaseStmt &) {} // nop |
| 5440 | void genFIR(const Fortran::parser::ContinueStmt &) {} // nop |
| 5441 | void genFIR(const Fortran::parser::ElseIfStmt &) {} // nop |
| 5442 | void genFIR(const Fortran::parser::ElseStmt &) {} // nop |
| 5443 | void genFIR(const Fortran::parser::EndAssociateStmt &) {} // nop |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5444 | void genFIR(const Fortran::parser::EndBlockStmt &) {} // nop |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 5445 | void genFIR(const Fortran::parser::EndDoStmt &) {} // nop |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5446 | void genFIR(const Fortran::parser::EndFunctionStmt &) {} // nop |
| 5447 | void genFIR(const Fortran::parser::EndIfStmt &) {} // nop |
| 5448 | void genFIR(const Fortran::parser::EndMpSubprogramStmt &) {} // nop |
Valentin Clement | 591e3e6 | 2023-02-01 15:53:52 +0100 | [diff] [blame] | 5449 | void genFIR(const Fortran::parser::EndProgramStmt &) {} // nop |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5450 | void genFIR(const Fortran::parser::EndSelectStmt &) {} // nop |
| 5451 | void genFIR(const Fortran::parser::EndSubroutineStmt &) {} // nop |
| 5452 | void genFIR(const Fortran::parser::EntryStmt &) {} // nop |
| 5453 | void genFIR(const Fortran::parser::IfStmt &) {} // nop |
| 5454 | void genFIR(const Fortran::parser::IfThenStmt &) {} // nop |
Kiran Chandramohan | b5b3e50 | 2022-04-28 12:20:11 +0000 | [diff] [blame] | 5455 | void genFIR(const Fortran::parser::NonLabelDoStmt &) {} // nop |
Kiran Chandramohan | b85c39d | 2022-05-06 11:45:18 +0000 | [diff] [blame] | 5456 | void genFIR(const Fortran::parser::OmpEndLoopDirective &) {} // nop |
Valentin Clement | f677c5e | 2022-11-14 10:46:53 +0100 | [diff] [blame] | 5457 | void genFIR(const Fortran::parser::SelectTypeStmt &) {} // nop |
| 5458 | void genFIR(const Fortran::parser::TypeGuardStmt &) {} // nop |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5459 | |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 5460 | /// Generate FIR for Evaluation \p eval. |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5461 | void genFIR(Fortran::lower::pft::Evaluation &eval, |
| 5462 | bool unstructuredContext = true) { |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 5463 | // Start a new unstructured block when applicable. When transitioning |
| 5464 | // from unstructured to structured code, unstructuredContext is true, |
| 5465 | // which accounts for the possibility that the structured code could be |
| 5466 | // a target that starts a new block. |
| 5467 | if (unstructuredContext) |
Kiran Chandramohan | ae37bb9 | 2022-02-08 23:01:39 +0000 | [diff] [blame] | 5468 | maybeStartBlock(eval.isConstruct() && eval.lowerAsStructured() |
| 5469 | ? eval.getFirstNestedEvaluation().block |
| 5470 | : eval.block); |
Kiran Chandramohan | ae37bb9 | 2022-02-08 23:01:39 +0000 | [diff] [blame] | 5471 | |
V Donaldson | 609b789 | 2023-01-03 10:31:30 -0800 | [diff] [blame] | 5472 | // Generate evaluation specific code. Even nop calls should usually reach |
| 5473 | // here in case they start a new block or require generation of a generic |
| 5474 | // end-of-block branch. An alternative is to add special case code |
| 5475 | // elsewhere, such as in the genFIR code for a parent construct. |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5476 | setCurrentEval(eval); |
| 5477 | setCurrentPosition(eval.position); |
| 5478 | eval.visit([&](const auto &stmt) { genFIR(stmt); }); |
Valentin Clement | 9907591 | 2022-02-01 13:49:49 +0100 | [diff] [blame] | 5479 | } |
| 5480 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5481 | /// Map mlir function block arguments to the corresponding Fortran dummy |
| 5482 | /// variables. When the result is passed as a hidden argument, the Fortran |
| 5483 | /// result is also mapped. The symbol map is used to hold this mapping. |
| 5484 | void mapDummiesAndResults(Fortran::lower::pft::FunctionLikeUnit &funit, |
| 5485 | const Fortran::lower::CalleeInterface &callee) { |
| 5486 | assert(builder && "require a builder object at this point"); |
| 5487 | using PassBy = Fortran::lower::CalleeInterface::PassEntityBy; |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 5488 | auto mapPassedEntity = [&](const auto arg, bool isResult = false) { |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5489 | if (arg.passBy == PassBy::AddressAndLength) { |
Valentin Clement | de3efd1 | 2022-09-24 08:58:50 +0200 | [diff] [blame] | 5490 | if (callee.characterize().IsBindC()) |
| 5491 | return; |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5492 | // TODO: now that fir call has some attributes regarding character |
| 5493 | // return, PassBy::AddressAndLength should be retired. |
| 5494 | mlir::Location loc = toLocation(); |
| 5495 | fir::factory::CharacterExprHelper charHelp{*builder, loc}; |
| 5496 | mlir::Value box = |
| 5497 | charHelp.createEmboxChar(arg.firArgument, arg.firLength); |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 5498 | mapBlockArgToDummyOrResult(arg.entity->get(), box, isResult); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5499 | } else { |
| 5500 | if (arg.entity.has_value()) { |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 5501 | mapBlockArgToDummyOrResult(arg.entity->get(), arg.firArgument, |
| 5502 | isResult); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5503 | } else { |
Jean Perier | 93129ca | 2022-12-20 13:49:38 +0100 | [diff] [blame] | 5504 | assert(funit.parentHasTupleHostAssoc() && "expect tuple argument"); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5505 | } |
| 5506 | } |
| 5507 | }; |
| 5508 | for (const Fortran::lower::CalleeInterface::PassedEntity &arg : |
| 5509 | callee.getPassedArguments()) |
| 5510 | mapPassedEntity(arg); |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 5511 | if (lowerToHighLevelFIR() && !callee.getPassedArguments().empty()) { |
| 5512 | mlir::Value scopeOp = builder->create<fir::DummyScopeOp>(toLocation()); |
| 5513 | setDummyArgsScope(scopeOp); |
| 5514 | } |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5515 | if (std::optional<Fortran::lower::CalleeInterface::PassedEntity> |
| 5516 | passedResult = callee.getPassedResult()) { |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 5517 | mapPassedEntity(*passedResult, /*isResult=*/true); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5518 | // FIXME: need to make sure things are OK here. addSymbol may not be OK |
| 5519 | if (funit.primaryResult && |
| 5520 | passedResult->entity->get() != *funit.primaryResult) |
Jean Perier | ab9c4e9 | 2023-02-07 09:22:47 +0100 | [diff] [blame] | 5521 | mapBlockArgToDummyOrResult( |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 5522 | *funit.primaryResult, getSymbolAddress(passedResult->entity->get()), |
| 5523 | /*isResult=*/true); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5524 | } |
| 5525 | } |
| 5526 | |
| 5527 | /// Instantiate variable \p var and add it to the symbol map. |
| 5528 | /// See ConvertVariable.cpp. |
| 5529 | void instantiateVar(const Fortran::lower::pft::Variable &var, |
| 5530 | Fortran::lower::AggregateStoreMap &storeMap) { |
| 5531 | Fortran::lower::instantiateVariable(*this, var, localSymbols, storeMap); |
Krzysztof Parzyszek | 82e91b9 | 2023-12-15 09:32:57 -0600 | [diff] [blame] | 5532 | if (var.hasSymbol()) |
| 5533 | genOpenMPSymbolProperties(*this, var); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5534 | } |
| 5535 | |
vdonaldson | 6003be7 | 2024-12-04 16:21:11 -0500 | [diff] [blame] | 5536 | /// Where applicable, save the exception state and halting, rounding, and |
| 5537 | /// underflow modes at function entry, and restore them at function exits. |
vdonaldson | 3aba926 | 2023-12-04 09:55:54 -0800 | [diff] [blame] | 5538 | void manageFPEnvironment(Fortran::lower::pft::FunctionLikeUnit &funit) { |
| 5539 | mlir::Location loc = toLocation(); |
| 5540 | mlir::Location endLoc = |
| 5541 | toLocation(Fortran::lower::pft::stmtSourceLoc(funit.endStmt)); |
| 5542 | if (funit.hasIeeeAccess) { |
| 5543 | // Subject to F18 Clause 17.1p3, 17.3p3 states: If a flag is signaling |
| 5544 | // on entry to a procedure [...], the processor will set it to quiet |
| 5545 | // on entry and restore it to signaling on return. If a flag signals |
| 5546 | // during execution of a procedure, the processor shall not set it to |
| 5547 | // quiet on return. |
| 5548 | mlir::func::FuncOp testExcept = fir::factory::getFetestexcept(*builder); |
| 5549 | mlir::func::FuncOp clearExcept = fir::factory::getFeclearexcept(*builder); |
| 5550 | mlir::func::FuncOp raiseExcept = fir::factory::getFeraiseexcept(*builder); |
| 5551 | mlir::Value ones = builder->createIntegerConstant( |
| 5552 | loc, testExcept.getFunctionType().getInput(0), -1); |
| 5553 | mlir::Value exceptSet = |
| 5554 | builder->create<fir::CallOp>(loc, testExcept, ones).getResult(0); |
| 5555 | builder->create<fir::CallOp>(loc, clearExcept, exceptSet); |
| 5556 | bridge.fctCtx().attachCleanup([=]() { |
| 5557 | builder->create<fir::CallOp>(endLoc, raiseExcept, exceptSet); |
| 5558 | }); |
| 5559 | } |
| 5560 | if (funit.mayModifyHaltingMode) { |
| 5561 | // F18 Clause 17.6p1: In a procedure [...], the processor shall not |
| 5562 | // change the halting mode on entry, and on return shall ensure that |
| 5563 | // the halting mode is the same as it was on entry. |
| 5564 | mlir::func::FuncOp getExcept = fir::factory::getFegetexcept(*builder); |
| 5565 | mlir::func::FuncOp disableExcept = |
| 5566 | fir::factory::getFedisableexcept(*builder); |
| 5567 | mlir::func::FuncOp enableExcept = |
| 5568 | fir::factory::getFeenableexcept(*builder); |
| 5569 | mlir::Value exceptSet = |
| 5570 | builder->create<fir::CallOp>(loc, getExcept).getResult(0); |
| 5571 | mlir::Value ones = builder->createIntegerConstant( |
| 5572 | loc, disableExcept.getFunctionType().getInput(0), -1); |
| 5573 | bridge.fctCtx().attachCleanup([=]() { |
| 5574 | builder->create<fir::CallOp>(endLoc, disableExcept, ones); |
| 5575 | builder->create<fir::CallOp>(endLoc, enableExcept, exceptSet); |
| 5576 | }); |
| 5577 | } |
| 5578 | if (funit.mayModifyRoundingMode) { |
vdonaldson | 6003be7 | 2024-12-04 16:21:11 -0500 | [diff] [blame] | 5579 | // F18 Clause 17.4p5: In a procedure [...], the processor shall not |
vdonaldson | 3aba926 | 2023-12-04 09:55:54 -0800 | [diff] [blame] | 5580 | // change the rounding modes on entry, and on return shall ensure that |
| 5581 | // the rounding modes are the same as they were on entry. |
| 5582 | mlir::func::FuncOp getRounding = |
| 5583 | fir::factory::getLlvmGetRounding(*builder); |
| 5584 | mlir::func::FuncOp setRounding = |
| 5585 | fir::factory::getLlvmSetRounding(*builder); |
| 5586 | mlir::Value roundingMode = |
| 5587 | builder->create<fir::CallOp>(loc, getRounding).getResult(0); |
| 5588 | bridge.fctCtx().attachCleanup([=]() { |
| 5589 | builder->create<fir::CallOp>(endLoc, setRounding, roundingMode); |
| 5590 | }); |
| 5591 | } |
vdonaldson | 6003be7 | 2024-12-04 16:21:11 -0500 | [diff] [blame] | 5592 | if ((funit.mayModifyUnderflowMode) && |
| 5593 | (bridge.getTargetCharacteristics().hasSubnormalFlushingControl( |
| 5594 | /*any=*/true))) { |
| 5595 | // F18 Clause 17.5p2: In a procedure [...], the processor shall not |
| 5596 | // change the underflow mode on entry, and on return shall ensure that |
| 5597 | // the underflow mode is the same as it was on entry. |
| 5598 | mlir::Value underflowMode = |
| 5599 | fir::runtime::genGetUnderflowMode(*builder, loc); |
| 5600 | bridge.fctCtx().attachCleanup([=]() { |
| 5601 | fir::runtime::genSetUnderflowMode(*builder, loc, {underflowMode}); |
| 5602 | }); |
| 5603 | } |
vdonaldson | 3aba926 | 2023-12-04 09:55:54 -0800 | [diff] [blame] | 5604 | } |
| 5605 | |
V Donaldson | 518e6f1 | 2022-12-12 14:20:06 -0800 | [diff] [blame] | 5606 | /// Start translation of a function. |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5607 | void startNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) { |
| 5608 | assert(!builder && "expected nullptr"); |
Valentin Clement | 97492fd1a | 2023-01-31 13:46:12 +0100 | [diff] [blame] | 5609 | bridge.fctCtx().pushScope(); |
Valentin Clement (バレンタイン クレメン) | a3700cc | 2023-11-14 14:42:11 -0800 | [diff] [blame] | 5610 | bridge.openAccCtx().pushScope(); |
V Donaldson | 518e6f1 | 2022-12-12 14:20:06 -0800 | [diff] [blame] | 5611 | const Fortran::semantics::Scope &scope = funit.getScope(); |
| 5612 | LLVM_DEBUG(llvm::dbgs() << "\n[bridge - startNewFunction]"; |
| 5613 | if (auto *sym = scope.symbol()) llvm::dbgs() << " " << *sym; |
| 5614 | llvm::dbgs() << "\n"); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5615 | Fortran::lower::CalleeInterface callee(funit, *this); |
River Riddle | 58ceae9 | 2022-04-18 11:53:47 -0700 | [diff] [blame] | 5616 | mlir::func::FuncOp func = callee.addEntryBlockAndMapArguments(); |
jeanPerier | a4798bb | 2024-04-02 14:29:29 +0200 | [diff] [blame] | 5617 | builder = |
| 5618 | new fir::FirOpBuilder(func, bridge.getKindMap(), &mlirSymbolTable); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5619 | assert(builder && "FirOpBuilder did not instantiate"); |
Slava Zakharin | 8f3f15c | 2022-11-07 09:05:27 -0800 | [diff] [blame] | 5620 | builder->setFastMathFlags(bridge.getLoweringOptions().getMathOptions()); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5621 | builder->setInsertionPointToStart(&func.front()); |
jeanPerier | 06f775a | 2024-02-28 14:30:29 +0100 | [diff] [blame] | 5622 | if (funit.parent.isA<Fortran::lower::pft::FunctionLikeUnit>()) { |
| 5623 | // Give internal linkage to internal functions. There are no name clash |
| 5624 | // risks, but giving global linkage to internal procedure will break the |
| 5625 | // static link register in shared libraries because of the system calls. |
| 5626 | // Also, it should be possible to eliminate the procedure code if all the |
| 5627 | // uses have been inlined. |
| 5628 | fir::factory::setInternalLinkage(func); |
| 5629 | } else { |
| 5630 | func.setVisibility(mlir::SymbolTable::Visibility::Public); |
| 5631 | } |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5632 | assert(blockId == 0 && "invalid blockId"); |
| 5633 | assert(activeConstructStack.empty() && "invalid construct stack state"); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5634 | |
vdonaldson | 3aba926 | 2023-12-04 09:55:54 -0800 | [diff] [blame] | 5635 | // Manage floating point exception, halting mode, and rounding mode |
| 5636 | // settings at function entry and exit. |
| 5637 | if (!funit.isMainProgram()) |
| 5638 | manageFPEnvironment(funit); |
V Donaldson | 09ea692 | 2023-06-29 11:32:56 -0700 | [diff] [blame] | 5639 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5640 | mapDummiesAndResults(funit, callee); |
| 5641 | |
Jean Perier | 93129ca | 2022-12-20 13:49:38 +0100 | [diff] [blame] | 5642 | // Map host associated symbols from parent procedure if any. |
| 5643 | if (funit.parentHasHostAssoc()) |
| 5644 | funit.parentHostAssoc().internalProcedureBindings(*this, localSymbols); |
| 5645 | |
V Donaldson | 518e6f1 | 2022-12-12 14:20:06 -0800 | [diff] [blame] | 5646 | // Non-primary results of a function with multiple entry points. |
| 5647 | // These result values share storage with the primary result. |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5648 | llvm::SmallVector<Fortran::lower::pft::Variable> deferredFuncResultList; |
| 5649 | |
V Donaldson | 518e6f1 | 2022-12-12 14:20:06 -0800 | [diff] [blame] | 5650 | // Backup actual argument for entry character results with different |
| 5651 | // lengths. It needs to be added to the non-primary results symbol before |
| 5652 | // mapSymbolAttributes is called. |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5653 | Fortran::lower::SymbolBox resultArg; |
| 5654 | if (std::optional<Fortran::lower::CalleeInterface::PassedEntity> |
| 5655 | passedResult = callee.getPassedResult()) |
| 5656 | resultArg = lookupSymbol(passedResult->entity->get()); |
| 5657 | |
| 5658 | Fortran::lower::AggregateStoreMap storeMap; |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5659 | |
V Donaldson | 518e6f1 | 2022-12-12 14:20:06 -0800 | [diff] [blame] | 5660 | // Map all containing submodule and module equivalences and variables, in |
| 5661 | // case they are referenced. It might be better to limit this to variables |
| 5662 | // that are actually referenced, although that is more complicated when |
| 5663 | // there are equivalenced variables. |
| 5664 | auto &scopeVariableListMap = |
| 5665 | Fortran::lower::pft::getScopeVariableListMap(funit); |
| 5666 | for (auto *scp = &scope.parent(); !scp->IsGlobal(); scp = &scp->parent()) |
| 5667 | if (scp->kind() == Fortran::semantics::Scope::Kind::Module) |
| 5668 | for (const auto &var : Fortran::lower::pft::getScopeVariableList( |
| 5669 | *scp, scopeVariableListMap)) |
jeanPerier | 0a45d17 | 2024-02-05 10:12:33 +0100 | [diff] [blame] | 5670 | if (!var.isRuntimeTypeInfoData()) |
| 5671 | instantiateVar(var, storeMap); |
V Donaldson | 518e6f1 | 2022-12-12 14:20:06 -0800 | [diff] [blame] | 5672 | |
| 5673 | // Map function equivalences and variables. |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5674 | mlir::Value primaryFuncResultStorage; |
| 5675 | for (const Fortran::lower::pft::Variable &var : |
V Donaldson | 518e6f1 | 2022-12-12 14:20:06 -0800 | [diff] [blame] | 5676 | Fortran::lower::pft::getScopeVariableList(scope)) { |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5677 | // Always instantiate aggregate storage blocks. |
| 5678 | if (var.isAggregateStore()) { |
| 5679 | instantiateVar(var, storeMap); |
| 5680 | continue; |
| 5681 | } |
| 5682 | const Fortran::semantics::Symbol &sym = var.getSymbol(); |
| 5683 | if (funit.parentHasHostAssoc()) { |
V Donaldson | 518e6f1 | 2022-12-12 14:20:06 -0800 | [diff] [blame] | 5684 | // Never instantiate host associated variables, as they are already |
| 5685 | // instantiated from an argument tuple. Instead, just bind the symbol |
| 5686 | // to the host variable, which must be in the map. |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5687 | const Fortran::semantics::Symbol &ultimate = sym.GetUltimate(); |
| 5688 | if (funit.parentHostAssoc().isAssociated(ultimate)) { |
Jean Perier | 93129ca | 2022-12-20 13:49:38 +0100 | [diff] [blame] | 5689 | copySymbolBinding(ultimate, sym); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5690 | continue; |
| 5691 | } |
| 5692 | } |
| 5693 | if (!sym.IsFuncResult() || !funit.primaryResult) { |
| 5694 | instantiateVar(var, storeMap); |
| 5695 | } else if (&sym == funit.primaryResult) { |
| 5696 | instantiateVar(var, storeMap); |
| 5697 | primaryFuncResultStorage = getSymbolAddress(sym); |
| 5698 | } else { |
| 5699 | deferredFuncResultList.push_back(var); |
| 5700 | } |
| 5701 | } |
| 5702 | |
V Donaldson | 1e1f60c | 2022-05-24 10:06:24 -0700 | [diff] [blame] | 5703 | // TODO: should use same mechanism as equivalence? |
| 5704 | // One blocking point is character entry returns that need special handling |
| 5705 | // since they are not locally allocated but come as argument. CHARACTER(*) |
| 5706 | // is not something that fits well with equivalence lowering. |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5707 | for (const Fortran::lower::pft::Variable &altResult : |
| 5708 | deferredFuncResultList) { |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5709 | Fortran::lower::StatementContext stmtCtx; |
Jean Perier | 9e37301 | 2022-10-18 11:07:47 +0200 | [diff] [blame] | 5710 | if (std::optional<Fortran::lower::CalleeInterface::PassedEntity> |
| 5711 | passedResult = callee.getPassedResult()) { |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 5712 | mapBlockArgToDummyOrResult(altResult.getSymbol(), resultArg.getAddr(), |
| 5713 | /*isResult=*/true); |
Jean Perier | 9e37301 | 2022-10-18 11:07:47 +0200 | [diff] [blame] | 5714 | Fortran::lower::mapSymbolAttributes(*this, altResult, localSymbols, |
| 5715 | stmtCtx); |
| 5716 | } else { |
Tom Eccles | 569716f | 2023-06-14 13:23:00 +0000 | [diff] [blame] | 5717 | // catch cases where the allocation for the function result storage type |
| 5718 | // doesn't match the type of this symbol |
| 5719 | mlir::Value preAlloc = primaryFuncResultStorage; |
| 5720 | mlir::Type resTy = primaryFuncResultStorage.getType(); |
| 5721 | mlir::Type symTy = genType(altResult); |
| 5722 | mlir::Type wrappedSymTy = fir::ReferenceType::get(symTy); |
| 5723 | if (resTy != wrappedSymTy) { |
| 5724 | // check size of the pointed to type so we can't overflow by writing |
| 5725 | // double precision to a single precision allocation, etc |
| 5726 | LLVM_ATTRIBUTE_UNUSED auto getBitWidth = [this](mlir::Type ty) { |
| 5727 | // 15.6.2.6.3: differering result types should be integer, real, |
| 5728 | // complex or logical |
jeanPerier | c4204c0 | 2024-10-03 17:10:57 +0200 | [diff] [blame] | 5729 | if (auto cmplx = mlir::dyn_cast_or_null<mlir::ComplexType>(ty)) |
| 5730 | return 2 * cmplx.getElementType().getIntOrFloatBitWidth(); |
Tom Eccles | 569716f | 2023-06-14 13:23:00 +0000 | [diff] [blame] | 5731 | if (auto logical = mlir::dyn_cast_or_null<fir::LogicalType>(ty)) { |
| 5732 | fir::KindTy kind = logical.getFKind(); |
| 5733 | return builder->getKindMap().getLogicalBitsize(kind); |
| 5734 | } |
| 5735 | return ty.getIntOrFloatBitWidth(); |
| 5736 | }; |
| 5737 | assert(getBitWidth(fir::unwrapRefType(resTy)) >= getBitWidth(symTy)); |
| 5738 | |
| 5739 | // convert the storage to the symbol type so that the hlfir.declare |
| 5740 | // gets the correct type for this symbol |
| 5741 | preAlloc = builder->create<fir::ConvertOp>(getCurrentLocation(), |
| 5742 | wrappedSymTy, preAlloc); |
| 5743 | } |
| 5744 | |
Jean Perier | 9e37301 | 2022-10-18 11:07:47 +0200 | [diff] [blame] | 5745 | Fortran::lower::mapSymbolAttributes(*this, altResult, localSymbols, |
Tom Eccles | 569716f | 2023-06-14 13:23:00 +0000 | [diff] [blame] | 5746 | stmtCtx, preAlloc); |
Jean Perier | 9e37301 | 2022-10-18 11:07:47 +0200 | [diff] [blame] | 5747 | } |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5748 | } |
| 5749 | |
V Donaldson | 1e1f60c | 2022-05-24 10:06:24 -0700 | [diff] [blame] | 5750 | // If this is a host procedure with host associations, then create the tuple |
| 5751 | // of pointers for passing to the internal procedures. |
| 5752 | if (!funit.getHostAssoc().empty()) |
| 5753 | funit.getHostAssoc().hostProcedureBindings(*this, localSymbols); |
| 5754 | |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 5755 | // Unregister all dummy symbols, so that their cloning (e.g. for OpenMP |
| 5756 | // privatization) does not create the cloned hlfir.declare operations |
| 5757 | // with dummy_scope operands. |
| 5758 | resetRegisteredDummySymbols(); |
| 5759 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5760 | // Create most function blocks in advance. |
| 5761 | createEmptyBlocks(funit.evaluationList); |
| 5762 | |
| 5763 | // Reinstate entry block as the current insertion point. |
| 5764 | builder->setInsertionPointToEnd(&func.front()); |
| 5765 | |
| 5766 | if (callee.hasAlternateReturns()) { |
| 5767 | // Create a local temp to hold the alternate return index. |
| 5768 | // Give it an integer index type and the subroutine name (for dumps). |
| 5769 | // Attach it to the subroutine symbol in the localSymbols map. |
| 5770 | // Initialize it to zero, the "fallthrough" alternate return value. |
| 5771 | const Fortran::semantics::Symbol &symbol = funit.getSubprogramSymbol(); |
| 5772 | mlir::Location loc = toLocation(); |
| 5773 | mlir::Type idxTy = builder->getIndexType(); |
| 5774 | mlir::Value altResult = |
| 5775 | builder->createTemporary(loc, idxTy, toStringRef(symbol.name())); |
| 5776 | addSymbol(symbol, altResult); |
| 5777 | mlir::Value zero = builder->createIntegerConstant(loc, idxTy, 0); |
| 5778 | builder->create<fir::StoreOp>(loc, zero, altResult); |
| 5779 | } |
| 5780 | |
| 5781 | if (Fortran::lower::pft::Evaluation *alternateEntryEval = |
| 5782 | funit.getEntryEval()) |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5783 | genBranch(alternateEntryEval->lexicalSuccessor->block); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5784 | } |
| 5785 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5786 | /// Create global blocks for the current function. This eliminates the |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5787 | /// distinction between forward and backward targets when generating |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5788 | /// branches. A block is "global" if it can be the target of a GOTO or |
| 5789 | /// other source code branch. A block that can only be targeted by a |
| 5790 | /// compiler generated branch is "local". For example, a DO loop preheader |
| 5791 | /// block containing loop initialization code is global. A loop header |
| 5792 | /// block, which is the target of the loop back edge, is local. Blocks |
| 5793 | /// belong to a region. Any block within a nested region must be replaced |
| 5794 | /// with a block belonging to that region. Branches may not cross region |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5795 | /// boundaries. |
| 5796 | void createEmptyBlocks( |
| 5797 | std::list<Fortran::lower::pft::Evaluation> &evaluationList) { |
| 5798 | mlir::Region *region = &builder->getRegion(); |
| 5799 | for (Fortran::lower::pft::Evaluation &eval : evaluationList) { |
| 5800 | if (eval.isNewBlock) |
| 5801 | eval.block = builder->createBlock(region); |
| 5802 | if (eval.isConstruct() || eval.isDirective()) { |
| 5803 | if (eval.lowerAsUnstructured()) { |
| 5804 | createEmptyBlocks(eval.getNestedEvaluations()); |
| 5805 | } else if (eval.hasNestedEvaluations()) { |
| 5806 | // A structured construct that is a target starts a new block. |
| 5807 | Fortran::lower::pft::Evaluation &constructStmt = |
| 5808 | eval.getFirstNestedEvaluation(); |
| 5809 | if (constructStmt.isNewBlock) |
| 5810 | constructStmt.block = builder->createBlock(region); |
| 5811 | } |
| 5812 | } |
| 5813 | } |
| 5814 | } |
| 5815 | |
| 5816 | /// Return the predicate: "current block does not have a terminator branch". |
| 5817 | bool blockIsUnterminated() { |
| 5818 | mlir::Block *currentBlock = builder->getBlock(); |
| 5819 | return currentBlock->empty() || |
| 5820 | !currentBlock->back().hasTrait<mlir::OpTrait::IsTerminator>(); |
| 5821 | } |
| 5822 | |
| 5823 | /// Unconditionally switch code insertion to a new block. |
| 5824 | void startBlock(mlir::Block *newBlock) { |
| 5825 | assert(newBlock && "missing block"); |
| 5826 | // Default termination for the current block is a fallthrough branch to |
| 5827 | // the new block. |
| 5828 | if (blockIsUnterminated()) |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5829 | genBranch(newBlock); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5830 | // Some blocks may be re/started more than once, and might not be empty. |
| 5831 | // If the new block already has (only) a terminator, set the insertion |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5832 | // point to the start of the block. Otherwise set it to the end. |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5833 | builder->setInsertionPointToStart(newBlock); |
| 5834 | if (blockIsUnterminated()) |
| 5835 | builder->setInsertionPointToEnd(newBlock); |
| 5836 | } |
| 5837 | |
| 5838 | /// Conditionally switch code insertion to a new block. |
| 5839 | void maybeStartBlock(mlir::Block *newBlock) { |
| 5840 | if (newBlock) |
| 5841 | startBlock(newBlock); |
| 5842 | } |
| 5843 | |
Jean Perier | 23fbe52 | 2023-06-28 08:27:16 +0200 | [diff] [blame] | 5844 | void eraseDeadCodeAndBlocks(mlir::RewriterBase &rewriter, |
| 5845 | llvm::MutableArrayRef<mlir::Region> regions) { |
Jan Sjodin | 45a9604 | 2023-07-10 10:55:47 -0400 | [diff] [blame] | 5846 | // WARNING: Do not add passes that can do folding or code motion here |
| 5847 | // because they might cross omp.target region boundaries, which can result |
| 5848 | // in incorrect code. Optimization passes like these must be added after |
| 5849 | // OMP early outlining has been done. |
Jean Perier | 23fbe52 | 2023-06-28 08:27:16 +0200 | [diff] [blame] | 5850 | (void)mlir::eraseUnreachableBlocks(rewriter, regions); |
| 5851 | (void)mlir::runRegionDCE(rewriter, regions); |
| 5852 | } |
| 5853 | |
V Donaldson | 518e6f1 | 2022-12-12 14:20:06 -0800 | [diff] [blame] | 5854 | /// Finish translation of a function. |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5855 | void endNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) { |
| 5856 | setCurrentPosition(Fortran::lower::pft::stmtSourceLoc(funit.endStmt)); |
Valentin Clement | 97492fd1a | 2023-01-31 13:46:12 +0100 | [diff] [blame] | 5857 | if (funit.isMainProgram()) { |
khaki3 | ff7fca7 | 2024-11-15 08:44:42 -0800 | [diff] [blame] | 5858 | genExitRoutine(false); |
Valentin Clement | 97492fd1a | 2023-01-31 13:46:12 +0100 | [diff] [blame] | 5859 | } else { |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5860 | genFIRProcedureExit(funit, funit.getSubprogramSymbol()); |
Valentin Clement | 97492fd1a | 2023-01-31 13:46:12 +0100 | [diff] [blame] | 5861 | } |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5862 | funit.finalBlock = nullptr; |
V Donaldson | 518e6f1 | 2022-12-12 14:20:06 -0800 | [diff] [blame] | 5863 | LLVM_DEBUG(llvm::dbgs() << "\n[bridge - endNewFunction"; |
| 5864 | if (auto *sym = funit.scope->symbol()) llvm::dbgs() |
| 5865 | << " " << sym->name(); |
| 5866 | llvm::dbgs() << "] generated IR:\n\n" |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5867 | << *builder->getFunction() << '\n'); |
V Donaldson | 518e6f1 | 2022-12-12 14:20:06 -0800 | [diff] [blame] | 5868 | // Eliminate dead code as a prerequisite to calling other IR passes. |
| 5869 | // FIXME: This simplification should happen in a normal pass, not here. |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5870 | mlir::IRRewriter rewriter(*builder); |
Jean Perier | 23fbe52 | 2023-06-28 08:27:16 +0200 | [diff] [blame] | 5871 | (void)eraseDeadCodeAndBlocks(rewriter, {builder->getRegion()}); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5872 | delete builder; |
| 5873 | builder = nullptr; |
| 5874 | hostAssocTuple = mlir::Value{}; |
| 5875 | localSymbols.clear(); |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 5876 | blockId = 0; |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 5877 | dummyArgsScope = mlir::Value{}; |
| 5878 | resetRegisteredDummySymbols(); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5879 | } |
| 5880 | |
| 5881 | /// Helper to generate GlobalOps when the builder is not positioned in any |
| 5882 | /// region block. This is required because the FirOpBuilder assumes it is |
| 5883 | /// always positioned inside a region block when creating globals, the easiest |
| 5884 | /// way comply is to create a dummy function and to throw it afterwards. |
| 5885 | void createGlobalOutsideOfFunctionLowering( |
| 5886 | const std::function<void()> &createGlobals) { |
| 5887 | // FIXME: get rid of the bogus function context and instantiate the |
| 5888 | // globals directly into the module. |
| 5889 | mlir::MLIRContext *context = &getMLIRContext(); |
jeanPerier | a4798bb | 2024-04-02 14:29:29 +0200 | [diff] [blame] | 5890 | mlir::SymbolTable *symbolTable = getMLIRSymbolTable(); |
River Riddle | 58ceae9 | 2022-04-18 11:53:47 -0700 | [diff] [blame] | 5891 | mlir::func::FuncOp func = fir::FirOpBuilder::createFunction( |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5892 | mlir::UnknownLoc::get(context), getModuleOp(), |
| 5893 | fir::NameUniquer::doGenerated("Sham"), |
jeanPerier | a4798bb | 2024-04-02 14:29:29 +0200 | [diff] [blame] | 5894 | mlir::FunctionType::get(context, std::nullopt, std::nullopt), |
| 5895 | symbolTable); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5896 | func.addEntryBlock(); |
jeanPerier | a4798bb | 2024-04-02 14:29:29 +0200 | [diff] [blame] | 5897 | builder = new fir::FirOpBuilder(func, bridge.getKindMap(), symbolTable); |
Slava Zakharin | 8f3f15c | 2022-11-07 09:05:27 -0800 | [diff] [blame] | 5898 | assert(builder && "FirOpBuilder did not instantiate"); |
| 5899 | builder->setFastMathFlags(bridge.getLoweringOptions().getMathOptions()); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5900 | createGlobals(); |
| 5901 | if (mlir::Region *region = func.getCallableRegion()) |
| 5902 | region->dropAllReferences(); |
| 5903 | func.erase(); |
| 5904 | delete builder; |
| 5905 | builder = nullptr; |
| 5906 | localSymbols.clear(); |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 5907 | resetRegisteredDummySymbols(); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5908 | } |
vdonaldson | 3aba926 | 2023-12-04 09:55:54 -0800 | [diff] [blame] | 5909 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5910 | /// Instantiate the data from a BLOCK DATA unit. |
| 5911 | void lowerBlockData(Fortran::lower::pft::BlockDataUnit &bdunit) { |
| 5912 | createGlobalOutsideOfFunctionLowering([&]() { |
| 5913 | Fortran::lower::AggregateStoreMap fakeMap; |
| 5914 | for (const auto &[_, sym] : bdunit.symTab) { |
| 5915 | if (sym->has<Fortran::semantics::ObjectEntityDetails>()) { |
| 5916 | Fortran::lower::pft::Variable var(*sym, true); |
| 5917 | instantiateVar(var, fakeMap); |
| 5918 | } |
| 5919 | } |
| 5920 | }); |
| 5921 | } |
| 5922 | |
Jean Perier | 2c8cb9a | 2022-04-29 14:52:27 +0200 | [diff] [blame] | 5923 | /// Create fir::Global for all the common blocks that appear in the program. |
| 5924 | void |
| 5925 | lowerCommonBlocks(const Fortran::semantics::CommonBlockList &commonBlocks) { |
| 5926 | createGlobalOutsideOfFunctionLowering( |
| 5927 | [&]() { Fortran::lower::defineCommonBlocks(*this, commonBlocks); }); |
| 5928 | } |
| 5929 | |
vdonaldson | 3aba926 | 2023-12-04 09:55:54 -0800 | [diff] [blame] | 5930 | /// Create intrinsic module array constant definitions. |
| 5931 | void createIntrinsicModuleDefinitions(Fortran::lower::pft::Program &pft) { |
| 5932 | // The intrinsic module scope, if present, is the first scope. |
| 5933 | const Fortran::semantics::Scope *intrinsicModuleScope = nullptr; |
| 5934 | for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) { |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 5935 | Fortran::common::visit( |
| 5936 | Fortran::common::visitors{ |
| 5937 | [&](Fortran::lower::pft::FunctionLikeUnit &f) { |
| 5938 | intrinsicModuleScope = &f.getScope().parent(); |
| 5939 | }, |
| 5940 | [&](Fortran::lower::pft::ModuleLikeUnit &m) { |
| 5941 | intrinsicModuleScope = &m.getScope().parent(); |
| 5942 | }, |
| 5943 | [&](Fortran::lower::pft::BlockDataUnit &b) {}, |
| 5944 | [&](Fortran::lower::pft::CompilerDirectiveUnit &d) {}, |
| 5945 | [&](Fortran::lower::pft::OpenACCDirectiveUnit &d) {}, |
| 5946 | }, |
| 5947 | u); |
vdonaldson | 3aba926 | 2023-12-04 09:55:54 -0800 | [diff] [blame] | 5948 | if (intrinsicModuleScope) { |
| 5949 | while (!intrinsicModuleScope->IsGlobal()) |
| 5950 | intrinsicModuleScope = &intrinsicModuleScope->parent(); |
| 5951 | intrinsicModuleScope = &intrinsicModuleScope->children().front(); |
| 5952 | break; |
| 5953 | } |
| 5954 | } |
| 5955 | if (!intrinsicModuleScope || !intrinsicModuleScope->IsIntrinsicModules()) |
| 5956 | return; |
| 5957 | for (const auto &scope : intrinsicModuleScope->children()) { |
| 5958 | llvm::StringRef modName = toStringRef(scope.symbol()->name()); |
| 5959 | if (modName != "__fortran_ieee_exceptions") |
| 5960 | continue; |
| 5961 | for (auto &var : Fortran::lower::pft::getScopeVariableList(scope)) { |
| 5962 | const Fortran::semantics::Symbol &sym = var.getSymbol(); |
| 5963 | if (sym.test(Fortran::semantics::Symbol::Flag::CompilerCreated)) |
| 5964 | continue; |
| 5965 | const auto *object = |
| 5966 | sym.detailsIf<Fortran::semantics::ObjectEntityDetails>(); |
| 5967 | if (object && object->IsArray() && object->init()) |
| 5968 | Fortran::lower::createIntrinsicModuleGlobal(*this, var); |
| 5969 | } |
| 5970 | } |
| 5971 | } |
| 5972 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5973 | /// Lower a procedure (nest). |
| 5974 | void lowerFunc(Fortran::lower::pft::FunctionLikeUnit &funit) { |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5975 | setCurrentPosition(funit.getStartingSourceLoc()); |
jeanPerier | bb8bf85 | 2024-11-26 09:21:13 +0100 | [diff] [blame] | 5976 | setCurrentFunctionUnit(&funit); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5977 | for (int entryIndex = 0, last = funit.entryPointList.size(); |
| 5978 | entryIndex < last; ++entryIndex) { |
| 5979 | funit.setActiveEntry(entryIndex); |
| 5980 | startNewFunction(funit); // the entry point for lowering this procedure |
| 5981 | for (Fortran::lower::pft::Evaluation &eval : funit.evaluationList) |
| 5982 | genFIR(eval); |
| 5983 | endNewFunction(funit); |
| 5984 | } |
| 5985 | funit.setActiveEntry(0); |
jeanPerier | bb8bf85 | 2024-11-26 09:21:13 +0100 | [diff] [blame] | 5986 | setCurrentFunctionUnit(nullptr); |
vdonaldson | 87374a8 | 2024-06-12 09:35:14 -0400 | [diff] [blame] | 5987 | for (Fortran::lower::pft::ContainedUnit &unit : funit.containedUnitList) |
| 5988 | if (auto *f = std::get_if<Fortran::lower::pft::FunctionLikeUnit>(&unit)) |
| 5989 | lowerFunc(*f); // internal procedure |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 5990 | } |
| 5991 | |
| 5992 | /// Lower module variable definitions to fir::globalOp and OpenMP/OpenACC |
| 5993 | /// declarative construct. |
| 5994 | void lowerModuleDeclScope(Fortran::lower::pft::ModuleLikeUnit &mod) { |
| 5995 | setCurrentPosition(mod.getStartingSourceLoc()); |
| 5996 | createGlobalOutsideOfFunctionLowering([&]() { |
V Donaldson | 518e6f1 | 2022-12-12 14:20:06 -0800 | [diff] [blame] | 5997 | auto &scopeVariableListMap = |
| 5998 | Fortran::lower::pft::getScopeVariableListMap(mod); |
| 5999 | for (const auto &var : Fortran::lower::pft::getScopeVariableList( |
| 6000 | mod.getScope(), scopeVariableListMap)) { |
Michael Kruse | 123eb75 | 2025-03-21 12:32:54 +0100 | [diff] [blame] | 6001 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 6002 | // Only define the variables owned by this module. |
| 6003 | const Fortran::semantics::Scope *owningScope = var.getOwningScope(); |
Michael Kruse | 123eb75 | 2025-03-21 12:32:54 +0100 | [diff] [blame] | 6004 | if (owningScope && mod.getScope() != *owningScope) |
| 6005 | continue; |
| 6006 | |
| 6007 | // Very special case: The value of numeric_storage_size depends on |
| 6008 | // compilation options and therefore its value is not yet known when |
| 6009 | // building the builtins runtime. Instead, the parameter is folding a |
| 6010 | // __numeric_storage_size() expression which is loaded into the user |
| 6011 | // program. For the iso_fortran_env object file, omit the symbol as it |
| 6012 | // is never used. |
| 6013 | if (var.hasSymbol()) { |
| 6014 | const Fortran::semantics::Symbol &sym = var.getSymbol(); |
| 6015 | const Fortran::semantics::Scope &owner = sym.owner(); |
| 6016 | if (sym.name() == "numeric_storage_size" && owner.IsModule() && |
| 6017 | DEREF(owner.symbol()).name() == "iso_fortran_env") |
| 6018 | continue; |
| 6019 | } |
| 6020 | |
| 6021 | Fortran::lower::defineModuleVariable(*this, var); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 6022 | } |
| 6023 | for (auto &eval : mod.evaluationList) |
| 6024 | genFIR(eval); |
| 6025 | }); |
| 6026 | } |
| 6027 | |
| 6028 | /// Lower functions contained in a module. |
| 6029 | void lowerMod(Fortran::lower::pft::ModuleLikeUnit &mod) { |
vdonaldson | 87374a8 | 2024-06-12 09:35:14 -0400 | [diff] [blame] | 6030 | for (Fortran::lower::pft::ContainedUnit &unit : mod.containedUnitList) |
| 6031 | if (auto *f = std::get_if<Fortran::lower::pft::FunctionLikeUnit>(&unit)) |
| 6032 | lowerFunc(*f); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 6033 | } |
| 6034 | |
| 6035 | void setCurrentPosition(const Fortran::parser::CharBlock &position) { |
| 6036 | if (position != Fortran::parser::CharBlock{}) |
| 6037 | currentPosition = position; |
| 6038 | } |
| 6039 | |
| 6040 | /// Set current position at the location of \p parseTreeNode. Note that the |
| 6041 | /// position is updated automatically when visiting statements, but not when |
| 6042 | /// entering higher level nodes like constructs or procedures. This helper is |
| 6043 | /// intended to cover the latter cases. |
| 6044 | template <typename A> |
| 6045 | void setCurrentPositionAt(const A &parseTreeNode) { |
| 6046 | setCurrentPosition(Fortran::parser::FindSourceLocation(parseTreeNode)); |
| 6047 | } |
| 6048 | |
| 6049 | //===--------------------------------------------------------------------===// |
| 6050 | // Utility methods |
| 6051 | //===--------------------------------------------------------------------===// |
| 6052 | |
| 6053 | /// Convert a parser CharBlock to a Location |
| 6054 | mlir::Location toLocation(const Fortran::parser::CharBlock &cb) { |
| 6055 | return genLocation(cb); |
| 6056 | } |
| 6057 | |
| 6058 | mlir::Location toLocation() { return toLocation(currentPosition); } |
| 6059 | void setCurrentEval(Fortran::lower::pft::Evaluation &eval) { |
| 6060 | evalPtr = &eval; |
| 6061 | } |
| 6062 | Fortran::lower::pft::Evaluation &getEval() { |
| 6063 | assert(evalPtr); |
| 6064 | return *evalPtr; |
| 6065 | } |
| 6066 | |
| 6067 | std::optional<Fortran::evaluate::Shape> |
| 6068 | getShape(const Fortran::lower::SomeExpr &expr) { |
| 6069 | return Fortran::evaluate::GetShape(foldingContext, expr); |
| 6070 | } |
| 6071 | |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 6072 | //===--------------------------------------------------------------------===// |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 6073 | // Analysis on a nested explicit iteration space. |
| 6074 | //===--------------------------------------------------------------------===// |
| 6075 | |
| 6076 | void analyzeExplicitSpace(const Fortran::parser::ConcurrentHeader &header) { |
| 6077 | explicitIterSpace.pushLevel(); |
| 6078 | for (const Fortran::parser::ConcurrentControl &ctrl : |
| 6079 | std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) { |
| 6080 | const Fortran::semantics::Symbol *ctrlVar = |
| 6081 | std::get<Fortran::parser::Name>(ctrl.t).symbol; |
| 6082 | explicitIterSpace.addSymbol(ctrlVar); |
| 6083 | } |
| 6084 | if (const auto &mask = |
| 6085 | std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>( |
| 6086 | header.t); |
| 6087 | mask.has_value()) |
| 6088 | analyzeExplicitSpace(*Fortran::semantics::GetExpr(*mask)); |
| 6089 | } |
| 6090 | template <bool LHS = false, typename A> |
| 6091 | void analyzeExplicitSpace(const Fortran::evaluate::Expr<A> &e) { |
| 6092 | explicitIterSpace.exprBase(&e, LHS); |
| 6093 | } |
| 6094 | void analyzeExplicitSpace(const Fortran::evaluate::Assignment *assign) { |
| 6095 | auto analyzeAssign = [&](const Fortran::lower::SomeExpr &lhs, |
| 6096 | const Fortran::lower::SomeExpr &rhs) { |
| 6097 | analyzeExplicitSpace</*LHS=*/true>(lhs); |
| 6098 | analyzeExplicitSpace(rhs); |
| 6099 | }; |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 6100 | Fortran::common::visit( |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 6101 | Fortran::common::visitors{ |
| 6102 | [&](const Fortran::evaluate::ProcedureRef &procRef) { |
| 6103 | // Ensure the procRef expressions are the one being visited. |
| 6104 | assert(procRef.arguments().size() == 2); |
| 6105 | const Fortran::lower::SomeExpr *lhs = |
| 6106 | procRef.arguments()[0].value().UnwrapExpr(); |
| 6107 | const Fortran::lower::SomeExpr *rhs = |
| 6108 | procRef.arguments()[1].value().UnwrapExpr(); |
| 6109 | assert(lhs && rhs && |
| 6110 | "user defined assignment arguments must be expressions"); |
| 6111 | analyzeAssign(*lhs, *rhs); |
| 6112 | }, |
| 6113 | [&](const auto &) { analyzeAssign(assign->lhs, assign->rhs); }}, |
| 6114 | assign->u); |
| 6115 | explicitIterSpace.endAssign(); |
| 6116 | } |
| 6117 | void analyzeExplicitSpace(const Fortran::parser::ForallAssignmentStmt &stmt) { |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 6118 | Fortran::common::visit([&](const auto &s) { analyzeExplicitSpace(s); }, |
| 6119 | stmt.u); |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 6120 | } |
| 6121 | void analyzeExplicitSpace(const Fortran::parser::AssignmentStmt &s) { |
| 6122 | analyzeExplicitSpace(s.typedAssignment->v.operator->()); |
| 6123 | } |
| 6124 | void analyzeExplicitSpace(const Fortran::parser::PointerAssignmentStmt &s) { |
| 6125 | analyzeExplicitSpace(s.typedAssignment->v.operator->()); |
| 6126 | } |
| 6127 | void analyzeExplicitSpace(const Fortran::parser::WhereConstruct &c) { |
| 6128 | analyzeExplicitSpace( |
| 6129 | std::get< |
| 6130 | Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>( |
| 6131 | c.t) |
| 6132 | .statement); |
| 6133 | for (const Fortran::parser::WhereBodyConstruct &body : |
| 6134 | std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t)) |
| 6135 | analyzeExplicitSpace(body); |
| 6136 | for (const Fortran::parser::WhereConstruct::MaskedElsewhere &e : |
| 6137 | std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>( |
| 6138 | c.t)) |
| 6139 | analyzeExplicitSpace(e); |
| 6140 | if (const auto &e = |
| 6141 | std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>( |
| 6142 | c.t); |
| 6143 | e.has_value()) |
| 6144 | analyzeExplicitSpace(e.operator->()); |
| 6145 | } |
| 6146 | void analyzeExplicitSpace(const Fortran::parser::WhereConstructStmt &ws) { |
| 6147 | const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr( |
| 6148 | std::get<Fortran::parser::LogicalExpr>(ws.t)); |
| 6149 | addMaskVariable(exp); |
| 6150 | analyzeExplicitSpace(*exp); |
| 6151 | } |
| 6152 | void analyzeExplicitSpace( |
| 6153 | const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) { |
| 6154 | analyzeExplicitSpace( |
| 6155 | std::get< |
| 6156 | Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>( |
| 6157 | ew.t) |
| 6158 | .statement); |
| 6159 | for (const Fortran::parser::WhereBodyConstruct &e : |
| 6160 | std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t)) |
| 6161 | analyzeExplicitSpace(e); |
| 6162 | } |
| 6163 | void analyzeExplicitSpace(const Fortran::parser::WhereBodyConstruct &body) { |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 6164 | Fortran::common::visit( |
| 6165 | Fortran::common::visitors{ |
| 6166 | [&](const Fortran::common::Indirection< |
| 6167 | Fortran::parser::WhereConstruct> &wc) { |
| 6168 | analyzeExplicitSpace(wc.value()); |
| 6169 | }, |
| 6170 | [&](const auto &s) { analyzeExplicitSpace(s.statement); }}, |
| 6171 | body.u); |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 6172 | } |
| 6173 | void analyzeExplicitSpace(const Fortran::parser::MaskedElsewhereStmt &stmt) { |
| 6174 | const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr( |
| 6175 | std::get<Fortran::parser::LogicalExpr>(stmt.t)); |
| 6176 | addMaskVariable(exp); |
| 6177 | analyzeExplicitSpace(*exp); |
| 6178 | } |
| 6179 | void |
| 6180 | analyzeExplicitSpace(const Fortran::parser::WhereConstruct::Elsewhere *ew) { |
| 6181 | for (const Fortran::parser::WhereBodyConstruct &e : |
| 6182 | std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew->t)) |
| 6183 | analyzeExplicitSpace(e); |
| 6184 | } |
| 6185 | void analyzeExplicitSpace(const Fortran::parser::WhereStmt &stmt) { |
| 6186 | const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr( |
| 6187 | std::get<Fortran::parser::LogicalExpr>(stmt.t)); |
| 6188 | addMaskVariable(exp); |
| 6189 | analyzeExplicitSpace(*exp); |
| 6190 | const std::optional<Fortran::evaluate::Assignment> &assign = |
| 6191 | std::get<Fortran::parser::AssignmentStmt>(stmt.t).typedAssignment->v; |
| 6192 | assert(assign.has_value() && "WHERE has no statement"); |
| 6193 | analyzeExplicitSpace(assign.operator->()); |
| 6194 | } |
| 6195 | void analyzeExplicitSpace(const Fortran::parser::ForallStmt &forall) { |
| 6196 | analyzeExplicitSpace( |
| 6197 | std::get< |
| 6198 | Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>( |
| 6199 | forall.t) |
| 6200 | .value()); |
| 6201 | analyzeExplicitSpace(std::get<Fortran::parser::UnlabeledStatement< |
| 6202 | Fortran::parser::ForallAssignmentStmt>>(forall.t) |
| 6203 | .statement); |
| 6204 | analyzeExplicitSpacePop(); |
| 6205 | } |
| 6206 | void |
| 6207 | analyzeExplicitSpace(const Fortran::parser::ForallConstructStmt &forall) { |
| 6208 | analyzeExplicitSpace( |
| 6209 | std::get< |
| 6210 | Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>( |
| 6211 | forall.t) |
| 6212 | .value()); |
| 6213 | } |
| 6214 | void analyzeExplicitSpace(const Fortran::parser::ForallConstruct &forall) { |
| 6215 | analyzeExplicitSpace( |
| 6216 | std::get< |
| 6217 | Fortran::parser::Statement<Fortran::parser::ForallConstructStmt>>( |
| 6218 | forall.t) |
| 6219 | .statement); |
| 6220 | for (const Fortran::parser::ForallBodyConstruct &s : |
| 6221 | std::get<std::list<Fortran::parser::ForallBodyConstruct>>(forall.t)) { |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 6222 | Fortran::common::visit( |
| 6223 | Fortran::common::visitors{ |
| 6224 | [&](const Fortran::common::Indirection< |
| 6225 | Fortran::parser::ForallConstruct> &b) { |
| 6226 | analyzeExplicitSpace(b.value()); |
| 6227 | }, |
| 6228 | [&](const Fortran::parser::WhereConstruct &w) { |
| 6229 | analyzeExplicitSpace(w); |
| 6230 | }, |
| 6231 | [&](const auto &b) { analyzeExplicitSpace(b.statement); }}, |
| 6232 | s.u); |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 6233 | } |
| 6234 | analyzeExplicitSpacePop(); |
| 6235 | } |
| 6236 | |
| 6237 | void analyzeExplicitSpacePop() { explicitIterSpace.popLevel(); } |
| 6238 | |
| 6239 | void addMaskVariable(Fortran::lower::FrontEndExpr exp) { |
| 6240 | // Note: use i8 to store bool values. This avoids round-down behavior found |
| 6241 | // with sequences of i1. That is, an array of i1 will be truncated in size |
| 6242 | // and be too small. For example, a buffer of type fir.array<7xi1> will have |
| 6243 | // 0 size. |
| 6244 | mlir::Type i64Ty = builder->getIntegerType(64); |
| 6245 | mlir::TupleType ty = fir::factory::getRaggedArrayHeaderType(*builder); |
| 6246 | mlir::Type buffTy = ty.getType(1); |
| 6247 | mlir::Type shTy = ty.getType(2); |
| 6248 | mlir::Location loc = toLocation(); |
| 6249 | mlir::Value hdr = builder->createTemporary(loc, ty); |
| 6250 | // FIXME: Is there a way to create a `zeroinitializer` in LLVM-IR dialect? |
| 6251 | // For now, explicitly set lazy ragged header to all zeros. |
| 6252 | // auto nilTup = builder->createNullConstant(loc, ty); |
| 6253 | // builder->create<fir::StoreOp>(loc, nilTup, hdr); |
| 6254 | mlir::Type i32Ty = builder->getIntegerType(32); |
| 6255 | mlir::Value zero = builder->createIntegerConstant(loc, i32Ty, 0); |
| 6256 | mlir::Value zero64 = builder->createIntegerConstant(loc, i64Ty, 0); |
| 6257 | mlir::Value flags = builder->create<fir::CoordinateOp>( |
| 6258 | loc, builder->getRefType(i64Ty), hdr, zero); |
| 6259 | builder->create<fir::StoreOp>(loc, zero64, flags); |
| 6260 | mlir::Value one = builder->createIntegerConstant(loc, i32Ty, 1); |
| 6261 | mlir::Value nullPtr1 = builder->createNullConstant(loc, buffTy); |
| 6262 | mlir::Value var = builder->create<fir::CoordinateOp>( |
| 6263 | loc, builder->getRefType(buffTy), hdr, one); |
| 6264 | builder->create<fir::StoreOp>(loc, nullPtr1, var); |
| 6265 | mlir::Value two = builder->createIntegerConstant(loc, i32Ty, 2); |
| 6266 | mlir::Value nullPtr2 = builder->createNullConstant(loc, shTy); |
| 6267 | mlir::Value shape = builder->create<fir::CoordinateOp>( |
| 6268 | loc, builder->getRefType(shTy), hdr, two); |
| 6269 | builder->create<fir::StoreOp>(loc, nullPtr2, shape); |
| 6270 | implicitIterSpace.addMaskVariable(exp, var, shape, hdr); |
| 6271 | explicitIterSpace.outermostContext().attachCleanup( |
| 6272 | [builder = this->builder, hdr, loc]() { |
| 6273 | fir::runtime::genRaggedArrayDeallocate(loc, *builder, hdr); |
| 6274 | }); |
| 6275 | } |
| 6276 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 6277 | void createRuntimeTypeInfoGlobals() {} |
| 6278 | |
Jean Perier | 7531c87 | 2023-01-20 14:05:42 +0100 | [diff] [blame] | 6279 | bool lowerToHighLevelFIR() const { |
| 6280 | return bridge.getLoweringOptions().getLowerToHighLevelFIR(); |
| 6281 | } |
| 6282 | |
Slava Zakharin | be5747e | 2023-05-09 19:50:48 -0700 | [diff] [blame] | 6283 | // Returns the mangling prefix for the given constant expression. |
| 6284 | std::string getConstantExprManglePrefix(mlir::Location loc, |
| 6285 | const Fortran::lower::SomeExpr &expr, |
| 6286 | mlir::Type eleTy) { |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 6287 | return Fortran::common::visit( |
Slava Zakharin | be5747e | 2023-05-09 19:50:48 -0700 | [diff] [blame] | 6288 | [&](const auto &x) -> std::string { |
| 6289 | using T = std::decay_t<decltype(x)>; |
| 6290 | if constexpr (Fortran::common::HasMember< |
| 6291 | T, Fortran::lower::CategoryExpression>) { |
| 6292 | if constexpr (T::Result::category == |
| 6293 | Fortran::common::TypeCategory::Derived) { |
| 6294 | if (const auto *constant = |
| 6295 | std::get_if<Fortran::evaluate::Constant< |
| 6296 | Fortran::evaluate::SomeDerived>>(&x.u)) |
| 6297 | return Fortran::lower::mangle::mangleArrayLiteral(eleTy, |
| 6298 | *constant); |
| 6299 | fir::emitFatalError(loc, |
| 6300 | "non a constant derived type expression"); |
| 6301 | } else { |
Alexander Shaposhnikov | 77d8cfb | 2024-06-17 12:59:04 -0700 | [diff] [blame] | 6302 | return Fortran::common::visit( |
Slava Zakharin | be5747e | 2023-05-09 19:50:48 -0700 | [diff] [blame] | 6303 | [&](const auto &someKind) -> std::string { |
| 6304 | using T = std::decay_t<decltype(someKind)>; |
| 6305 | using TK = Fortran::evaluate::Type<T::Result::category, |
| 6306 | T::Result::kind>; |
| 6307 | if (const auto *constant = |
| 6308 | std::get_if<Fortran::evaluate::Constant<TK>>( |
| 6309 | &someKind.u)) { |
| 6310 | return Fortran::lower::mangle::mangleArrayLiteral( |
| 6311 | nullptr, *constant); |
| 6312 | } |
| 6313 | fir::emitFatalError( |
| 6314 | loc, "not a Fortran::evaluate::Constant<T> expression"); |
| 6315 | return {}; |
| 6316 | }, |
| 6317 | x.u); |
| 6318 | } |
| 6319 | } else { |
| 6320 | fir::emitFatalError(loc, "unexpected expression"); |
| 6321 | } |
| 6322 | }, |
| 6323 | expr.u); |
| 6324 | } |
| 6325 | |
Valentin Clement | 69a6bd5 | 2023-08-17 14:25:05 -0700 | [diff] [blame] | 6326 | /// Performing OpenACC lowering action that were deferred to the end of |
| 6327 | /// lowering. |
| 6328 | void finalizeOpenACCLowering() { |
| 6329 | Fortran::lower::finalizeOpenACCRoutineAttachment(getModuleOp(), |
| 6330 | accRoutineInfos); |
| 6331 | } |
| 6332 | |
Sergio Afonso | 29aa749 | 2023-03-29 18:13:48 +0100 | [diff] [blame] | 6333 | /// Performing OpenMP lowering actions that were deferred to the end of |
| 6334 | /// lowering. |
| 6335 | void finalizeOpenMPLowering( |
| 6336 | const Fortran::semantics::Symbol *globalOmpRequiresSymbol) { |
agozillon | afb05cd | 2024-03-05 17:27:16 +0100 | [diff] [blame] | 6337 | if (!ompDeferredDeclareTarget.empty()) { |
| 6338 | bool deferredDeviceFuncFound = |
| 6339 | Fortran::lower::markOpenMPDeferredDeclareTargetFunctions( |
| 6340 | getModuleOp().getOperation(), ompDeferredDeclareTarget, *this); |
| 6341 | ompDeviceCodeFound = ompDeviceCodeFound || deferredDeviceFuncFound; |
| 6342 | } |
| 6343 | |
Sergio Afonso | 29aa749 | 2023-03-29 18:13:48 +0100 | [diff] [blame] | 6344 | // Set the module attribute related to OpenMP requires directives |
| 6345 | if (ompDeviceCodeFound) |
| 6346 | Fortran::lower::genOpenMPRequires(getModuleOp().getOperation(), |
| 6347 | globalOmpRequiresSymbol); |
| 6348 | } |
| 6349 | |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 6350 | /// Record fir.dummy_scope operation for this function. |
| 6351 | /// It will be used to set dummy_scope operand of the hlfir.declare |
| 6352 | /// operations. |
| 6353 | void setDummyArgsScope(mlir::Value val) { |
| 6354 | assert(!dummyArgsScope && val); |
| 6355 | dummyArgsScope = val; |
| 6356 | } |
| 6357 | |
| 6358 | /// Record the given symbol as a dummy argument of this function. |
| 6359 | void registerDummySymbol(Fortran::semantics::SymbolRef symRef) { |
| 6360 | auto *sym = &*symRef; |
| 6361 | registeredDummySymbols.insert(sym); |
| 6362 | } |
| 6363 | |
| 6364 | /// Reset all registered dummy symbols. |
| 6365 | void resetRegisteredDummySymbols() { registeredDummySymbols.clear(); } |
| 6366 | |
jeanPerier | bb8bf85 | 2024-11-26 09:21:13 +0100 | [diff] [blame] | 6367 | void setCurrentFunctionUnit(Fortran::lower::pft::FunctionLikeUnit *unit) { |
| 6368 | currentFunctionUnit = unit; |
| 6369 | } |
| 6370 | |
Valentin Clement | 88ae0d6 | 2022-03-10 19:43:11 +0100 | [diff] [blame] | 6371 | //===--------------------------------------------------------------------===// |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 6372 | |
| 6373 | Fortran::lower::LoweringBridge &bridge; |
| 6374 | Fortran::evaluate::FoldingContext foldingContext; |
| 6375 | fir::FirOpBuilder *builder = nullptr; |
| 6376 | Fortran::lower::pft::Evaluation *evalPtr = nullptr; |
jeanPerier | bb8bf85 | 2024-11-26 09:21:13 +0100 | [diff] [blame] | 6377 | Fortran::lower::pft::FunctionLikeUnit *currentFunctionUnit = nullptr; |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 6378 | Fortran::lower::SymMap localSymbols; |
| 6379 | Fortran::parser::CharBlock currentPosition; |
jeanPerier | 4ccd57d | 2023-10-06 09:29:57 +0200 | [diff] [blame] | 6380 | TypeInfoConverter typeInfoConverter; |
Valentin Clement | d0b70a0 | 2022-02-23 19:48:07 +0100 | [diff] [blame] | 6381 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 6382 | // Stack to manage object deallocation and finalization at construct exits. |
| 6383 | llvm::SmallVector<ConstructContext> activeConstructStack; |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 6384 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 6385 | /// BLOCK name mangling component map |
| 6386 | int blockId = 0; |
| 6387 | Fortran::lower::mangle::ScopeBlockIdMap scopeBlockIdMap; |
| 6388 | |
| 6389 | /// FORALL statement/construct context |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 6390 | Fortran::lower::ExplicitIterSpace explicitIterSpace; |
| 6391 | |
V Donaldson | 2c14334 | 2023-02-27 14:05:53 -0800 | [diff] [blame] | 6392 | /// WHERE statement/construct mask expression stack |
| 6393 | Fortran::lower::ImplicitIterSpace implicitIterSpace; |
| 6394 | |
| 6395 | /// Tuple of host associated variables |
Valentin Clement | d0b70a0 | 2022-02-23 19:48:07 +0100 | [diff] [blame] | 6396 | mlir::Value hostAssocTuple; |
Slava Zakharin | be5747e | 2023-05-09 19:50:48 -0700 | [diff] [blame] | 6397 | |
Slava Zakharin | 1710c8c | 2024-05-08 16:48:14 -0700 | [diff] [blame] | 6398 | /// Value of fir.dummy_scope operation for this function. |
| 6399 | mlir::Value dummyArgsScope; |
| 6400 | |
| 6401 | /// A set of dummy argument symbols for this function. |
| 6402 | /// The set is only preserved during the instatiation |
| 6403 | /// of variables for this function. |
| 6404 | llvm::SmallPtrSet<const Fortran::semantics::Symbol *, 16> |
| 6405 | registeredDummySymbols; |
| 6406 | |
Slava Zakharin | be5747e | 2023-05-09 19:50:48 -0700 | [diff] [blame] | 6407 | /// A map of unique names for constant expressions. |
| 6408 | /// The names are used for representing the constant expressions |
| 6409 | /// with global constant initialized objects. |
| 6410 | /// The names are usually prefixed by a mangling string based |
| 6411 | /// on the element type of the constant expression, but the element |
| 6412 | /// type is not used as a key into the map (so the assumption is that |
| 6413 | /// the equivalent constant expressions are prefixed using the same |
| 6414 | /// element type). |
| 6415 | llvm::DenseMap<const Fortran::lower::SomeExpr *, std::string> literalNamesMap; |
| 6416 | |
| 6417 | /// Storage for Constant expressions used as keys for literalNamesMap. |
| 6418 | llvm::SmallVector<std::unique_ptr<Fortran::lower::SomeExpr>> |
| 6419 | literalExprsStorage; |
| 6420 | |
| 6421 | /// A counter for uniquing names in `literalNamesMap`. |
| 6422 | std::uint64_t uniqueLitId = 0; |
Valentin Clement | 69a6bd5 | 2023-08-17 14:25:05 -0700 | [diff] [blame] | 6423 | |
| 6424 | /// Deferred OpenACC routine attachment. |
| 6425 | Fortran::lower::AccRoutineInfoMappingList accRoutineInfos; |
Sergio Afonso | 29aa749 | 2023-03-29 18:13:48 +0100 | [diff] [blame] | 6426 | |
| 6427 | /// Whether an OpenMP target region or declare target function/subroutine |
| 6428 | /// intended for device offloading has been detected |
| 6429 | bool ompDeviceCodeFound = false; |
jeanPerier | b6b0756 | 2023-10-25 09:22:23 +0200 | [diff] [blame] | 6430 | |
agozillon | afb05cd | 2024-03-05 17:27:16 +0100 | [diff] [blame] | 6431 | /// Keeps track of symbols defined as declare target that could not be |
| 6432 | /// processed at the time of lowering the declare target construct, such |
| 6433 | /// as certain cases where interfaces are declared but not defined within |
| 6434 | /// a module. |
| 6435 | llvm::SmallVector<Fortran::lower::OMPDeferredDeclareTargetInfo> |
| 6436 | ompDeferredDeclareTarget; |
| 6437 | |
jeanPerier | b6b0756 | 2023-10-25 09:22:23 +0200 | [diff] [blame] | 6438 | const Fortran::lower::ExprToValueMap *exprValueOverrides{nullptr}; |
jeanPerier | c373f58 | 2023-12-19 17:17:09 +0100 | [diff] [blame] | 6439 | |
| 6440 | /// Stack of derived type under construction to avoid infinite loops when |
| 6441 | /// dealing with recursive derived types. This is held in the bridge because |
| 6442 | /// the state needs to be maintained between data and function type lowering |
| 6443 | /// utilities to deal with procedure pointer components whose arguments have |
| 6444 | /// the type of the containing derived type. |
| 6445 | Fortran::lower::TypeConstructionStack typeConstructionStack; |
jeanPerier | a4798bb | 2024-04-02 14:29:29 +0200 | [diff] [blame] | 6446 | /// MLIR symbol table of the fir.global/func.func operations. Note that it is |
| 6447 | /// not guaranteed to contain all operations of the ModuleOp with Symbol |
| 6448 | /// attribute since mlirSymbolTable must pro-actively be maintained when |
| 6449 | /// new Symbol operations are created. |
| 6450 | mlir::SymbolTable mlirSymbolTable; |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 6451 | }; |
| 6452 | |
| 6453 | } // namespace |
| 6454 | |
| 6455 | Fortran::evaluate::FoldingContext |
jeanPerier | 181eab2 | 2024-01-29 18:28:56 +0100 | [diff] [blame] | 6456 | Fortran::lower::LoweringBridge::createFoldingContext() { |
Peter Klausler | 1c91d9b | 2023-11-13 16:13:50 -0800 | [diff] [blame] | 6457 | return {getDefaultKinds(), getIntrinsicTable(), getTargetCharacteristics(), |
jeanPerier | 181eab2 | 2024-01-29 18:28:56 +0100 | [diff] [blame] | 6458 | getLanguageFeatures(), tempNames}; |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 6459 | } |
| 6460 | |
| 6461 | void Fortran::lower::LoweringBridge::lower( |
| 6462 | const Fortran::parser::Program &prg, |
| 6463 | const Fortran::semantics::SemanticsContext &semanticsContext) { |
| 6464 | std::unique_ptr<Fortran::lower::pft::Program> pft = |
| 6465 | Fortran::lower::createPFT(prg, semanticsContext); |
| 6466 | if (dumpBeforeFir) |
| 6467 | Fortran::lower::dumpPFT(llvm::errs(), *pft); |
| 6468 | FirConverter converter{*this}; |
| 6469 | converter.run(*pft); |
| 6470 | } |
| 6471 | |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 6472 | void Fortran::lower::LoweringBridge::parseSourceFile(llvm::SourceMgr &srcMgr) { |
Matthias Springer | c870632 | 2024-12-25 09:42:03 +0100 | [diff] [blame] | 6473 | module = mlir::parseSourceFile<mlir::ModuleOp>(srcMgr, &context); |
Valentin Clement | fe252f8 | 2022-03-22 15:40:32 +0100 | [diff] [blame] | 6474 | } |
| 6475 | |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 6476 | Fortran::lower::LoweringBridge::LoweringBridge( |
| 6477 | mlir::MLIRContext &context, |
Valentin Clement | 8fc0024 | 2022-08-12 21:22:30 +0200 | [diff] [blame] | 6478 | Fortran::semantics::SemanticsContext &semanticsContext, |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 6479 | const Fortran::common::IntrinsicTypeDefaultKinds &defaultKinds, |
| 6480 | const Fortran::evaluate::IntrinsicProcTable &intrinsics, |
Peter Klausler | 23c2bed | 2022-07-01 11:40:44 -0700 | [diff] [blame] | 6481 | const Fortran::evaluate::TargetCharacteristics &targetCharacteristics, |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 6482 | const Fortran::parser::AllCookedSources &cooked, llvm::StringRef triple, |
Slava Zakharin | f1eb945 | 2022-07-19 20:39:58 -0700 | [diff] [blame] | 6483 | fir::KindMapping &kindMap, |
Jonathon Penix | 0ec3ac9 | 2022-07-19 11:47:25 -0700 | [diff] [blame] | 6484 | const Fortran::lower::LoweringOptions &loweringOptions, |
Peter Klausler | 1c91d9b | 2023-11-13 16:13:50 -0800 | [diff] [blame] | 6485 | const std::vector<Fortran::lower::EnvironmentDefault> &envDefaults, |
jeanPerier | e59e848 | 2023-12-06 14:20:06 +0100 | [diff] [blame] | 6486 | const Fortran::common::LanguageFeatureControl &languageFeatures, |
Tarun Prabhu | 839344f | 2024-10-14 08:44:24 -0600 | [diff] [blame] | 6487 | const llvm::TargetMachine &targetMachine, |
| 6488 | const Fortran::frontend::TargetOptions &targetOpts, |
| 6489 | const Fortran::frontend::CodeGenOptions &cgOpts) |
Valentin Clement | 8fc0024 | 2022-08-12 21:22:30 +0200 | [diff] [blame] | 6490 | : semanticsContext{semanticsContext}, defaultKinds{defaultKinds}, |
| 6491 | intrinsics{intrinsics}, targetCharacteristics{targetCharacteristics}, |
| 6492 | cooked{&cooked}, context{context}, kindMap{kindMap}, |
Peter Klausler | 1c91d9b | 2023-11-13 16:13:50 -0800 | [diff] [blame] | 6493 | loweringOptions{loweringOptions}, envDefaults{envDefaults}, |
| 6494 | languageFeatures{languageFeatures} { |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 6495 | // Register the diagnostic handler. |
| 6496 | context.getDiagEngine().registerHandler([](mlir::Diagnostic &diag) { |
| 6497 | llvm::raw_ostream &os = llvm::errs(); |
| 6498 | switch (diag.getSeverity()) { |
| 6499 | case mlir::DiagnosticSeverity::Error: |
| 6500 | os << "error: "; |
| 6501 | break; |
| 6502 | case mlir::DiagnosticSeverity::Remark: |
| 6503 | os << "info: "; |
| 6504 | break; |
| 6505 | case mlir::DiagnosticSeverity::Warning: |
| 6506 | os << "warning: "; |
| 6507 | break; |
| 6508 | default: |
| 6509 | break; |
| 6510 | } |
Christian Sigg | fac349a | 2024-04-28 22:01:42 +0200 | [diff] [blame] | 6511 | if (!mlir::isa<mlir::UnknownLoc>(diag.getLocation())) |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 6512 | os << diag.getLocation() << ": "; |
| 6513 | os << diag << '\n'; |
| 6514 | os.flush(); |
| 6515 | return mlir::success(); |
| 6516 | }); |
| 6517 | |
Kiran Chandramohan | eef0210 | 2023-01-19 16:49:26 +0000 | [diff] [blame] | 6518 | auto getPathLocation = [&semanticsContext, &context]() -> mlir::Location { |
| 6519 | std::optional<std::string> path; |
| 6520 | const auto &allSources{semanticsContext.allCookedSources().allSources()}; |
| 6521 | if (auto initial{allSources.GetFirstFileProvenance()}; |
| 6522 | initial && !initial->empty()) { |
| 6523 | if (const auto *sourceFile{allSources.GetSourceFile(initial->start())}) { |
| 6524 | path = sourceFile->path(); |
| 6525 | } |
| 6526 | } |
| 6527 | |
| 6528 | if (path.has_value()) { |
| 6529 | llvm::SmallString<256> curPath(*path); |
| 6530 | llvm::sys::fs::make_absolute(curPath); |
| 6531 | llvm::sys::path::remove_dots(curPath); |
| 6532 | return mlir::FileLineColLoc::get(&context, curPath.str(), /*line=*/0, |
| 6533 | /*col=*/0); |
| 6534 | } else { |
| 6535 | return mlir::UnknownLoc::get(&context); |
| 6536 | } |
| 6537 | }; |
| 6538 | |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 6539 | // Create the module and attach the attributes. |
Matthias Springer | c870632 | 2024-12-25 09:42:03 +0100 | [diff] [blame] | 6540 | module = mlir::OwningOpRef<mlir::ModuleOp>( |
Kiran Chandramohan | eef0210 | 2023-01-19 16:49:26 +0000 | [diff] [blame] | 6541 | mlir::ModuleOp::create(getPathLocation())); |
Matthias Springer | c870632 | 2024-12-25 09:42:03 +0100 | [diff] [blame] | 6542 | assert(*module && "module was not created"); |
| 6543 | fir::setTargetTriple(*module, triple); |
| 6544 | fir::setKindMapping(*module, kindMap); |
| 6545 | fir::setTargetCPU(*module, targetMachine.getTargetCPU()); |
| 6546 | fir::setTuneCPU(*module, targetOpts.cpuToTuneFor); |
| 6547 | fir::setTargetFeatures(*module, targetMachine.getTargetFeatureString()); |
| 6548 | fir::support::setMLIRDataLayout(*module, targetMachine.createDataLayout()); |
| 6549 | fir::setIdent(*module, Fortran::common::getFlangFullVersion()); |
Tarun Prabhu | 839344f | 2024-10-14 08:44:24 -0600 | [diff] [blame] | 6550 | if (cgOpts.RecordCommandLine) |
Matthias Springer | c870632 | 2024-12-25 09:42:03 +0100 | [diff] [blame] | 6551 | fir::setCommandline(*module, *cgOpts.RecordCommandLine); |
Valentin Clement | e1a1276 | 2022-01-28 22:39:44 +0100 | [diff] [blame] | 6552 | } |
jeanPerier | c7c5666 | 2024-05-14 13:34:46 +0200 | [diff] [blame] | 6553 | |
| 6554 | void Fortran::lower::genCleanUpInRegionIfAny( |
| 6555 | mlir::Location loc, fir::FirOpBuilder &builder, mlir::Region ®ion, |
| 6556 | Fortran::lower::StatementContext &context) { |
| 6557 | if (!context.hasCode()) |
| 6558 | return; |
| 6559 | mlir::OpBuilder::InsertPoint insertPt = builder.saveInsertionPoint(); |
| 6560 | if (region.empty()) |
| 6561 | builder.createBlock(®ion); |
| 6562 | else |
| 6563 | builder.setInsertionPointToEnd(®ion.front()); |
| 6564 | context.finalizeAndPop(); |
| 6565 | hlfir::YieldOp::ensureTerminator(region, builder, loc); |
| 6566 | builder.restoreInsertionPoint(insertPt); |
| 6567 | } |