| 1 |
//===-- IO.cpp -- IO statement lowering -----------------------------------===// |
| 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/IO.h" |
| 14 |
#include "flang/Common/uint128.h" |
| 15 |
#include "flang/Evaluate/tools.h" |
| 16 |
#include "flang/Lower/Allocatable.h" |
| 17 |
#include "flang/Lower/Bridge.h" |
| 18 |
#include "flang/Lower/CallInterface.h" |
| 19 |
#include "flang/Lower/ConvertExpr.h" |
| 20 |
#include "flang/Lower/ConvertVariable.h" |
| 21 |
#include "flang/Lower/Mangler.h" |
| 22 |
#include "flang/Lower/PFTBuilder.h" |
| 23 |
#include "flang/Lower/Runtime.h" |
| 24 |
#include "flang/Lower/StatementContext.h" |
| 25 |
#include "flang/Lower/Support/Utils.h" |
| 26 |
#include "flang/Lower/VectorSubscripts.h" |
| 27 |
#include "flang/Optimizer/Builder/Character.h" |
| 28 |
#include "flang/Optimizer/Builder/Complex.h" |
| 29 |
#include "flang/Optimizer/Builder/FIRBuilder.h" |
| 30 |
#include "flang/Optimizer/Builder/Runtime/RTBuilder.h" |
| 31 |
#include "flang/Optimizer/Builder/Runtime/Stop.h" |
| 32 |
#include "flang/Optimizer/Builder/Todo.h" |
| 33 |
#include "flang/Optimizer/Dialect/FIRDialect.h" |
| 34 |
#include "flang/Optimizer/Dialect/Support/FIRContext.h" |
| 35 |
#include "flang/Parser/parse-tree.h" |
| 36 |
#include "flang/Runtime/io-api.h" |
| 37 |
#include "flang/Semantics/runtime-type-info.h" |
| 38 |
#include "flang/Semantics/tools.h" |
| 39 |
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" |
| 40 |
#include "llvm/Support/Debug.h" |
| 41 |
#include <optional> |
| 42 |
|
| 43 |
#define DEBUG_TYPE "flang-lower-io" |
| 44 |
|
| 45 |
// Define additional runtime type models specific to IO. |
| 46 |
namespace fir::runtime { |
| 47 |
template <> |
| 48 |
constexpr TypeBuilderFunc getModel<Fortran::runtime::io::IoStatementState *>() { |
| 49 |
return getModel<char *>(); |
| 50 |
} |
| 51 |
template <> |
| 52 |
constexpr TypeBuilderFunc getModel<Fortran::runtime::io::Iostat>() { |
| 53 |
return [](mlir::MLIRContext *context) -> mlir::Type { |
| 54 |
return mlir::IntegerType::get(context, |
| 55 |
8 * sizeof(Fortran::runtime::io::Iostat)); |
| 56 |
}; |
| 57 |
} |
| 58 |
template <> |
| 59 |
constexpr TypeBuilderFunc |
| 60 |
getModel<const Fortran::runtime::io::NamelistGroup &>() { |
| 61 |
return [](mlir::MLIRContext *context) -> mlir::Type { |
| 62 |
return fir::ReferenceType::get(mlir::TupleType::get(context)); |
| 63 |
}; |
| 64 |
} |
| 65 |
template <> |
| 66 |
constexpr TypeBuilderFunc |
| 67 |
getModel<const Fortran::runtime::io::NonTbpDefinedIoTable *>() { |
| 68 |
return [](mlir::MLIRContext *context) -> mlir::Type { |
| 69 |
return fir::ReferenceType::get(mlir::TupleType::get(context)); |
| 70 |
}; |
| 71 |
} |
| 72 |
} // namespace fir::runtime |
| 73 |
|
| 74 |
using namespace Fortran::runtime::io; |
| 75 |
|
| 76 |
#define mkIOKey(X) FirmkKey(IONAME(X)) |
| 77 |
|
| 78 |
namespace Fortran::lower { |
| 79 |
/// Static table of IO runtime calls |
| 80 |
/// |
| 81 |
/// This logical map contains the name and type builder function for each IO |
| 82 |
/// runtime function listed in the tuple. This table is fully constructed at |
| 83 |
/// compile-time. Use the `mkIOKey` macro to access the table. |
| 84 |
static constexpr std::tuple< |
| 85 |
mkIOKey(BeginBackspace), mkIOKey(BeginClose), mkIOKey(BeginEndfile), |
| 86 |
mkIOKey(BeginExternalFormattedInput), mkIOKey(BeginExternalFormattedOutput), |
| 87 |
mkIOKey(BeginExternalListInput), mkIOKey(BeginExternalListOutput), |
| 88 |
mkIOKey(BeginFlush), mkIOKey(BeginInquireFile), |
| 89 |
mkIOKey(BeginInquireIoLength), mkIOKey(BeginInquireUnit), |
| 90 |
mkIOKey(BeginInternalArrayFormattedInput), |
| 91 |
mkIOKey(BeginInternalArrayFormattedOutput), |
| 92 |
mkIOKey(BeginInternalArrayListInput), mkIOKey(BeginInternalArrayListOutput), |
| 93 |
mkIOKey(BeginInternalFormattedInput), mkIOKey(BeginInternalFormattedOutput), |
| 94 |
mkIOKey(BeginInternalListInput), mkIOKey(BeginInternalListOutput), |
| 95 |
mkIOKey(BeginOpenNewUnit), mkIOKey(BeginOpenUnit), mkIOKey(BeginRewind), |
| 96 |
mkIOKey(BeginUnformattedInput), mkIOKey(BeginUnformattedOutput), |
| 97 |
mkIOKey(BeginWait), mkIOKey(BeginWaitAll), |
| 98 |
mkIOKey(CheckUnitNumberInRange64), mkIOKey(CheckUnitNumberInRange128), |
| 99 |
mkIOKey(EnableHandlers), mkIOKey(EndIoStatement), |
| 100 |
mkIOKey(GetAsynchronousId), mkIOKey(GetIoLength), mkIOKey(GetIoMsg), |
| 101 |
mkIOKey(GetNewUnit), mkIOKey(GetSize), mkIOKey(InputAscii), |
| 102 |
mkIOKey(InputComplex32), mkIOKey(InputComplex64), mkIOKey(InputDerivedType), |
| 103 |
mkIOKey(InputDescriptor), mkIOKey(InputInteger), mkIOKey(InputLogical), |
| 104 |
mkIOKey(InputNamelist), mkIOKey(InputReal32), mkIOKey(InputReal64), |
| 105 |
mkIOKey(InquireCharacter), mkIOKey(InquireInteger64), |
| 106 |
mkIOKey(InquireLogical), mkIOKey(InquirePendingId), mkIOKey(OutputAscii), |
| 107 |
mkIOKey(OutputComplex32), mkIOKey(OutputComplex64), |
| 108 |
mkIOKey(OutputDerivedType), mkIOKey(OutputDescriptor), |
| 109 |
mkIOKey(OutputInteger8), mkIOKey(OutputInteger16), mkIOKey(OutputInteger32), |
| 110 |
mkIOKey(OutputInteger64), mkIOKey(OutputInteger128), mkIOKey(OutputLogical), |
| 111 |
mkIOKey(OutputNamelist), mkIOKey(OutputReal32), mkIOKey(OutputReal64), |
| 112 |
mkIOKey(SetAccess), mkIOKey(SetAction), mkIOKey(SetAdvance), |
| 113 |
mkIOKey(SetAsynchronous), mkIOKey(SetBlank), mkIOKey(SetCarriagecontrol), |
| 114 |
mkIOKey(SetConvert), mkIOKey(SetDecimal), mkIOKey(SetDelim), |
| 115 |
mkIOKey(SetEncoding), mkIOKey(SetFile), mkIOKey(SetForm), mkIOKey(SetPad), |
| 116 |
mkIOKey(SetPos), mkIOKey(SetPosition), mkIOKey(SetRec), mkIOKey(SetRecl), |
| 117 |
mkIOKey(SetRound), mkIOKey(SetSign), mkIOKey(SetStatus)> |
| 118 |
newIOTable; |
| 119 |
} // namespace Fortran::lower |
| 120 |
|
| 121 |
namespace { |
| 122 |
/// IO statements may require exceptional condition handling. A statement that |
| 123 |
/// encounters an exceptional condition may branch to a label given on an ERR |
| 124 |
/// (error), END (end-of-file), or EOR (end-of-record) specifier. An IOSTAT |
| 125 |
/// specifier variable may be set to a value that indicates some condition, |
| 126 |
/// and an IOMSG specifier variable may be set to a description of a condition. |
| 127 |
struct ConditionSpecInfo { |
| 128 |
const Fortran::lower::SomeExpr *ioStatExpr{}; |
| 129 |
std::optional<fir::ExtendedValue> ioMsg; |
| 130 |
bool hasErr{}; |
| 131 |
bool hasEnd{}; |
| 132 |
bool hasEor{}; |
| 133 |
fir::IfOp bigUnitIfOp; |
| 134 |
|
| 135 |
/// Check for any condition specifier that applies to specifier processing. |
| 136 |
bool hasErrorConditionSpec() const { return ioStatExpr != nullptr || hasErr; } |
| 137 |
|
| 138 |
/// Check for any condition specifier that applies to data transfer items |
| 139 |
/// in a PRINT, READ, WRITE, or WAIT statement. (WAIT may be irrelevant.) |
| 140 |
bool hasTransferConditionSpec() const { |
| 141 |
return hasErrorConditionSpec() || hasEnd || hasEor; |
| 142 |
} |
| 143 |
|
| 144 |
/// Check for any condition specifier, including IOMSG. |
| 145 |
bool hasAnyConditionSpec() const { |
| 146 |
return hasTransferConditionSpec() || ioMsg; |
| 147 |
} |
| 148 |
}; |
| 149 |
} // namespace |
| 150 |
|
| 151 |
template <typename D> |
| 152 |
static void genIoLoop(Fortran::lower::AbstractConverter &converter, |
| 153 |
mlir::Value cookie, const D &ioImpliedDo, |
| 154 |
bool isFormatted, bool checkResult, mlir::Value &ok, |
| 155 |
bool inLoop); |
| 156 |
|
| 157 |
/// Helper function to retrieve the name of the IO function given the key `A` |
| 158 |
template <typename A> |
| 159 |
static constexpr const char *getName() { |
| 160 |
return std::get<A>(Fortran::lower::newIOTable).name; |
| 161 |
} |
| 162 |
|
| 163 |
/// Helper function to retrieve the type model signature builder of the IO |
| 164 |
/// function as defined by the key `A` |
| 165 |
template <typename A> |
| 166 |
static constexpr fir::runtime::FuncTypeBuilderFunc getTypeModel() { |
| 167 |
return std::get<A>(Fortran::lower::newIOTable).getTypeModel(); |
| 168 |
} |
| 169 |
|
| 170 |
inline int64_t getLength(mlir::Type argTy) { |
| 171 |
return mlir::cast<fir::SequenceType>(argTy).getShape()[0]; |
| 172 |
} |
| 173 |
|
| 174 |
/// Get (or generate) the MLIR FuncOp for a given IO runtime function. |
| 175 |
template <typename E> |
| 176 |
static mlir::func::FuncOp getIORuntimeFunc(mlir::Location loc, |
| 177 |
fir::FirOpBuilder &builder) { |
| 178 |
llvm::StringRef name = getName<E>(); |
| 179 |
mlir::func::FuncOp func = builder.getNamedFunction(name); |
| 180 |
if (func) |
| 181 |
return func; |
| 182 |
auto funTy = getTypeModel<E>()(builder.getContext()); |
| 183 |
func = builder.createFunction(loc, name, funTy); |
| 184 |
func->setAttr(fir::FIROpsDialect::getFirRuntimeAttrName(), |
| 185 |
builder.getUnitAttr()); |
| 186 |
func->setAttr("fir.io", builder.getUnitAttr()); |
| 187 |
return func; |
| 188 |
} |
| 189 |
|
| 190 |
/// Generate calls to end an IO statement. Return the IOSTAT value, if any. |
| 191 |
/// It is the caller's responsibility to generate branches on that value. |
| 192 |
static mlir::Value genEndIO(Fortran::lower::AbstractConverter &converter, |
| 193 |
mlir::Location loc, mlir::Value cookie, |
| 194 |
ConditionSpecInfo &csi, |
| 195 |
Fortran::lower::StatementContext &stmtCtx) { |
| 196 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 197 |
if (csi.ioMsg) { |
| 198 |
mlir::func::FuncOp getIoMsg = |
| 199 |
getIORuntimeFunc<mkIOKey(GetIoMsg)>(loc, builder); |
| 200 |
builder.create<fir::CallOp>( |
| 201 |
loc, getIoMsg, |
| 202 |
mlir::ValueRange{ |
| 203 |
cookie, |
| 204 |
builder.createConvert(loc, getIoMsg.getFunctionType().getInput(1), |
| 205 |
fir::getBase(*csi.ioMsg)), |
| 206 |
builder.createConvert(loc, getIoMsg.getFunctionType().getInput(2), |
| 207 |
fir::getLen(*csi.ioMsg))}); |
| 208 |
} |
| 209 |
mlir::func::FuncOp endIoStatement = |
| 210 |
getIORuntimeFunc<mkIOKey(EndIoStatement)>(loc, builder); |
| 211 |
auto call = builder.create<fir::CallOp>(loc, endIoStatement, |
| 212 |
mlir::ValueRange{cookie}); |
| 213 |
mlir::Value iostat = call.getResult(0); |
| 214 |
if (csi.bigUnitIfOp) { |
| 215 |
stmtCtx.finalizeAndPop(); |
| 216 |
builder.create<fir::ResultOp>(loc, iostat); |
| 217 |
builder.setInsertionPointAfter(csi.bigUnitIfOp); |
| 218 |
iostat = csi.bigUnitIfOp.getResult(0); |
| 219 |
} |
| 220 |
if (csi.ioStatExpr) { |
| 221 |
mlir::Value ioStatVar = |
| 222 |
fir::getBase(converter.genExprAddr(loc, csi.ioStatExpr, stmtCtx)); |
| 223 |
mlir::Value ioStatResult = |
| 224 |
builder.createConvert(loc, converter.genType(*csi.ioStatExpr), iostat); |
| 225 |
builder.create<fir::StoreOp>(loc, ioStatResult, ioStatVar); |
| 226 |
} |
| 227 |
return csi.hasTransferConditionSpec() ? iostat : mlir::Value{}; |
| 228 |
} |
| 229 |
|
| 230 |
/// Make the next call in the IO statement conditional on runtime result `ok`. |
| 231 |
/// If a call returns `ok==false`, further suboperation calls for an IO |
| 232 |
/// statement will be skipped. This may generate branch heavy, deeply nested |
| 233 |
/// conditionals for IO statements with a large number of suboperations. |
| 234 |
static void makeNextConditionalOn(fir::FirOpBuilder &builder, |
| 235 |
mlir::Location loc, bool checkResult, |
| 236 |
mlir::Value ok, bool inLoop = false) { |
| 237 |
if (!checkResult || !ok) |
| 238 |
// Either no IO calls need to be checked, or this will be the first call. |
| 239 |
return; |
| 240 |
|
| 241 |
// A previous IO call for a statement returned the bool `ok`. If this call |
| 242 |
// is in a fir.iterate_while loop, the result must be propagated up to the |
| 243 |
// loop scope as an extra ifOp result. (The propagation is done in genIoLoop.) |
| 244 |
mlir::TypeRange resTy; |
| 245 |
// TypeRange does not own its contents, so make sure the the type object |
| 246 |
// is live until the end of the function. |
| 247 |
mlir::IntegerType boolTy = builder.getI1Type(); |
| 248 |
if (inLoop) |
| 249 |
resTy = boolTy; |
| 250 |
auto ifOp = builder.create<fir::IfOp>(loc, resTy, ok, |
| 251 |
/*withElseRegion=*/inLoop); |
| 252 |
builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); |
| 253 |
} |
| 254 |
|
| 255 |
// Derived type symbols may each be mapped to up to 4 defined IO procedures. |
| 256 |
using DefinedIoProcMap = std::multimap<const Fortran::semantics::Symbol *, |
| 257 |
Fortran::semantics::NonTbpDefinedIo>; |
| 258 |
|
| 259 |
/// Get the current scope's non-type-bound defined IO procedures. |
| 260 |
static DefinedIoProcMap |
| 261 |
getDefinedIoProcMap(Fortran::lower::AbstractConverter &converter) { |
| 262 |
const Fortran::semantics::Scope *scope = &converter.getCurrentScope(); |
| 263 |
for (; !scope->IsGlobal(); scope = &scope->parent()) |
| 264 |
if (scope->kind() == Fortran::semantics::Scope::Kind::MainProgram || |
| 265 |
scope->kind() == Fortran::semantics::Scope::Kind::Subprogram || |
| 266 |
scope->kind() == Fortran::semantics::Scope::Kind::BlockConstruct) |
| 267 |
break; |
| 268 |
return Fortran::semantics::CollectNonTbpDefinedIoGenericInterfaces(*scope, |
| 269 |
false); |
| 270 |
} |
| 271 |
|
| 272 |
/// Check a set of defined IO procedures for any procedure pointer or dummy |
| 273 |
/// procedures. |
| 274 |
static bool hasLocalDefinedIoProc(DefinedIoProcMap &definedIoProcMap) { |
| 275 |
for (auto &iface : definedIoProcMap) { |
| 276 |
const Fortran::semantics::Symbol *procSym = iface.second.subroutine; |
| 277 |
if (!procSym) |
| 278 |
continue; |
| 279 |
procSym = &procSym->GetUltimate(); |
| 280 |
if (Fortran::semantics::IsProcedurePointer(*procSym) || |
| 281 |
Fortran::semantics::IsDummy(*procSym)) |
| 282 |
return true; |
| 283 |
} |
| 284 |
return false; |
| 285 |
} |
| 286 |
|
| 287 |
/// Retrieve or generate a runtime description of the non-type-bound defined |
| 288 |
/// IO procedures in the current scope. If any procedure is a dummy or a |
| 289 |
/// procedure pointer, the result is local. Otherwise the result is static. |
| 290 |
/// If there are no procedures, return a scope-independent default table with |
| 291 |
/// an empty procedure list, but with the `ignoreNonTbpEntries` flag set. The |
| 292 |
/// form of the description is defined in runtime header file non-tbp-dio.h. |
| 293 |
static mlir::Value |
| 294 |
getNonTbpDefinedIoTableAddr(Fortran::lower::AbstractConverter &converter, |
| 295 |
DefinedIoProcMap &definedIoProcMap) { |
| 296 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 297 |
mlir::MLIRContext *context = builder.getContext(); |
| 298 |
mlir::Location loc = converter.getCurrentLocation(); |
| 299 |
mlir::Type refTy = fir::ReferenceType::get(mlir::NoneType::get(context)); |
| 300 |
std::string suffix = ".nonTbpDefinedIoTable"; |
| 301 |
std::string tableMangleName = definedIoProcMap.empty() |
| 302 |
? "default" + suffix |
| 303 |
: converter.mangleName(suffix); |
| 304 |
if (auto table = builder.getNamedGlobal(tableMangleName)) |
| 305 |
return builder.createConvert( |
| 306 |
loc, refTy, |
| 307 |
builder.create<fir::AddrOfOp>(loc, table.resultType(), |
| 308 |
table.getSymbol())); |
| 309 |
|
| 310 |
mlir::StringAttr linkOnce = builder.createLinkOnceLinkage(); |
| 311 |
mlir::Type idxTy = builder.getIndexType(); |
| 312 |
mlir::Type sizeTy = |
| 313 |
fir::runtime::getModel<std::size_t>()(builder.getContext()); |
| 314 |
mlir::Type intTy = fir::runtime::getModel<int>()(builder.getContext()); |
| 315 |
mlir::Type boolTy = fir::runtime::getModel<bool>()(builder.getContext()); |
| 316 |
mlir::Type listTy = fir::SequenceType::get( |
| 317 |
definedIoProcMap.size(), |
| 318 |
mlir::TupleType::get(context, {refTy, refTy, intTy, boolTy})); |
| 319 |
mlir::Type tableTy = mlir::TupleType::get( |
| 320 |
context, {sizeTy, fir::ReferenceType::get(listTy), boolTy}); |
| 321 |
|
| 322 |
// Define the list of NonTbpDefinedIo procedures. |
| 323 |
bool tableIsLocal = |
| 324 |
!definedIoProcMap.empty() && hasLocalDefinedIoProc(definedIoProcMap); |
| 325 |
mlir::Value listAddr = |
| 326 |
tableIsLocal ? builder.create<fir::AllocaOp>(loc, listTy) : mlir::Value{}; |
| 327 |
std::string listMangleName = tableMangleName + ".list"; |
| 328 |
auto listFunc = [&](fir::FirOpBuilder &builder) { |
| 329 |
mlir::Value list = builder.create<fir::UndefOp>(loc, listTy); |
| 330 |
mlir::IntegerAttr intAttr[4]; |
| 331 |
for (int i = 0; i < 4; ++i) |
| 332 |
intAttr[i] = builder.getIntegerAttr(idxTy, i); |
| 333 |
llvm::SmallVector<mlir::Attribute, 2> idx = {mlir::Attribute{}, |
| 334 |
mlir::Attribute{}}; |
| 335 |
int n0 = 0, n1; |
| 336 |
auto insert = [&](mlir::Value val) { |
| 337 |
idx[1] = intAttr[n1++]; |
| 338 |
list = builder.create<fir::InsertValueOp>(loc, listTy, list, val, |
| 339 |
builder.getArrayAttr(idx)); |
| 340 |
}; |
| 341 |
for (auto &iface : definedIoProcMap) { |
| 342 |
idx[0] = builder.getIntegerAttr(idxTy, n0++); |
| 343 |
n1 = 0; |
| 344 |
// derived type description [const typeInfo::DerivedType &derivedType] |
| 345 |
const Fortran::semantics::Symbol &dtSym = iface.first->GetUltimate(); |
| 346 |
std::string dtName = converter.mangleName(dtSym); |
| 347 |
insert(builder.createConvert( |
| 348 |
loc, refTy, |
| 349 |
builder.create<fir::AddrOfOp>( |
| 350 |
loc, fir::ReferenceType::get(converter.genType(dtSym)), |
| 351 |
builder.getSymbolRefAttr(dtName)))); |
| 352 |
// defined IO procedure [void (*subroutine)()], may be null |
| 353 |
const Fortran::semantics::Symbol *procSym = iface.second.subroutine; |
| 354 |
if (procSym) { |
| 355 |
procSym = &procSym->GetUltimate(); |
| 356 |
if (Fortran::semantics::IsProcedurePointer(*procSym)) { |
| 357 |
TODO(loc, "defined IO procedure pointers"); |
| 358 |
} else if (Fortran::semantics::IsDummy(*procSym)) { |
| 359 |
Fortran::lower::StatementContext stmtCtx; |
| 360 |
insert(builder.create<fir::BoxAddrOp>( |
| 361 |
loc, refTy, |
| 362 |
fir::getBase(converter.genExprAddr( |
| 363 |
loc, |
| 364 |
Fortran::lower::SomeExpr{ |
| 365 |
Fortran::evaluate::ProcedureDesignator{*procSym}}, |
| 366 |
stmtCtx)))); |
| 367 |
} else { |
| 368 |
mlir::func::FuncOp procDef = Fortran::lower::getOrDeclareFunction( |
| 369 |
Fortran::evaluate::ProcedureDesignator{*procSym}, converter); |
| 370 |
mlir::SymbolRefAttr nameAttr = |
| 371 |
builder.getSymbolRefAttr(procDef.getSymName()); |
| 372 |
insert(builder.createConvert( |
| 373 |
loc, refTy, |
| 374 |
builder.create<fir::AddrOfOp>(loc, procDef.getFunctionType(), |
| 375 |
nameAttr))); |
| 376 |
} |
| 377 |
} else { |
| 378 |
insert(builder.createNullConstant(loc, refTy)); |
| 379 |
} |
| 380 |
// defined IO variant, one of (read/write, formatted/unformatted) |
| 381 |
// [common::DefinedIo definedIo] |
| 382 |
insert(builder.createIntegerConstant( |
| 383 |
loc, intTy, static_cast<int>(iface.second.definedIo))); |
| 384 |
// polymorphic flag is set if first defined IO dummy arg is CLASS(T) |
| 385 |
// [bool isDtvArgPolymorphic] |
| 386 |
insert(builder.createIntegerConstant(loc, boolTy, |
| 387 |
iface.second.isDtvArgPolymorphic)); |
| 388 |
} |
| 389 |
if (tableIsLocal) |
| 390 |
builder.create<fir::StoreOp>(loc, list, listAddr); |
| 391 |
else |
| 392 |
builder.create<fir::HasValueOp>(loc, list); |
| 393 |
}; |
| 394 |
if (!definedIoProcMap.empty()) { |
| 395 |
if (tableIsLocal) |
| 396 |
listFunc(builder); |
| 397 |
else |
| 398 |
builder.createGlobalConstant(loc, listTy, listMangleName, listFunc, |
| 399 |
linkOnce); |
| 400 |
} |
| 401 |
|
| 402 |
// Define the NonTbpDefinedIoTable. |
| 403 |
mlir::Value tableAddr = tableIsLocal |
| 404 |
? builder.create<fir::AllocaOp>(loc, tableTy) |
| 405 |
: mlir::Value{}; |
| 406 |
auto tableFunc = [&](fir::FirOpBuilder &builder) { |
| 407 |
mlir::Value table = builder.create<fir::UndefOp>(loc, tableTy); |
| 408 |
// list item count [std::size_t items] |
| 409 |
table = builder.create<fir::InsertValueOp>( |
| 410 |
loc, tableTy, table, |
| 411 |
builder.createIntegerConstant(loc, sizeTy, definedIoProcMap.size()), |
| 412 |
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 0))); |
| 413 |
// item list [const NonTbpDefinedIo *item] |
| 414 |
if (definedIoProcMap.empty()) |
| 415 |
listAddr = builder.createNullConstant(loc, builder.getRefType(listTy)); |
| 416 |
else if (fir::GlobalOp list = builder.getNamedGlobal(listMangleName)) |
| 417 |
listAddr = builder.create<fir::AddrOfOp>(loc, list.resultType(), |
| 418 |
list.getSymbol()); |
| 419 |
assert(listAddr && "missing namelist object list"); |
| 420 |
table = builder.create<fir::InsertValueOp>( |
| 421 |
loc, tableTy, table, listAddr, |
| 422 |
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 1))); |
| 423 |
// [bool ignoreNonTbpEntries] conservatively set to true |
| 424 |
table = builder.create<fir::InsertValueOp>( |
| 425 |
loc, tableTy, table, builder.createIntegerConstant(loc, boolTy, true), |
| 426 |
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 2))); |
| 427 |
if (tableIsLocal) |
| 428 |
builder.create<fir::StoreOp>(loc, table, tableAddr); |
| 429 |
else |
| 430 |
builder.create<fir::HasValueOp>(loc, table); |
| 431 |
}; |
| 432 |
if (tableIsLocal) { |
| 433 |
tableFunc(builder); |
| 434 |
} else { |
| 435 |
fir::GlobalOp table = builder.createGlobal( |
| 436 |
loc, tableTy, tableMangleName, |
| 437 |
/*isConst=*/true, /*isTarget=*/false, tableFunc, linkOnce); |
| 438 |
tableAddr = builder.create<fir::AddrOfOp>( |
| 439 |
loc, fir::ReferenceType::get(tableTy), table.getSymbol()); |
| 440 |
} |
| 441 |
assert(tableAddr && "missing NonTbpDefinedIo table result"); |
| 442 |
return builder.createConvert(loc, refTy, tableAddr); |
| 443 |
} |
| 444 |
|
| 445 |
static mlir::Value |
| 446 |
getNonTbpDefinedIoTableAddr(Fortran::lower::AbstractConverter &converter) { |
| 447 |
DefinedIoProcMap definedIoProcMap = getDefinedIoProcMap(converter); |
| 448 |
return getNonTbpDefinedIoTableAddr(converter, definedIoProcMap); |
| 449 |
} |
| 450 |
|
| 451 |
/// Retrieve or generate a runtime description of NAMELIST group \p symbol. |
| 452 |
/// The form of the description is defined in runtime header file namelist.h. |
| 453 |
/// Static descriptors are generated for global objects; local descriptors for |
| 454 |
/// local objects. If all descriptors and defined IO procedures are static, |
| 455 |
/// the NamelistGroup is static. |
| 456 |
static mlir::Value |
| 457 |
getNamelistGroup(Fortran::lower::AbstractConverter &converter, |
| 458 |
const Fortran::semantics::Symbol &symbol, |
| 459 |
Fortran::lower::StatementContext &stmtCtx) { |
| 460 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 461 |
mlir::Location loc = converter.getCurrentLocation(); |
| 462 |
std::string groupMangleName = converter.mangleName(symbol); |
| 463 |
if (auto group = builder.getNamedGlobal(groupMangleName)) |
| 464 |
return builder.create<fir::AddrOfOp>(loc, group.resultType(), |
| 465 |
group.getSymbol()); |
| 466 |
|
| 467 |
const auto &details = |
| 468 |
symbol.GetUltimate().get<Fortran::semantics::NamelistDetails>(); |
| 469 |
mlir::MLIRContext *context = builder.getContext(); |
| 470 |
mlir::StringAttr linkOnce = builder.createLinkOnceLinkage(); |
| 471 |
mlir::Type idxTy = builder.getIndexType(); |
| 472 |
mlir::Type sizeTy = |
| 473 |
fir::runtime::getModel<std::size_t>()(builder.getContext()); |
| 474 |
mlir::Type charRefTy = fir::ReferenceType::get(builder.getIntegerType(8)); |
| 475 |
mlir::Type descRefTy = |
| 476 |
fir::ReferenceType::get(fir::BoxType::get(mlir::NoneType::get(context))); |
| 477 |
mlir::Type listTy = fir::SequenceType::get( |
| 478 |
details.objects().size(), |
| 479 |
mlir::TupleType::get(context, {charRefTy, descRefTy})); |
| 480 |
mlir::Type groupTy = mlir::TupleType::get( |
| 481 |
context, {charRefTy, sizeTy, fir::ReferenceType::get(listTy), |
| 482 |
fir::ReferenceType::get(mlir::NoneType::get(context))}); |
| 483 |
auto stringAddress = [&](const Fortran::semantics::Symbol &symbol) { |
| 484 |
return fir::factory::createStringLiteral(builder, loc, |
| 485 |
symbol.name().ToString() + '\0'); |
| 486 |
}; |
| 487 |
|
| 488 |
// Define variable names, and static descriptors for global variables. |
| 489 |
DefinedIoProcMap definedIoProcMap = getDefinedIoProcMap(converter); |
| 490 |
bool groupIsLocal = hasLocalDefinedIoProc(definedIoProcMap); |
| 491 |
stringAddress(symbol); |
| 492 |
for (const Fortran::semantics::Symbol &s : details.objects()) { |
| 493 |
stringAddress(s); |
| 494 |
if (!Fortran::lower::symbolIsGlobal(s)) { |
| 495 |
groupIsLocal = true; |
| 496 |
continue; |
| 497 |
} |
| 498 |
// A global pointer or allocatable variable has a descriptor for typical |
| 499 |
// accesses. Variables in multiple namelist groups may already have one. |
| 500 |
// Create descriptors for other cases. |
| 501 |
if (!IsAllocatableOrObjectPointer(&s)) { |
| 502 |
std::string mangleName = |
| 503 |
Fortran::lower::mangle::globalNamelistDescriptorName(s); |
| 504 |
if (builder.getNamedGlobal(mangleName)) |
| 505 |
continue; |
| 506 |
const auto expr = Fortran::evaluate::AsGenericExpr(s); |
| 507 |
fir::BoxType boxTy = |
| 508 |
fir::BoxType::get(fir::PointerType::get(converter.genType(s))); |
| 509 |
auto descFunc = [&](fir::FirOpBuilder &b) { |
| 510 |
auto box = Fortran::lower::genInitialDataTarget( |
| 511 |
converter, loc, boxTy, *expr, /*couldBeInEquivalence=*/true); |
| 512 |
b.create<fir::HasValueOp>(loc, box); |
| 513 |
}; |
| 514 |
builder.createGlobalConstant(loc, boxTy, mangleName, descFunc, linkOnce); |
| 515 |
} |
| 516 |
} |
| 517 |
|
| 518 |
// Define the list of Items. |
| 519 |
mlir::Value listAddr = |
| 520 |
groupIsLocal ? builder.create<fir::AllocaOp>(loc, listTy) : mlir::Value{}; |
| 521 |
std::string listMangleName = groupMangleName + ".list"; |
| 522 |
auto listFunc = [&](fir::FirOpBuilder &builder) { |
| 523 |
mlir::Value list = builder.create<fir::UndefOp>(loc, listTy); |
| 524 |
mlir::IntegerAttr zero = builder.getIntegerAttr(idxTy, 0); |
| 525 |
mlir::IntegerAttr one = builder.getIntegerAttr(idxTy, 1); |
| 526 |
llvm::SmallVector<mlir::Attribute, 2> idx = {mlir::Attribute{}, |
| 527 |
mlir::Attribute{}}; |
| 528 |
int n = 0; |
| 529 |
for (const Fortran::semantics::Symbol &s : details.objects()) { |
| 530 |
idx[0] = builder.getIntegerAttr(idxTy, n++); |
| 531 |
idx[1] = zero; |
| 532 |
mlir::Value nameAddr = |
| 533 |
builder.createConvert(loc, charRefTy, fir::getBase(stringAddress(s))); |
| 534 |
list = builder.create<fir::InsertValueOp>(loc, listTy, list, nameAddr, |
| 535 |
builder.getArrayAttr(idx)); |
| 536 |
idx[1] = one; |
| 537 |
mlir::Value descAddr; |
| 538 |
if (auto desc = builder.getNamedGlobal( |
| 539 |
Fortran::lower::mangle::globalNamelistDescriptorName(s))) { |
| 540 |
descAddr = builder.create<fir::AddrOfOp>(loc, desc.resultType(), |
| 541 |
desc.getSymbol()); |
| 542 |
} else if (Fortran::semantics::FindCommonBlockContaining(s) && |
| 543 |
IsAllocatableOrPointer(s)) { |
| 544 |
mlir::Type symType = converter.genType(s); |
| 545 |
const Fortran::semantics::Symbol *commonBlockSym = |
| 546 |
Fortran::semantics::FindCommonBlockContaining(s); |
| 547 |
std::string commonBlockName = converter.mangleName(*commonBlockSym); |
| 548 |
fir::GlobalOp commonGlobal = builder.getNamedGlobal(commonBlockName); |
| 549 |
mlir::Value commonBlockAddr = builder.create<fir::AddrOfOp>( |
| 550 |
loc, commonGlobal.resultType(), commonGlobal.getSymbol()); |
| 551 |
mlir::IntegerType i8Ty = builder.getIntegerType(8); |
| 552 |
mlir::Type i8Ptr = builder.getRefType(i8Ty); |
| 553 |
mlir::Type seqTy = builder.getRefType(builder.getVarLenSeqTy(i8Ty)); |
| 554 |
mlir::Value base = builder.createConvert(loc, seqTy, commonBlockAddr); |
| 555 |
std::size_t byteOffset = s.GetUltimate().offset(); |
| 556 |
mlir::Value offs = builder.createIntegerConstant( |
| 557 |
loc, builder.getIndexType(), byteOffset); |
| 558 |
mlir::Value varAddr = builder.create<fir::CoordinateOp>( |
| 559 |
loc, i8Ptr, base, mlir::ValueRange{offs}); |
| 560 |
descAddr = |
| 561 |
builder.createConvert(loc, builder.getRefType(symType), varAddr); |
| 562 |
} else { |
| 563 |
const auto expr = Fortran::evaluate::AsGenericExpr(s); |
| 564 |
fir::ExtendedValue exv = converter.genExprAddr(*expr, stmtCtx); |
| 565 |
mlir::Type type = fir::getBase(exv).getType(); |
| 566 |
if (mlir::Type baseTy = fir::dyn_cast_ptrOrBoxEleTy(type)) |
| 567 |
type = baseTy; |
| 568 |
fir::BoxType boxType = fir::BoxType::get(fir::PointerType::get(type)); |
| 569 |
descAddr = builder.createTemporary(loc, boxType); |
| 570 |
fir::MutableBoxValue box = fir::MutableBoxValue(descAddr, {}, {}); |
| 571 |
fir::factory::associateMutableBox(builder, loc, box, exv, |
| 572 |
/*lbounds=*/std::nullopt); |
| 573 |
} |
| 574 |
descAddr = builder.createConvert(loc, descRefTy, descAddr); |
| 575 |
list = builder.create<fir::InsertValueOp>(loc, listTy, list, descAddr, |
| 576 |
builder.getArrayAttr(idx)); |
| 577 |
} |
| 578 |
if (groupIsLocal) |
| 579 |
builder.create<fir::StoreOp>(loc, list, listAddr); |
| 580 |
else |
| 581 |
builder.create<fir::HasValueOp>(loc, list); |
| 582 |
}; |
| 583 |
if (groupIsLocal) |
| 584 |
listFunc(builder); |
| 585 |
else |
| 586 |
builder.createGlobalConstant(loc, listTy, listMangleName, listFunc, |
| 587 |
linkOnce); |
| 588 |
|
| 589 |
// Define the group. |
| 590 |
mlir::Value groupAddr = groupIsLocal |
| 591 |
? builder.create<fir::AllocaOp>(loc, groupTy) |
| 592 |
: mlir::Value{}; |
| 593 |
auto groupFunc = [&](fir::FirOpBuilder &builder) { |
| 594 |
mlir::Value group = builder.create<fir::UndefOp>(loc, groupTy); |
| 595 |
// group name [const char *groupName] |
| 596 |
group = builder.create<fir::InsertValueOp>( |
| 597 |
loc, groupTy, group, |
| 598 |
builder.createConvert(loc, charRefTy, |
| 599 |
fir::getBase(stringAddress(symbol))), |
| 600 |
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 0))); |
| 601 |
// list item count [std::size_t items] |
| 602 |
group = builder.create<fir::InsertValueOp>( |
| 603 |
loc, groupTy, group, |
| 604 |
builder.createIntegerConstant(loc, sizeTy, details.objects().size()), |
| 605 |
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 1))); |
| 606 |
// item list [const Item *item] |
| 607 |
if (fir::GlobalOp list = builder.getNamedGlobal(listMangleName)) |
| 608 |
listAddr = builder.create<fir::AddrOfOp>(loc, list.resultType(), |
| 609 |
list.getSymbol()); |
| 610 |
assert(listAddr && "missing namelist object list"); |
| 611 |
group = builder.create<fir::InsertValueOp>( |
| 612 |
loc, groupTy, group, listAddr, |
| 613 |
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 2))); |
| 614 |
// non-type-bound defined IO procedures |
| 615 |
// [const NonTbpDefinedIoTable *nonTbpDefinedIo] |
| 616 |
group = builder.create<fir::InsertValueOp>( |
| 617 |
loc, groupTy, group, |
| 618 |
getNonTbpDefinedIoTableAddr(converter, definedIoProcMap), |
| 619 |
builder.getArrayAttr(builder.getIntegerAttr(idxTy, 3))); |
| 620 |
if (groupIsLocal) |
| 621 |
builder.create<fir::StoreOp>(loc, group, groupAddr); |
| 622 |
else |
| 623 |
builder.create<fir::HasValueOp>(loc, group); |
| 624 |
}; |
| 625 |
if (groupIsLocal) { |
| 626 |
groupFunc(builder); |
| 627 |
} else { |
| 628 |
fir::GlobalOp group = builder.createGlobal( |
| 629 |
loc, groupTy, groupMangleName, |
| 630 |
/*isConst=*/true, /*isTarget=*/false, groupFunc, linkOnce); |
| 631 |
groupAddr = builder.create<fir::AddrOfOp>(loc, group.resultType(), |
| 632 |
group.getSymbol()); |
| 633 |
} |
| 634 |
assert(groupAddr && "missing namelist group result"); |
| 635 |
return groupAddr; |
| 636 |
} |
| 637 |
|
| 638 |
/// Generate a namelist IO call. |
| 639 |
static void genNamelistIO(Fortran::lower::AbstractConverter &converter, |
| 640 |
mlir::Value cookie, mlir::func::FuncOp funcOp, |
| 641 |
Fortran::semantics::Symbol &symbol, bool checkResult, |
| 642 |
mlir::Value &ok, |
| 643 |
Fortran::lower::StatementContext &stmtCtx) { |
| 644 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 645 |
mlir::Location loc = converter.getCurrentLocation(); |
| 646 |
makeNextConditionalOn(builder, loc, checkResult, ok); |
| 647 |
mlir::Type argType = funcOp.getFunctionType().getInput(1); |
| 648 |
mlir::Value groupAddr = |
| 649 |
getNamelistGroup(converter, symbol.GetUltimate(), stmtCtx); |
| 650 |
groupAddr = builder.createConvert(loc, argType, groupAddr); |
| 651 |
llvm::SmallVector<mlir::Value> args = {cookie, groupAddr}; |
| 652 |
ok = builder.create<fir::CallOp>(loc, funcOp, args).getResult(0); |
| 653 |
} |
| 654 |
|
| 655 |
/// Get the output function to call for a value of the given type. |
| 656 |
static mlir::func::FuncOp getOutputFunc(mlir::Location loc, |
| 657 |
fir::FirOpBuilder &builder, |
| 658 |
mlir::Type type, bool isFormatted) { |
| 659 |
if (mlir::isa<fir::RecordType>(fir::unwrapPassByRefType(type))) |
| 660 |
return getIORuntimeFunc<mkIOKey(OutputDerivedType)>(loc, builder); |
| 661 |
if (!isFormatted) |
| 662 |
return getIORuntimeFunc<mkIOKey(OutputDescriptor)>(loc, builder); |
| 663 |
if (auto ty = mlir::dyn_cast<mlir::IntegerType>(type)) { |
| 664 |
switch (ty.getWidth()) { |
| 665 |
case 1: |
| 666 |
return getIORuntimeFunc<mkIOKey(OutputLogical)>(loc, builder); |
| 667 |
case 8: |
| 668 |
return getIORuntimeFunc<mkIOKey(OutputInteger8)>(loc, builder); |
| 669 |
case 16: |
| 670 |
return getIORuntimeFunc<mkIOKey(OutputInteger16)>(loc, builder); |
| 671 |
case 32: |
| 672 |
return getIORuntimeFunc<mkIOKey(OutputInteger32)>(loc, builder); |
| 673 |
case 64: |
| 674 |
return getIORuntimeFunc<mkIOKey(OutputInteger64)>(loc, builder); |
| 675 |
case 128: |
| 676 |
return getIORuntimeFunc<mkIOKey(OutputInteger128)>(loc, builder); |
| 677 |
} |
| 678 |
llvm_unreachable("unknown OutputInteger kind"); |
| 679 |
} |
| 680 |
if (auto ty = mlir::dyn_cast<mlir::FloatType>(type)) { |
| 681 |
if (auto width = ty.getWidth(); width == 32) |
| 682 |
return getIORuntimeFunc<mkIOKey(OutputReal32)>(loc, builder); |
| 683 |
else if (width == 64) |
| 684 |
return getIORuntimeFunc<mkIOKey(OutputReal64)>(loc, builder); |
| 685 |
} |
| 686 |
auto kindMap = fir::getKindMapping(builder.getModule()); |
| 687 |
if (auto ty = mlir::dyn_cast<fir::ComplexType>(type)) { |
| 688 |
// COMPLEX(KIND=k) corresponds to a pair of REAL(KIND=k). |
| 689 |
auto width = kindMap.getRealBitsize(ty.getFKind()); |
| 690 |
if (width == 32) |
| 691 |
return getIORuntimeFunc<mkIOKey(OutputComplex32)>(loc, builder); |
| 692 |
else if (width == 64) |
| 693 |
return getIORuntimeFunc<mkIOKey(OutputComplex64)>(loc, builder); |
| 694 |
} |
| 695 |
if (mlir::isa<fir::LogicalType>(type)) |
| 696 |
return getIORuntimeFunc<mkIOKey(OutputLogical)>(loc, builder); |
| 697 |
if (fir::factory::CharacterExprHelper::isCharacterScalar(type)) { |
| 698 |
// TODO: What would it mean if the default CHARACTER KIND is set to a wide |
| 699 |
// character encoding scheme? How do we handle UTF-8? Is it a distinct KIND |
| 700 |
// value? For now, assume that if the default CHARACTER KIND is 8 bit, |
| 701 |
// then it is an ASCII string and UTF-8 is unsupported. |
| 702 |
auto asciiKind = kindMap.defaultCharacterKind(); |
| 703 |
if (kindMap.getCharacterBitsize(asciiKind) == 8 && |
| 704 |
fir::factory::CharacterExprHelper::getCharacterKind(type) == asciiKind) |
| 705 |
return getIORuntimeFunc<mkIOKey(OutputAscii)>(loc, builder); |
| 706 |
} |
| 707 |
return getIORuntimeFunc<mkIOKey(OutputDescriptor)>(loc, builder); |
| 708 |
} |
| 709 |
|
| 710 |
/// Generate a sequence of output data transfer calls. |
| 711 |
static void genOutputItemList( |
| 712 |
Fortran::lower::AbstractConverter &converter, mlir::Value cookie, |
| 713 |
const std::list<Fortran::parser::OutputItem> &items, bool isFormatted, |
| 714 |
bool checkResult, mlir::Value &ok, bool inLoop) { |
| 715 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 716 |
for (const Fortran::parser::OutputItem &item : items) { |
| 717 |
if (const auto &impliedDo = std::get_if<1>(&item.u)) { |
| 718 |
genIoLoop(converter, cookie, impliedDo->value(), isFormatted, checkResult, |
| 719 |
ok, inLoop); |
| 720 |
continue; |
| 721 |
} |
| 722 |
auto &pExpr = std::get<Fortran::parser::Expr>(item.u); |
| 723 |
mlir::Location loc = converter.genLocation(pExpr.source); |
| 724 |
makeNextConditionalOn(builder, loc, checkResult, ok, inLoop); |
| 725 |
Fortran::lower::StatementContext stmtCtx; |
| 726 |
|
| 727 |
const auto *expr = Fortran::semantics::GetExpr(pExpr); |
| 728 |
if (!expr) |
| 729 |
fir::emitFatalError(loc, "internal error: could not get evaluate::Expr"); |
| 730 |
mlir::Type itemTy = converter.genType(*expr); |
| 731 |
mlir::func::FuncOp outputFunc = |
| 732 |
getOutputFunc(loc, builder, itemTy, isFormatted); |
| 733 |
mlir::Type argType = outputFunc.getFunctionType().getInput(1); |
| 734 |
assert((isFormatted || mlir::isa<fir::BoxType>(argType)) && |
| 735 |
"expect descriptor for unformatted IO runtime"); |
| 736 |
llvm::SmallVector<mlir::Value> outputFuncArgs = {cookie}; |
| 737 |
fir::factory::CharacterExprHelper helper{builder, loc}; |
| 738 |
if (mlir::isa<fir::BoxType>(argType)) { |
| 739 |
mlir::Value box = fir::getBase(converter.genExprBox(loc, *expr, stmtCtx)); |
| 740 |
outputFuncArgs.push_back(builder.createConvert(loc, argType, box)); |
| 741 |
if (mlir::isa<fir::RecordType>(fir::unwrapPassByRefType(itemTy))) |
| 742 |
outputFuncArgs.push_back(getNonTbpDefinedIoTableAddr(converter)); |
| 743 |
} else if (helper.isCharacterScalar(itemTy)) { |
| 744 |
fir::ExtendedValue exv = converter.genExprAddr(loc, expr, stmtCtx); |
| 745 |
// scalar allocatable/pointer may also get here, not clear if |
| 746 |
// genExprAddr will lower them as CharBoxValue or BoxValue. |
| 747 |
if (!exv.getCharBox()) |
| 748 |
llvm::report_fatal_error( |
| 749 |
"internal error: scalar character not in CharBox"); |
| 750 |
outputFuncArgs.push_back(builder.createConvert( |
| 751 |
loc, outputFunc.getFunctionType().getInput(1), fir::getBase(exv))); |
| 752 |
outputFuncArgs.push_back(builder.createConvert( |
| 753 |
loc, outputFunc.getFunctionType().getInput(2), fir::getLen(exv))); |
| 754 |
} else { |
| 755 |
fir::ExtendedValue itemBox = converter.genExprValue(loc, expr, stmtCtx); |
| 756 |
mlir::Value itemValue = fir::getBase(itemBox); |
| 757 |
if (fir::isa_complex(itemTy)) { |
| 758 |
auto parts = |
| 759 |
fir::factory::Complex{builder, loc}.extractParts(itemValue); |
| 760 |
outputFuncArgs.push_back(parts.first); |
| 761 |
outputFuncArgs.push_back(parts.second); |
| 762 |
} else { |
| 763 |
itemValue = builder.createConvert(loc, argType, itemValue); |
| 764 |
outputFuncArgs.push_back(itemValue); |
| 765 |
} |
| 766 |
} |
| 767 |
ok = builder.create<fir::CallOp>(loc, outputFunc, outputFuncArgs) |
| 768 |
.getResult(0); |
| 769 |
} |
| 770 |
} |
| 771 |
|
| 772 |
/// Get the input function to call for a value of the given type. |
| 773 |
static mlir::func::FuncOp getInputFunc(mlir::Location loc, |
| 774 |
fir::FirOpBuilder &builder, |
| 775 |
mlir::Type type, bool isFormatted) { |
| 776 |
if (mlir::isa<fir::RecordType>(fir::unwrapPassByRefType(type))) |
| 777 |
return getIORuntimeFunc<mkIOKey(InputDerivedType)>(loc, builder); |
| 778 |
if (!isFormatted) |
| 779 |
return getIORuntimeFunc<mkIOKey(InputDescriptor)>(loc, builder); |
| 780 |
if (auto ty = mlir::dyn_cast<mlir::IntegerType>(type)) |
| 781 |
return ty.getWidth() == 1 |
| 782 |
? getIORuntimeFunc<mkIOKey(InputLogical)>(loc, builder) |
| 783 |
: getIORuntimeFunc<mkIOKey(InputInteger)>(loc, builder); |
| 784 |
if (auto ty = mlir::dyn_cast<mlir::FloatType>(type)) { |
| 785 |
if (auto width = ty.getWidth(); width == 32) |
| 786 |
return getIORuntimeFunc<mkIOKey(InputReal32)>(loc, builder); |
| 787 |
else if (width == 64) |
| 788 |
return getIORuntimeFunc<mkIOKey(InputReal64)>(loc, builder); |
| 789 |
} |
| 790 |
auto kindMap = fir::getKindMapping(builder.getModule()); |
| 791 |
if (auto ty = mlir::dyn_cast<fir::ComplexType>(type)) { |
| 792 |
auto width = kindMap.getRealBitsize(ty.getFKind()); |
| 793 |
if (width == 32) |
| 794 |
return getIORuntimeFunc<mkIOKey(InputComplex32)>(loc, builder); |
| 795 |
else if (width == 64) |
| 796 |
return getIORuntimeFunc<mkIOKey(InputComplex64)>(loc, builder); |
| 797 |
} |
| 798 |
if (mlir::isa<fir::LogicalType>(type)) |
| 799 |
return getIORuntimeFunc<mkIOKey(InputLogical)>(loc, builder); |
| 800 |
if (fir::factory::CharacterExprHelper::isCharacterScalar(type)) { |
| 801 |
auto asciiKind = kindMap.defaultCharacterKind(); |
| 802 |
if (kindMap.getCharacterBitsize(asciiKind) == 8 && |
| 803 |
fir::factory::CharacterExprHelper::getCharacterKind(type) == asciiKind) |
| 804 |
return getIORuntimeFunc<mkIOKey(InputAscii)>(loc, builder); |
| 805 |
} |
| 806 |
return getIORuntimeFunc<mkIOKey(InputDescriptor)>(loc, builder); |
| 807 |
} |
| 808 |
|
| 809 |
/// Interpret the lowest byte of a LOGICAL and store that value into the full |
| 810 |
/// storage of the LOGICAL. The load, convert, and store effectively (sign or |
| 811 |
/// zero) extends the lowest byte into the full LOGICAL value storage, as the |
| 812 |
/// runtime is unaware of the LOGICAL value's actual bit width (it was passed |
| 813 |
/// as a `bool&` to the runtime in order to be set). |
| 814 |
static void boolRefToLogical(mlir::Location loc, fir::FirOpBuilder &builder, |
| 815 |
mlir::Value addr) { |
| 816 |
auto boolType = builder.getRefType(builder.getI1Type()); |
| 817 |
auto boolAddr = builder.createConvert(loc, boolType, addr); |
| 818 |
auto boolValue = builder.create<fir::LoadOp>(loc, boolAddr); |
| 819 |
auto logicalType = fir::unwrapPassByRefType(addr.getType()); |
| 820 |
// The convert avoid making any assumptions about how LOGICALs are actually |
| 821 |
// represented (it might end-up being either a signed or zero extension). |
| 822 |
auto logicalValue = builder.createConvert(loc, logicalType, boolValue); |
| 823 |
builder.create<fir::StoreOp>(loc, logicalValue, addr); |
| 824 |
} |
| 825 |
|
| 826 |
static mlir::Value |
| 827 |
createIoRuntimeCallForItem(Fortran::lower::AbstractConverter &converter, |
| 828 |
mlir::Location loc, mlir::func::FuncOp inputFunc, |
| 829 |
mlir::Value cookie, const fir::ExtendedValue &item) { |
| 830 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 831 |
mlir::Type argType = inputFunc.getFunctionType().getInput(1); |
| 832 |
llvm::SmallVector<mlir::Value> inputFuncArgs = {cookie}; |
| 833 |
if (mlir::isa<fir::BaseBoxType>(argType)) { |
| 834 |
mlir::Value box = fir::getBase(item); |
| 835 |
auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(box.getType()); |
| 836 |
assert(boxTy && "must be previously emboxed"); |
| 837 |
inputFuncArgs.push_back(builder.createConvert(loc, argType, box)); |
| 838 |
if (mlir::isa<fir::RecordType>(fir::unwrapPassByRefType(boxTy))) |
| 839 |
inputFuncArgs.push_back(getNonTbpDefinedIoTableAddr(converter)); |
| 840 |
} else { |
| 841 |
mlir::Value itemAddr = fir::getBase(item); |
| 842 |
mlir::Type itemTy = fir::unwrapPassByRefType(itemAddr.getType()); |
| 843 |
inputFuncArgs.push_back(builder.createConvert(loc, argType, itemAddr)); |
| 844 |
fir::factory::CharacterExprHelper charHelper{builder, loc}; |
| 845 |
if (charHelper.isCharacterScalar(itemTy)) { |
| 846 |
mlir::Value len = fir::getLen(item); |
| 847 |
inputFuncArgs.push_back(builder.createConvert( |
| 848 |
loc, inputFunc.getFunctionType().getInput(2), len)); |
| 849 |
} else if (mlir::isa<mlir::IntegerType>(itemTy)) { |
| 850 |
inputFuncArgs.push_back(builder.create<mlir::arith::ConstantOp>( |
| 851 |
loc, builder.getI32IntegerAttr( |
| 852 |
mlir::cast<mlir::IntegerType>(itemTy).getWidth() / 8))); |
| 853 |
} |
| 854 |
} |
| 855 |
auto call = builder.create<fir::CallOp>(loc, inputFunc, inputFuncArgs); |
| 856 |
auto itemAddr = fir::getBase(item); |
| 857 |
auto itemTy = fir::unwrapRefType(itemAddr.getType()); |
| 858 |
if (mlir::isa<fir::LogicalType>(itemTy)) |
| 859 |
boolRefToLogical(loc, builder, itemAddr); |
| 860 |
return call.getResult(0); |
| 861 |
} |
| 862 |
|
| 863 |
/// Generate a sequence of input data transfer calls. |
| 864 |
static void genInputItemList(Fortran::lower::AbstractConverter &converter, |
| 865 |
mlir::Value cookie, |
| 866 |
const std::list<Fortran::parser::InputItem> &items, |
| 867 |
bool isFormatted, bool checkResult, |
| 868 |
mlir::Value &ok, bool inLoop) { |
| 869 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 870 |
for (const Fortran::parser::InputItem &item : items) { |
| 871 |
if (const auto &impliedDo = std::get_if<1>(&item.u)) { |
| 872 |
genIoLoop(converter, cookie, impliedDo->value(), isFormatted, checkResult, |
| 873 |
ok, inLoop); |
| 874 |
continue; |
| 875 |
} |
| 876 |
auto &pVar = std::get<Fortran::parser::Variable>(item.u); |
| 877 |
mlir::Location loc = converter.genLocation(pVar.GetSource()); |
| 878 |
makeNextConditionalOn(builder, loc, checkResult, ok, inLoop); |
| 879 |
Fortran::lower::StatementContext stmtCtx; |
| 880 |
const auto *expr = Fortran::semantics::GetExpr(pVar); |
| 881 |
if (!expr) |
| 882 |
fir::emitFatalError(loc, "internal error: could not get evaluate::Expr"); |
| 883 |
if (Fortran::evaluate::HasVectorSubscript(*expr)) { |
| 884 |
auto vectorSubscriptBox = |
| 885 |
Fortran::lower::genVectorSubscriptBox(loc, converter, stmtCtx, *expr); |
| 886 |
mlir::func::FuncOp inputFunc = getInputFunc( |
| 887 |
loc, builder, vectorSubscriptBox.getElementType(), isFormatted); |
| 888 |
const bool mustBox = |
| 889 |
mlir::isa<fir::BoxType>(inputFunc.getFunctionType().getInput(1)); |
| 890 |
if (!checkResult) { |
| 891 |
auto elementalGenerator = [&](const fir::ExtendedValue &element) { |
| 892 |
createIoRuntimeCallForItem(converter, loc, inputFunc, cookie, |
| 893 |
mustBox ? builder.createBox(loc, element) |
| 894 |
: element); |
| 895 |
}; |
| 896 |
vectorSubscriptBox.loopOverElements(builder, loc, elementalGenerator); |
| 897 |
} else { |
| 898 |
auto elementalGenerator = |
| 899 |
[&](const fir::ExtendedValue &element) -> mlir::Value { |
| 900 |
return createIoRuntimeCallForItem( |
| 901 |
converter, loc, inputFunc, cookie, |
| 902 |
mustBox ? builder.createBox(loc, element) : element); |
| 903 |
}; |
| 904 |
if (!ok) |
| 905 |
ok = builder.createBool(loc, true); |
| 906 |
ok = vectorSubscriptBox.loopOverElementsWhile(builder, loc, |
| 907 |
elementalGenerator, ok); |
| 908 |
} |
| 909 |
continue; |
| 910 |
} |
| 911 |
mlir::Type itemTy = converter.genType(*expr); |
| 912 |
mlir::func::FuncOp inputFunc = |
| 913 |
getInputFunc(loc, builder, itemTy, isFormatted); |
| 914 |
auto itemExv = |
| 915 |
mlir::isa<fir::BoxType>(inputFunc.getFunctionType().getInput(1)) |
| 916 |
? converter.genExprBox(loc, *expr, stmtCtx) |
| 917 |
: converter.genExprAddr(loc, expr, stmtCtx); |
| 918 |
ok = createIoRuntimeCallForItem(converter, loc, inputFunc, cookie, itemExv); |
| 919 |
} |
| 920 |
} |
| 921 |
|
| 922 |
/// Generate an io-implied-do loop. |
| 923 |
template <typename D> |
| 924 |
static void genIoLoop(Fortran::lower::AbstractConverter &converter, |
| 925 |
mlir::Value cookie, const D &ioImpliedDo, |
| 926 |
bool isFormatted, bool checkResult, mlir::Value &ok, |
| 927 |
bool inLoop) { |
| 928 |
Fortran::lower::StatementContext stmtCtx; |
| 929 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 930 |
mlir::Location loc = converter.getCurrentLocation(); |
| 931 |
mlir::arith::IntegerOverflowFlags flags{}; |
| 932 |
if (converter.getLoweringOptions().getNSWOnLoopVarInc()) |
| 933 |
flags = bitEnumSet(flags, mlir::arith::IntegerOverflowFlags::nsw); |
| 934 |
auto iofAttr = |
| 935 |
mlir::arith::IntegerOverflowFlagsAttr::get(builder.getContext(), flags); |
| 936 |
makeNextConditionalOn(builder, loc, checkResult, ok, inLoop); |
| 937 |
const auto &itemList = std::get<0>(ioImpliedDo.t); |
| 938 |
const auto &control = std::get<1>(ioImpliedDo.t); |
| 939 |
const auto &loopSym = *control.name.thing.thing.symbol; |
| 940 |
mlir::Value loopVar = fir::getBase(converter.genExprAddr( |
| 941 |
Fortran::evaluate::AsGenericExpr(loopSym).value(), stmtCtx)); |
| 942 |
auto genControlValue = [&](const Fortran::parser::ScalarIntExpr &expr) { |
| 943 |
mlir::Value v = fir::getBase( |
| 944 |
converter.genExprValue(*Fortran::semantics::GetExpr(expr), stmtCtx)); |
| 945 |
return builder.createConvert(loc, builder.getIndexType(), v); |
| 946 |
}; |
| 947 |
mlir::Value lowerValue = genControlValue(control.lower); |
| 948 |
mlir::Value upperValue = genControlValue(control.upper); |
| 949 |
mlir::Value stepValue = |
| 950 |
control.step.has_value() |
| 951 |
? genControlValue(*control.step) |
| 952 |
: builder.create<mlir::arith::ConstantIndexOp>(loc, 1); |
| 953 |
auto genItemList = [&](const D &ioImpliedDo) { |
| 954 |
if constexpr (std::is_same_v<D, Fortran::parser::InputImpliedDo>) |
| 955 |
genInputItemList(converter, cookie, itemList, isFormatted, checkResult, |
| 956 |
ok, /*inLoop=*/true); |
| 957 |
else |
| 958 |
genOutputItemList(converter, cookie, itemList, isFormatted, checkResult, |
| 959 |
ok, /*inLoop=*/true); |
| 960 |
}; |
| 961 |
if (!checkResult) { |
| 962 |
// No IO call result checks - the loop is a fir.do_loop op. |
| 963 |
auto doLoopOp = builder.create<fir::DoLoopOp>( |
| 964 |
loc, lowerValue, upperValue, stepValue, /*unordered=*/false, |
| 965 |
/*finalCountValue=*/true); |
| 966 |
builder.setInsertionPointToStart(doLoopOp.getBody()); |
| 967 |
mlir::Value lcv = builder.createConvert( |
| 968 |
loc, fir::unwrapRefType(loopVar.getType()), doLoopOp.getInductionVar()); |
| 969 |
builder.create<fir::StoreOp>(loc, lcv, loopVar); |
| 970 |
genItemList(ioImpliedDo); |
| 971 |
builder.setInsertionPointToEnd(doLoopOp.getBody()); |
| 972 |
mlir::Value result = builder.create<mlir::arith::AddIOp>( |
| 973 |
loc, doLoopOp.getInductionVar(), doLoopOp.getStep(), iofAttr); |
| 974 |
builder.create<fir::ResultOp>(loc, result); |
| 975 |
builder.setInsertionPointAfter(doLoopOp); |
| 976 |
// The loop control variable may be used after the loop. |
| 977 |
lcv = builder.createConvert(loc, fir::unwrapRefType(loopVar.getType()), |
| 978 |
doLoopOp.getResult(0)); |
| 979 |
builder.create<fir::StoreOp>(loc, lcv, loopVar); |
| 980 |
return; |
| 981 |
} |
| 982 |
// Check IO call results - the loop is a fir.iterate_while op. |
| 983 |
if (!ok) |
| 984 |
ok = builder.createBool(loc, true); |
| 985 |
auto iterWhileOp = builder.create<fir::IterWhileOp>( |
| 986 |
loc, lowerValue, upperValue, stepValue, ok, /*finalCountValue*/ true); |
| 987 |
builder.setInsertionPointToStart(iterWhileOp.getBody()); |
| 988 |
mlir::Value lcv = |
| 989 |
builder.createConvert(loc, fir::unwrapRefType(loopVar.getType()), |
| 990 |
iterWhileOp.getInductionVar()); |
| 991 |
builder.create<fir::StoreOp>(loc, lcv, loopVar); |
| 992 |
ok = iterWhileOp.getIterateVar(); |
| 993 |
mlir::Value falseValue = |
| 994 |
builder.createIntegerConstant(loc, builder.getI1Type(), 0); |
| 995 |
genItemList(ioImpliedDo); |
| 996 |
// Unwind nested IO call scopes, filling in true and false ResultOp's. |
| 997 |
for (mlir::Operation *op = builder.getBlock()->getParentOp(); |
| 998 |
mlir::isa<fir::IfOp>(op); op = op->getBlock()->getParentOp()) { |
| 999 |
auto ifOp = mlir::dyn_cast<fir::IfOp>(op); |
| 1000 |
mlir::Operation *lastOp = &ifOp.getThenRegion().front().back(); |
| 1001 |
builder.setInsertionPointAfter(lastOp); |
| 1002 |
// The primary ifOp result is the result of an IO call or loop. |
| 1003 |
if (mlir::isa<fir::CallOp, fir::IfOp>(*lastOp)) |
| 1004 |
builder.create<fir::ResultOp>(loc, lastOp->getResult(0)); |
| 1005 |
else |
| 1006 |
builder.create<fir::ResultOp>(loc, ok); // loop result |
| 1007 |
// The else branch propagates an early exit false result. |
| 1008 |
builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); |
| 1009 |
builder.create<fir::ResultOp>(loc, falseValue); |
| 1010 |
} |
| 1011 |
builder.setInsertionPointToEnd(iterWhileOp.getBody()); |
| 1012 |
mlir::OpResult iterateResult = builder.getBlock()->back().getResult(0); |
| 1013 |
mlir::Value inductionResult0 = iterWhileOp.getInductionVar(); |
| 1014 |
auto inductionResult1 = builder.create<mlir::arith::AddIOp>( |
| 1015 |
loc, inductionResult0, iterWhileOp.getStep(), iofAttr); |
| 1016 |
auto inductionResult = builder.create<mlir::arith::SelectOp>( |
| 1017 |
loc, iterateResult, inductionResult1, inductionResult0); |
| 1018 |
llvm::SmallVector<mlir::Value> results = {inductionResult, iterateResult}; |
| 1019 |
builder.create<fir::ResultOp>(loc, results); |
| 1020 |
ok = iterWhileOp.getResult(1); |
| 1021 |
builder.setInsertionPointAfter(iterWhileOp); |
| 1022 |
// The loop control variable may be used after the loop. |
| 1023 |
lcv = builder.createConvert(loc, fir::unwrapRefType(loopVar.getType()), |
| 1024 |
iterWhileOp.getResult(0)); |
| 1025 |
builder.create<fir::StoreOp>(loc, lcv, loopVar); |
| 1026 |
} |
| 1027 |
|
| 1028 |
//===----------------------------------------------------------------------===// |
| 1029 |
// Default argument generation. |
| 1030 |
//===----------------------------------------------------------------------===// |
| 1031 |
|
| 1032 |
static mlir::Value locToFilename(Fortran::lower::AbstractConverter &converter, |
| 1033 |
mlir::Location loc, mlir::Type toType) { |
| 1034 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1035 |
return builder.createConvert(loc, toType, |
| 1036 |
fir::factory::locationToFilename(builder, loc)); |
| 1037 |
} |
| 1038 |
|
| 1039 |
static mlir::Value locToLineNo(Fortran::lower::AbstractConverter &converter, |
| 1040 |
mlir::Location loc, mlir::Type toType) { |
| 1041 |
return fir::factory::locationToLineNo(converter.getFirOpBuilder(), loc, |
| 1042 |
toType); |
| 1043 |
} |
| 1044 |
|
| 1045 |
static mlir::Value getDefaultScratch(fir::FirOpBuilder &builder, |
| 1046 |
mlir::Location loc, mlir::Type toType) { |
| 1047 |
mlir::Value null = builder.create<mlir::arith::ConstantOp>( |
| 1048 |
loc, builder.getI64IntegerAttr(0)); |
| 1049 |
return builder.createConvert(loc, toType, null); |
| 1050 |
} |
| 1051 |
|
| 1052 |
static mlir::Value getDefaultScratchLen(fir::FirOpBuilder &builder, |
| 1053 |
mlir::Location loc, mlir::Type toType) { |
| 1054 |
return builder.create<mlir::arith::ConstantOp>( |
| 1055 |
loc, builder.getIntegerAttr(toType, 0)); |
| 1056 |
} |
| 1057 |
|
| 1058 |
/// Generate a reference to a buffer and the length of buffer given |
| 1059 |
/// a character expression. An array expression will be cast to scalar |
| 1060 |
/// character as long as they are contiguous. |
| 1061 |
static std::tuple<mlir::Value, mlir::Value> |
| 1062 |
genBuffer(Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1063 |
const Fortran::lower::SomeExpr &expr, mlir::Type strTy, |
| 1064 |
mlir::Type lenTy, Fortran::lower::StatementContext &stmtCtx) { |
| 1065 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1066 |
fir::ExtendedValue exprAddr = converter.genExprAddr(expr, stmtCtx); |
| 1067 |
fir::factory::CharacterExprHelper helper(builder, loc); |
| 1068 |
using ValuePair = std::pair<mlir::Value, mlir::Value>; |
| 1069 |
auto [buff, len] = exprAddr.match( |
| 1070 |
[&](const fir::CharBoxValue &x) -> ValuePair { |
| 1071 |
return {x.getBuffer(), x.getLen()}; |
| 1072 |
}, |
| 1073 |
[&](const fir::CharArrayBoxValue &x) -> ValuePair { |
| 1074 |
fir::CharBoxValue scalar = helper.toScalarCharacter(x); |
| 1075 |
return {scalar.getBuffer(), scalar.getLen()}; |
| 1076 |
}, |
| 1077 |
[&](const fir::BoxValue &) -> ValuePair { |
| 1078 |
// May need to copy before after IO to handle contiguous |
| 1079 |
// aspect. Not sure descriptor can get here though. |
| 1080 |
TODO(loc, "character descriptor to contiguous buffer"); |
| 1081 |
}, |
| 1082 |
[&](const auto &) -> ValuePair { |
| 1083 |
llvm::report_fatal_error( |
| 1084 |
"internal error: IO buffer is not a character"); |
| 1085 |
}); |
| 1086 |
buff = builder.createConvert(loc, strTy, buff); |
| 1087 |
len = builder.createConvert(loc, lenTy, len); |
| 1088 |
return {buff, len}; |
| 1089 |
} |
| 1090 |
|
| 1091 |
/// Lower a string literal. Many arguments to the runtime are conveyed as |
| 1092 |
/// Fortran CHARACTER literals. |
| 1093 |
template <typename A> |
| 1094 |
static std::tuple<mlir::Value, mlir::Value, mlir::Value> |
| 1095 |
lowerStringLit(Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1096 |
Fortran::lower::StatementContext &stmtCtx, const A &syntax, |
| 1097 |
mlir::Type strTy, mlir::Type lenTy, mlir::Type ty2 = {}) { |
| 1098 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1099 |
auto *expr = Fortran::semantics::GetExpr(syntax); |
| 1100 |
if (!expr) |
| 1101 |
fir::emitFatalError(loc, "internal error: null semantic expr in IO"); |
| 1102 |
auto [buff, len] = genBuffer(converter, loc, *expr, strTy, lenTy, stmtCtx); |
| 1103 |
mlir::Value kind; |
| 1104 |
if (ty2) { |
| 1105 |
auto kindVal = expr->GetType().value().kind(); |
| 1106 |
kind = builder.create<mlir::arith::ConstantOp>( |
| 1107 |
loc, builder.getIntegerAttr(ty2, kindVal)); |
| 1108 |
} |
| 1109 |
return {buff, len, kind}; |
| 1110 |
} |
| 1111 |
|
| 1112 |
/// Pass the body of the FORMAT statement in as if it were a CHARACTER literal |
| 1113 |
/// constant. NB: This is the prescribed manner in which the front-end passes |
| 1114 |
/// this information to lowering. |
| 1115 |
static std::tuple<mlir::Value, mlir::Value, mlir::Value> |
| 1116 |
lowerSourceTextAsStringLit(Fortran::lower::AbstractConverter &converter, |
| 1117 |
mlir::Location loc, llvm::StringRef text, |
| 1118 |
mlir::Type strTy, mlir::Type lenTy) { |
| 1119 |
text = text.drop_front(text.find('(')); |
| 1120 |
text = text.take_front(text.rfind(')') + 1); |
| 1121 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1122 |
mlir::Value addrGlobalStringLit = |
| 1123 |
fir::getBase(fir::factory::createStringLiteral(builder, loc, text)); |
| 1124 |
mlir::Value buff = builder.createConvert(loc, strTy, addrGlobalStringLit); |
| 1125 |
mlir::Value len = builder.createIntegerConstant(loc, lenTy, text.size()); |
| 1126 |
return {buff, len, mlir::Value{}}; |
| 1127 |
} |
| 1128 |
|
| 1129 |
//===----------------------------------------------------------------------===// |
| 1130 |
// Handle IO statement specifiers. |
| 1131 |
// These are threaded together for a single statement via the passed cookie. |
| 1132 |
//===----------------------------------------------------------------------===// |
| 1133 |
|
| 1134 |
/// Generic to build an integral argument to the runtime. |
| 1135 |
template <typename A, typename B> |
| 1136 |
mlir::Value genIntIOOption(Fortran::lower::AbstractConverter &converter, |
| 1137 |
mlir::Location loc, mlir::Value cookie, |
| 1138 |
const B &spec) { |
| 1139 |
Fortran::lower::StatementContext localStatementCtx; |
| 1140 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1141 |
mlir::func::FuncOp ioFunc = getIORuntimeFunc<A>(loc, builder); |
| 1142 |
mlir::FunctionType ioFuncTy = ioFunc.getFunctionType(); |
| 1143 |
mlir::Value expr = fir::getBase(converter.genExprValue( |
| 1144 |
loc, Fortran::semantics::GetExpr(spec.v), localStatementCtx)); |
| 1145 |
mlir::Value val = builder.createConvert(loc, ioFuncTy.getInput(1), expr); |
| 1146 |
llvm::SmallVector<mlir::Value> ioArgs = {cookie, val}; |
| 1147 |
return builder.create<fir::CallOp>(loc, ioFunc, ioArgs).getResult(0); |
| 1148 |
} |
| 1149 |
|
| 1150 |
/// Generic to build a string argument to the runtime. This passes a CHARACTER |
| 1151 |
/// as a pointer to the buffer and a LEN parameter. |
| 1152 |
template <typename A, typename B> |
| 1153 |
mlir::Value genCharIOOption(Fortran::lower::AbstractConverter &converter, |
| 1154 |
mlir::Location loc, mlir::Value cookie, |
| 1155 |
const B &spec) { |
| 1156 |
Fortran::lower::StatementContext localStatementCtx; |
| 1157 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1158 |
mlir::func::FuncOp ioFunc = getIORuntimeFunc<A>(loc, builder); |
| 1159 |
mlir::FunctionType ioFuncTy = ioFunc.getFunctionType(); |
| 1160 |
std::tuple<mlir::Value, mlir::Value, mlir::Value> tup = |
| 1161 |
lowerStringLit(converter, loc, localStatementCtx, spec, |
| 1162 |
ioFuncTy.getInput(1), ioFuncTy.getInput(2)); |
| 1163 |
llvm::SmallVector<mlir::Value> ioArgs = {cookie, std::get<0>(tup), |
| 1164 |
std::get<1>(tup)}; |
| 1165 |
return builder.create<fir::CallOp>(loc, ioFunc, ioArgs).getResult(0); |
| 1166 |
} |
| 1167 |
|
| 1168 |
template <typename A> |
| 1169 |
mlir::Value genIOOption(Fortran::lower::AbstractConverter &converter, |
| 1170 |
mlir::Location loc, mlir::Value cookie, const A &spec) { |
| 1171 |
// These specifiers are processed in advance elsewhere - skip them here. |
| 1172 |
using PreprocessedSpecs = |
| 1173 |
std::tuple<Fortran::parser::EndLabel, Fortran::parser::EorLabel, |
| 1174 |
Fortran::parser::ErrLabel, Fortran::parser::FileUnitNumber, |
| 1175 |
Fortran::parser::Format, Fortran::parser::IoUnit, |
| 1176 |
Fortran::parser::MsgVariable, Fortran::parser::Name, |
| 1177 |
Fortran::parser::StatVariable>; |
| 1178 |
static_assert(Fortran::common::HasMember<A, PreprocessedSpecs>, |
| 1179 |
"missing genIOOPtion specialization"); |
| 1180 |
return {}; |
| 1181 |
} |
| 1182 |
|
| 1183 |
template <> |
| 1184 |
mlir::Value genIOOption<Fortran::parser::FileNameExpr>( |
| 1185 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1186 |
mlir::Value cookie, const Fortran::parser::FileNameExpr &spec) { |
| 1187 |
Fortran::lower::StatementContext localStatementCtx; |
| 1188 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1189 |
// has an extra KIND argument |
| 1190 |
mlir::func::FuncOp ioFunc = getIORuntimeFunc<mkIOKey(SetFile)>(loc, builder); |
| 1191 |
mlir::FunctionType ioFuncTy = ioFunc.getFunctionType(); |
| 1192 |
std::tuple<mlir::Value, mlir::Value, mlir::Value> tup = |
| 1193 |
lowerStringLit(converter, loc, localStatementCtx, spec, |
| 1194 |
ioFuncTy.getInput(1), ioFuncTy.getInput(2)); |
| 1195 |
llvm::SmallVector<mlir::Value> ioArgs{cookie, std::get<0>(tup), |
| 1196 |
std::get<1>(tup)}; |
| 1197 |
return builder.create<fir::CallOp>(loc, ioFunc, ioArgs).getResult(0); |
| 1198 |
} |
| 1199 |
|
| 1200 |
template <> |
| 1201 |
mlir::Value genIOOption<Fortran::parser::ConnectSpec::CharExpr>( |
| 1202 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1203 |
mlir::Value cookie, const Fortran::parser::ConnectSpec::CharExpr &spec) { |
| 1204 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1205 |
mlir::func::FuncOp ioFunc; |
| 1206 |
switch (std::get<Fortran::parser::ConnectSpec::CharExpr::Kind>(spec.t)) { |
| 1207 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Access: |
| 1208 |
ioFunc = getIORuntimeFunc<mkIOKey(SetAccess)>(loc, builder); |
| 1209 |
break; |
| 1210 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Action: |
| 1211 |
ioFunc = getIORuntimeFunc<mkIOKey(SetAction)>(loc, builder); |
| 1212 |
break; |
| 1213 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Asynchronous: |
| 1214 |
ioFunc = getIORuntimeFunc<mkIOKey(SetAsynchronous)>(loc, builder); |
| 1215 |
break; |
| 1216 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Blank: |
| 1217 |
ioFunc = getIORuntimeFunc<mkIOKey(SetBlank)>(loc, builder); |
| 1218 |
break; |
| 1219 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Decimal: |
| 1220 |
ioFunc = getIORuntimeFunc<mkIOKey(SetDecimal)>(loc, builder); |
| 1221 |
break; |
| 1222 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Delim: |
| 1223 |
ioFunc = getIORuntimeFunc<mkIOKey(SetDelim)>(loc, builder); |
| 1224 |
break; |
| 1225 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Encoding: |
| 1226 |
ioFunc = getIORuntimeFunc<mkIOKey(SetEncoding)>(loc, builder); |
| 1227 |
break; |
| 1228 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Form: |
| 1229 |
ioFunc = getIORuntimeFunc<mkIOKey(SetForm)>(loc, builder); |
| 1230 |
break; |
| 1231 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Pad: |
| 1232 |
ioFunc = getIORuntimeFunc<mkIOKey(SetPad)>(loc, builder); |
| 1233 |
break; |
| 1234 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Position: |
| 1235 |
ioFunc = getIORuntimeFunc<mkIOKey(SetPosition)>(loc, builder); |
| 1236 |
break; |
| 1237 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Round: |
| 1238 |
ioFunc = getIORuntimeFunc<mkIOKey(SetRound)>(loc, builder); |
| 1239 |
break; |
| 1240 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Sign: |
| 1241 |
ioFunc = getIORuntimeFunc<mkIOKey(SetSign)>(loc, builder); |
| 1242 |
break; |
| 1243 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Carriagecontrol: |
| 1244 |
ioFunc = getIORuntimeFunc<mkIOKey(SetCarriagecontrol)>(loc, builder); |
| 1245 |
break; |
| 1246 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Convert: |
| 1247 |
ioFunc = getIORuntimeFunc<mkIOKey(SetConvert)>(loc, builder); |
| 1248 |
break; |
| 1249 |
case Fortran::parser::ConnectSpec::CharExpr::Kind::Dispose: |
| 1250 |
TODO(loc, "DISPOSE not part of the runtime::io interface"); |
| 1251 |
} |
| 1252 |
Fortran::lower::StatementContext localStatementCtx; |
| 1253 |
mlir::FunctionType ioFuncTy = ioFunc.getFunctionType(); |
| 1254 |
std::tuple<mlir::Value, mlir::Value, mlir::Value> tup = |
| 1255 |
lowerStringLit(converter, loc, localStatementCtx, |
| 1256 |
std::get<Fortran::parser::ScalarDefaultCharExpr>(spec.t), |
| 1257 |
ioFuncTy.getInput(1), ioFuncTy.getInput(2)); |
| 1258 |
llvm::SmallVector<mlir::Value> ioArgs = {cookie, std::get<0>(tup), |
| 1259 |
std::get<1>(tup)}; |
| 1260 |
return builder.create<fir::CallOp>(loc, ioFunc, ioArgs).getResult(0); |
| 1261 |
} |
| 1262 |
|
| 1263 |
template <> |
| 1264 |
mlir::Value genIOOption<Fortran::parser::ConnectSpec::Recl>( |
| 1265 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1266 |
mlir::Value cookie, const Fortran::parser::ConnectSpec::Recl &spec) { |
| 1267 |
return genIntIOOption<mkIOKey(SetRecl)>(converter, loc, cookie, spec); |
| 1268 |
} |
| 1269 |
|
| 1270 |
template <> |
| 1271 |
mlir::Value genIOOption<Fortran::parser::StatusExpr>( |
| 1272 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1273 |
mlir::Value cookie, const Fortran::parser::StatusExpr &spec) { |
| 1274 |
return genCharIOOption<mkIOKey(SetStatus)>(converter, loc, cookie, spec.v); |
| 1275 |
} |
| 1276 |
|
| 1277 |
template <> |
| 1278 |
mlir::Value genIOOption<Fortran::parser::IoControlSpec::CharExpr>( |
| 1279 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1280 |
mlir::Value cookie, const Fortran::parser::IoControlSpec::CharExpr &spec) { |
| 1281 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1282 |
mlir::func::FuncOp ioFunc; |
| 1283 |
switch (std::get<Fortran::parser::IoControlSpec::CharExpr::Kind>(spec.t)) { |
| 1284 |
case Fortran::parser::IoControlSpec::CharExpr::Kind::Advance: |
| 1285 |
ioFunc = getIORuntimeFunc<mkIOKey(SetAdvance)>(loc, builder); |
| 1286 |
break; |
| 1287 |
case Fortran::parser::IoControlSpec::CharExpr::Kind::Blank: |
| 1288 |
ioFunc = getIORuntimeFunc<mkIOKey(SetBlank)>(loc, builder); |
| 1289 |
break; |
| 1290 |
case Fortran::parser::IoControlSpec::CharExpr::Kind::Decimal: |
| 1291 |
ioFunc = getIORuntimeFunc<mkIOKey(SetDecimal)>(loc, builder); |
| 1292 |
break; |
| 1293 |
case Fortran::parser::IoControlSpec::CharExpr::Kind::Delim: |
| 1294 |
ioFunc = getIORuntimeFunc<mkIOKey(SetDelim)>(loc, builder); |
| 1295 |
break; |
| 1296 |
case Fortran::parser::IoControlSpec::CharExpr::Kind::Pad: |
| 1297 |
ioFunc = getIORuntimeFunc<mkIOKey(SetPad)>(loc, builder); |
| 1298 |
break; |
| 1299 |
case Fortran::parser::IoControlSpec::CharExpr::Kind::Round: |
| 1300 |
ioFunc = getIORuntimeFunc<mkIOKey(SetRound)>(loc, builder); |
| 1301 |
break; |
| 1302 |
case Fortran::parser::IoControlSpec::CharExpr::Kind::Sign: |
| 1303 |
ioFunc = getIORuntimeFunc<mkIOKey(SetSign)>(loc, builder); |
| 1304 |
break; |
| 1305 |
} |
| 1306 |
Fortran::lower::StatementContext localStatementCtx; |
| 1307 |
mlir::FunctionType ioFuncTy = ioFunc.getFunctionType(); |
| 1308 |
std::tuple<mlir::Value, mlir::Value, mlir::Value> tup = |
| 1309 |
lowerStringLit(converter, loc, localStatementCtx, |
| 1310 |
std::get<Fortran::parser::ScalarDefaultCharExpr>(spec.t), |
| 1311 |
ioFuncTy.getInput(1), ioFuncTy.getInput(2)); |
| 1312 |
llvm::SmallVector<mlir::Value> ioArgs = {cookie, std::get<0>(tup), |
| 1313 |
std::get<1>(tup)}; |
| 1314 |
return builder.create<fir::CallOp>(loc, ioFunc, ioArgs).getResult(0); |
| 1315 |
} |
| 1316 |
|
| 1317 |
template <> |
| 1318 |
mlir::Value genIOOption<Fortran::parser::IoControlSpec::Asynchronous>( |
| 1319 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1320 |
mlir::Value cookie, |
| 1321 |
const Fortran::parser::IoControlSpec::Asynchronous &spec) { |
| 1322 |
return genCharIOOption<mkIOKey(SetAsynchronous)>(converter, loc, cookie, |
| 1323 |
spec.v); |
| 1324 |
} |
| 1325 |
|
| 1326 |
template <> |
| 1327 |
mlir::Value genIOOption<Fortran::parser::IoControlSpec::Pos>( |
| 1328 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1329 |
mlir::Value cookie, const Fortran::parser::IoControlSpec::Pos &spec) { |
| 1330 |
return genIntIOOption<mkIOKey(SetPos)>(converter, loc, cookie, spec); |
| 1331 |
} |
| 1332 |
|
| 1333 |
template <> |
| 1334 |
mlir::Value genIOOption<Fortran::parser::IoControlSpec::Rec>( |
| 1335 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1336 |
mlir::Value cookie, const Fortran::parser::IoControlSpec::Rec &spec) { |
| 1337 |
return genIntIOOption<mkIOKey(SetRec)>(converter, loc, cookie, spec); |
| 1338 |
} |
| 1339 |
|
| 1340 |
/// Generate runtime call to set some control variable. |
| 1341 |
/// Generates "VAR = IoRuntimeKey(cookie)". |
| 1342 |
template <typename IoRuntimeKey, typename VAR> |
| 1343 |
static void genIOGetVar(Fortran::lower::AbstractConverter &converter, |
| 1344 |
mlir::Location loc, mlir::Value cookie, |
| 1345 |
const VAR &parserVar) { |
| 1346 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1347 |
mlir::func::FuncOp ioFunc = getIORuntimeFunc<IoRuntimeKey>(loc, builder); |
| 1348 |
mlir::Value value = |
| 1349 |
builder.create<fir::CallOp>(loc, ioFunc, mlir::ValueRange{cookie}) |
| 1350 |
.getResult(0); |
| 1351 |
Fortran::lower::StatementContext localStatementCtx; |
| 1352 |
fir::ExtendedValue var = converter.genExprAddr( |
| 1353 |
loc, Fortran::semantics::GetExpr(parserVar.v), localStatementCtx); |
| 1354 |
builder.createStoreWithConvert(loc, value, fir::getBase(var)); |
| 1355 |
} |
| 1356 |
|
| 1357 |
//===----------------------------------------------------------------------===// |
| 1358 |
// Gather IO statement condition specifier information (if any). |
| 1359 |
//===----------------------------------------------------------------------===// |
| 1360 |
|
| 1361 |
template <typename SEEK, typename A> |
| 1362 |
static bool hasX(const A &list) { |
| 1363 |
for (const auto &spec : list) |
| 1364 |
if (std::holds_alternative<SEEK>(spec.u)) |
| 1365 |
return true; |
| 1366 |
return false; |
| 1367 |
} |
| 1368 |
|
| 1369 |
template <typename SEEK, typename A> |
| 1370 |
static bool hasSpec(const A &stmt) { |
| 1371 |
return hasX<SEEK>(stmt.v); |
| 1372 |
} |
| 1373 |
|
| 1374 |
/// Get the sought expression from the specifier list. |
| 1375 |
template <typename SEEK, typename A> |
| 1376 |
static const Fortran::lower::SomeExpr *getExpr(const A &stmt) { |
| 1377 |
for (const auto &spec : stmt.v) |
| 1378 |
if (auto *f = std::get_if<SEEK>(&spec.u)) |
| 1379 |
return Fortran::semantics::GetExpr(f->v); |
| 1380 |
llvm::report_fatal_error("must have a file unit"); |
| 1381 |
} |
| 1382 |
|
| 1383 |
/// For each specifier, build the appropriate call, threading the cookie. |
| 1384 |
template <typename A> |
| 1385 |
static void threadSpecs(Fortran::lower::AbstractConverter &converter, |
| 1386 |
mlir::Location loc, mlir::Value cookie, |
| 1387 |
const A &specList, bool checkResult, mlir::Value &ok) { |
| 1388 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1389 |
for (const auto &spec : specList) { |
| 1390 |
makeNextConditionalOn(builder, loc, checkResult, ok); |
| 1391 |
ok = Fortran::common::visit( |
| 1392 |
Fortran::common::visitors{ |
| 1393 |
[&](const Fortran::parser::IoControlSpec::Size &x) -> mlir::Value { |
| 1394 |
// Size must be queried after the related READ runtime calls, not |
| 1395 |
// before. |
| 1396 |
return ok; |
| 1397 |
}, |
| 1398 |
[&](const Fortran::parser::ConnectSpec::Newunit &x) -> mlir::Value { |
| 1399 |
// Newunit must be queried after OPEN specifier runtime calls |
| 1400 |
// that may fail to avoid modifying the newunit variable if |
| 1401 |
// there is an error. |
| 1402 |
return ok; |
| 1403 |
}, |
| 1404 |
[&](const Fortran::parser::IdVariable &) -> mlir::Value { |
| 1405 |
// ID is queried after the transfer so that ASYNCHROUNOUS= has |
| 1406 |
// been processed and also to set it to zero if the transfer is |
| 1407 |
// already finished. |
| 1408 |
return ok; |
| 1409 |
}, |
| 1410 |
[&](const auto &x) { |
| 1411 |
return genIOOption(converter, loc, cookie, x); |
| 1412 |
}}, |
| 1413 |
spec.u); |
| 1414 |
} |
| 1415 |
} |
| 1416 |
|
| 1417 |
/// Most IO statements allow one or more of five optional exception condition |
| 1418 |
/// handling specifiers: ERR, EOR, END, IOSTAT, and IOMSG. The first three |
| 1419 |
/// cause control flow to transfer to another statement. The final two return |
| 1420 |
/// information from the runtime, via a variable, about the nature of the |
| 1421 |
/// condition that occurred. These condition specifiers are handled here. |
| 1422 |
template <typename A> |
| 1423 |
ConditionSpecInfo lowerErrorSpec(Fortran::lower::AbstractConverter &converter, |
| 1424 |
mlir::Location loc, const A &specList) { |
| 1425 |
ConditionSpecInfo csi; |
| 1426 |
const Fortran::lower::SomeExpr *ioMsgExpr = nullptr; |
| 1427 |
for (const auto &spec : specList) { |
| 1428 |
Fortran::common::visit( |
| 1429 |
Fortran::common::visitors{ |
| 1430 |
[&](const Fortran::parser::StatVariable &var) { |
| 1431 |
csi.ioStatExpr = Fortran::semantics::GetExpr(var); |
| 1432 |
}, |
| 1433 |
[&](const Fortran::parser::InquireSpec::IntVar &var) { |
| 1434 |
if (std::get<Fortran::parser::InquireSpec::IntVar::Kind>(var.t) == |
| 1435 |
Fortran::parser::InquireSpec::IntVar::Kind::Iostat) |
| 1436 |
csi.ioStatExpr = Fortran::semantics::GetExpr( |
| 1437 |
std::get<Fortran::parser::ScalarIntVariable>(var.t)); |
| 1438 |
}, |
| 1439 |
[&](const Fortran::parser::MsgVariable &var) { |
| 1440 |
ioMsgExpr = Fortran::semantics::GetExpr(var); |
| 1441 |
}, |
| 1442 |
[&](const Fortran::parser::InquireSpec::CharVar &var) { |
| 1443 |
if (std::get<Fortran::parser::InquireSpec::CharVar::Kind>( |
| 1444 |
var.t) == |
| 1445 |
Fortran::parser::InquireSpec::CharVar::Kind::Iomsg) |
| 1446 |
ioMsgExpr = Fortran::semantics::GetExpr( |
| 1447 |
std::get<Fortran::parser::ScalarDefaultCharVariable>( |
| 1448 |
var.t)); |
| 1449 |
}, |
| 1450 |
[&](const Fortran::parser::EndLabel &) { csi.hasEnd = true; }, |
| 1451 |
[&](const Fortran::parser::EorLabel &) { csi.hasEor = true; }, |
| 1452 |
[&](const Fortran::parser::ErrLabel &) { csi.hasErr = true; }, |
| 1453 |
[](const auto &) {}}, |
| 1454 |
spec.u); |
| 1455 |
} |
| 1456 |
if (ioMsgExpr) { |
| 1457 |
// iomsg is a variable, its evaluation may require temps, but it cannot |
| 1458 |
// itself be a temp, and it is ok to us a local statement context here. |
| 1459 |
Fortran::lower::StatementContext stmtCtx; |
| 1460 |
csi.ioMsg = converter.genExprAddr(loc, ioMsgExpr, stmtCtx); |
| 1461 |
} |
| 1462 |
|
| 1463 |
return csi; |
| 1464 |
} |
| 1465 |
template <typename A> |
| 1466 |
static void |
| 1467 |
genConditionHandlerCall(Fortran::lower::AbstractConverter &converter, |
| 1468 |
mlir::Location loc, mlir::Value cookie, |
| 1469 |
const A &specList, ConditionSpecInfo &csi) { |
| 1470 |
if (!csi.hasAnyConditionSpec()) |
| 1471 |
return; |
| 1472 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1473 |
mlir::func::FuncOp enableHandlers = |
| 1474 |
getIORuntimeFunc<mkIOKey(EnableHandlers)>(loc, builder); |
| 1475 |
mlir::Type boolType = enableHandlers.getFunctionType().getInput(1); |
| 1476 |
auto boolValue = [&](bool specifierIsPresent) { |
| 1477 |
return builder.create<mlir::arith::ConstantOp>( |
| 1478 |
loc, builder.getIntegerAttr(boolType, specifierIsPresent)); |
| 1479 |
}; |
| 1480 |
llvm::SmallVector<mlir::Value> ioArgs = {cookie, |
| 1481 |
boolValue(csi.ioStatExpr != nullptr), |
| 1482 |
boolValue(csi.hasErr), |
| 1483 |
boolValue(csi.hasEnd), |
| 1484 |
boolValue(csi.hasEor), |
| 1485 |
boolValue(csi.ioMsg.has_value())}; |
| 1486 |
builder.create<fir::CallOp>(loc, enableHandlers, ioArgs); |
| 1487 |
} |
| 1488 |
|
| 1489 |
//===----------------------------------------------------------------------===// |
| 1490 |
// Data transfer helpers |
| 1491 |
//===----------------------------------------------------------------------===// |
| 1492 |
|
| 1493 |
template <typename SEEK, typename A> |
| 1494 |
static bool hasIOControl(const A &stmt) { |
| 1495 |
return hasX<SEEK>(stmt.controls); |
| 1496 |
} |
| 1497 |
|
| 1498 |
template <typename SEEK, typename A> |
| 1499 |
static const auto *getIOControl(const A &stmt) { |
| 1500 |
for (const auto &spec : stmt.controls) |
| 1501 |
if (const auto *result = std::get_if<SEEK>(&spec.u)) |
| 1502 |
return result; |
| 1503 |
return static_cast<const SEEK *>(nullptr); |
| 1504 |
} |
| 1505 |
|
| 1506 |
/// Returns true iff the expression in the parse tree is not really a format but |
| 1507 |
/// rather a namelist group. |
| 1508 |
template <typename A> |
| 1509 |
static bool formatIsActuallyNamelist(const A &format) { |
| 1510 |
if (auto *e = std::get_if<Fortran::parser::Expr>(&format.u)) { |
| 1511 |
auto *expr = Fortran::semantics::GetExpr(*e); |
| 1512 |
if (const Fortran::semantics::Symbol *y = |
| 1513 |
Fortran::evaluate::UnwrapWholeSymbolDataRef(*expr)) |
| 1514 |
return y->has<Fortran::semantics::NamelistDetails>(); |
| 1515 |
} |
| 1516 |
return false; |
| 1517 |
} |
| 1518 |
|
| 1519 |
template <typename A> |
| 1520 |
static bool isDataTransferFormatted(const A &stmt) { |
| 1521 |
if (stmt.format) |
| 1522 |
return !formatIsActuallyNamelist(*stmt.format); |
| 1523 |
return hasIOControl<Fortran::parser::Format>(stmt); |
| 1524 |
} |
| 1525 |
template <> |
| 1526 |
constexpr bool isDataTransferFormatted<Fortran::parser::PrintStmt>( |
| 1527 |
const Fortran::parser::PrintStmt &) { |
| 1528 |
return true; // PRINT is always formatted |
| 1529 |
} |
| 1530 |
|
| 1531 |
template <typename A> |
| 1532 |
static bool isDataTransferList(const A &stmt) { |
| 1533 |
if (stmt.format) |
| 1534 |
return std::holds_alternative<Fortran::parser::Star>(stmt.format->u); |
| 1535 |
if (auto *mem = getIOControl<Fortran::parser::Format>(stmt)) |
| 1536 |
return std::holds_alternative<Fortran::parser::Star>(mem->u); |
| 1537 |
return false; |
| 1538 |
} |
| 1539 |
template <> |
| 1540 |
bool isDataTransferList<Fortran::parser::PrintStmt>( |
| 1541 |
const Fortran::parser::PrintStmt &stmt) { |
| 1542 |
return std::holds_alternative<Fortran::parser::Star>( |
| 1543 |
std::get<Fortran::parser::Format>(stmt.t).u); |
| 1544 |
} |
| 1545 |
|
| 1546 |
template <typename A> |
| 1547 |
static bool isDataTransferInternal(const A &stmt) { |
| 1548 |
if (stmt.iounit.has_value()) |
| 1549 |
return std::holds_alternative<Fortran::parser::Variable>(stmt.iounit->u); |
| 1550 |
if (auto *unit = getIOControl<Fortran::parser::IoUnit>(stmt)) |
| 1551 |
return std::holds_alternative<Fortran::parser::Variable>(unit->u); |
| 1552 |
return false; |
| 1553 |
} |
| 1554 |
template <> |
| 1555 |
constexpr bool isDataTransferInternal<Fortran::parser::PrintStmt>( |
| 1556 |
const Fortran::parser::PrintStmt &) { |
| 1557 |
return false; |
| 1558 |
} |
| 1559 |
|
| 1560 |
/// If the variable `var` is an array or of a KIND other than the default |
| 1561 |
/// (normally 1), then a descriptor is required by the runtime IO API. This |
| 1562 |
/// condition holds even in F77 sources. |
| 1563 |
static std::optional<fir::ExtendedValue> getVariableBufferRequiredDescriptor( |
| 1564 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1565 |
const Fortran::parser::Variable &var, |
| 1566 |
Fortran::lower::StatementContext &stmtCtx) { |
| 1567 |
fir::ExtendedValue varBox = |
| 1568 |
converter.genExprBox(loc, var.typedExpr->v.value(), stmtCtx); |
| 1569 |
fir::KindTy defCharKind = converter.getKindMap().defaultCharacterKind(); |
| 1570 |
mlir::Value varAddr = fir::getBase(varBox); |
| 1571 |
if (fir::factory::CharacterExprHelper::getCharacterOrSequenceKind( |
| 1572 |
varAddr.getType()) != defCharKind) |
| 1573 |
return varBox; |
| 1574 |
if (fir::factory::CharacterExprHelper::isArray(varAddr.getType())) |
| 1575 |
return varBox; |
| 1576 |
return std::nullopt; |
| 1577 |
} |
| 1578 |
|
| 1579 |
template <typename A> |
| 1580 |
static std::optional<fir::ExtendedValue> |
| 1581 |
maybeGetInternalIODescriptor(Fortran::lower::AbstractConverter &converter, |
| 1582 |
mlir::Location loc, const A &stmt, |
| 1583 |
Fortran::lower::StatementContext &stmtCtx) { |
| 1584 |
if (stmt.iounit.has_value()) |
| 1585 |
if (auto *var = std::get_if<Fortran::parser::Variable>(&stmt.iounit->u)) |
| 1586 |
return getVariableBufferRequiredDescriptor(converter, loc, *var, stmtCtx); |
| 1587 |
if (auto *unit = getIOControl<Fortran::parser::IoUnit>(stmt)) |
| 1588 |
if (auto *var = std::get_if<Fortran::parser::Variable>(&unit->u)) |
| 1589 |
return getVariableBufferRequiredDescriptor(converter, loc, *var, stmtCtx); |
| 1590 |
return std::nullopt; |
| 1591 |
} |
| 1592 |
template <> |
| 1593 |
inline std::optional<fir::ExtendedValue> |
| 1594 |
maybeGetInternalIODescriptor<Fortran::parser::PrintStmt>( |
| 1595 |
Fortran::lower::AbstractConverter &, mlir::Location loc, |
| 1596 |
const Fortran::parser::PrintStmt &, Fortran::lower::StatementContext &) { |
| 1597 |
return std::nullopt; |
| 1598 |
} |
| 1599 |
|
| 1600 |
template <typename A> |
| 1601 |
static bool isDataTransferNamelist(const A &stmt) { |
| 1602 |
if (stmt.format) |
| 1603 |
return formatIsActuallyNamelist(*stmt.format); |
| 1604 |
return hasIOControl<Fortran::parser::Name>(stmt); |
| 1605 |
} |
| 1606 |
template <> |
| 1607 |
constexpr bool isDataTransferNamelist<Fortran::parser::PrintStmt>( |
| 1608 |
const Fortran::parser::PrintStmt &) { |
| 1609 |
return false; |
| 1610 |
} |
| 1611 |
|
| 1612 |
/// Lowers a format statment that uses an assigned variable label reference as |
| 1613 |
/// a select operation to allow for run-time selection of the format statement. |
| 1614 |
static std::tuple<mlir::Value, mlir::Value, mlir::Value> |
| 1615 |
lowerReferenceAsStringSelect(Fortran::lower::AbstractConverter &converter, |
| 1616 |
mlir::Location loc, |
| 1617 |
const Fortran::lower::SomeExpr &expr, |
| 1618 |
mlir::Type strTy, mlir::Type lenTy, |
| 1619 |
Fortran::lower::StatementContext &stmtCtx) { |
| 1620 |
// Create the requisite blocks to inline a selectOp. |
| 1621 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1622 |
mlir::Block *startBlock = builder.getBlock(); |
| 1623 |
mlir::Block *endBlock = startBlock->splitBlock(builder.getInsertionPoint()); |
| 1624 |
mlir::Block *block = startBlock->splitBlock(builder.getInsertionPoint()); |
| 1625 |
builder.setInsertionPointToEnd(block); |
| 1626 |
|
| 1627 |
llvm::SmallVector<int64_t> indexList; |
| 1628 |
llvm::SmallVector<mlir::Block *> blockList; |
| 1629 |
|
| 1630 |
auto symbol = GetLastSymbol(&expr); |
| 1631 |
Fortran::lower::pft::LabelSet labels; |
| 1632 |
converter.lookupLabelSet(*symbol, labels); |
| 1633 |
|
| 1634 |
for (auto label : labels) { |
| 1635 |
indexList.push_back(label); |
| 1636 |
auto *eval = converter.lookupLabel(label); |
| 1637 |
assert(eval && "Label is missing from the table"); |
| 1638 |
|
| 1639 |
llvm::StringRef text = toStringRef(eval->position); |
| 1640 |
mlir::Value stringRef; |
| 1641 |
mlir::Value stringLen; |
| 1642 |
if (eval->isA<Fortran::parser::FormatStmt>()) { |
| 1643 |
assert(text.contains('(') && "FORMAT is unexpectedly ill-formed"); |
| 1644 |
// This is a format statement, so extract the spec from the text. |
| 1645 |
std::tuple<mlir::Value, mlir::Value, mlir::Value> stringLit = |
| 1646 |
lowerSourceTextAsStringLit(converter, loc, text, strTy, lenTy); |
| 1647 |
stringRef = std::get<0>(stringLit); |
| 1648 |
stringLen = std::get<1>(stringLit); |
| 1649 |
} else { |
| 1650 |
// This is not a format statement, so use null. |
| 1651 |
stringRef = builder.createConvert( |
| 1652 |
loc, strTy, |
| 1653 |
builder.createIntegerConstant(loc, builder.getIndexType(), 0)); |
| 1654 |
stringLen = builder.createIntegerConstant(loc, lenTy, 0); |
| 1655 |
} |
| 1656 |
|
| 1657 |
// Pass the format string reference and the string length out of the select |
| 1658 |
// statement. |
| 1659 |
llvm::SmallVector<mlir::Value> args = {stringRef, stringLen}; |
| 1660 |
builder.create<mlir::cf::BranchOp>(loc, endBlock, args); |
| 1661 |
|
| 1662 |
// Add block to the list of cases and make a new one. |
| 1663 |
blockList.push_back(block); |
| 1664 |
block = block->splitBlock(builder.getInsertionPoint()); |
| 1665 |
builder.setInsertionPointToEnd(block); |
| 1666 |
} |
| 1667 |
|
| 1668 |
// Create the unit case which should result in an error. |
| 1669 |
auto *unitBlock = block->splitBlock(builder.getInsertionPoint()); |
| 1670 |
builder.setInsertionPointToEnd(unitBlock); |
| 1671 |
fir::runtime::genReportFatalUserError( |
| 1672 |
builder, loc, |
| 1673 |
"Assigned format variable '" + symbol->name().ToString() + |
| 1674 |
"' has not been assigned a valid format label"); |
| 1675 |
builder.create<fir::UnreachableOp>(loc); |
| 1676 |
blockList.push_back(unitBlock); |
| 1677 |
|
| 1678 |
// Lower the selectOp. |
| 1679 |
builder.setInsertionPointToEnd(startBlock); |
| 1680 |
auto label = fir::getBase(converter.genExprValue(loc, &expr, stmtCtx)); |
| 1681 |
builder.create<fir::SelectOp>(loc, label, indexList, blockList); |
| 1682 |
|
| 1683 |
builder.setInsertionPointToEnd(endBlock); |
| 1684 |
endBlock->addArgument(strTy, loc); |
| 1685 |
endBlock->addArgument(lenTy, loc); |
| 1686 |
|
| 1687 |
// Handle and return the string reference and length selected by the selectOp. |
| 1688 |
auto buff = endBlock->getArgument(0); |
| 1689 |
auto len = endBlock->getArgument(1); |
| 1690 |
|
| 1691 |
return {buff, len, mlir::Value{}}; |
| 1692 |
} |
| 1693 |
|
| 1694 |
/// Generate a reference to a format string. There are four cases - a format |
| 1695 |
/// statement label, a character format expression, an integer that holds the |
| 1696 |
/// label of a format statement, and the * case. The first three are done here. |
| 1697 |
/// The * case is done elsewhere. |
| 1698 |
static std::tuple<mlir::Value, mlir::Value, mlir::Value> |
| 1699 |
genFormat(Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1700 |
const Fortran::parser::Format &format, mlir::Type strTy, |
| 1701 |
mlir::Type lenTy, Fortran::lower::StatementContext &stmtCtx) { |
| 1702 |
if (const auto *label = std::get_if<Fortran::parser::Label>(&format.u)) { |
| 1703 |
// format statement label |
| 1704 |
auto eval = converter.lookupLabel(*label); |
| 1705 |
assert(eval && "FORMAT not found in PROCEDURE"); |
| 1706 |
return lowerSourceTextAsStringLit( |
| 1707 |
converter, loc, toStringRef(eval->position), strTy, lenTy); |
| 1708 |
} |
| 1709 |
const auto *pExpr = std::get_if<Fortran::parser::Expr>(&format.u); |
| 1710 |
assert(pExpr && "missing format expression"); |
| 1711 |
auto e = Fortran::semantics::GetExpr(*pExpr); |
| 1712 |
if (Fortran::semantics::ExprHasTypeCategory( |
| 1713 |
*e, Fortran::common::TypeCategory::Character)) { |
| 1714 |
// character expression |
| 1715 |
if (e->Rank()) |
| 1716 |
// Array: return address(descriptor) and no length (and no kind value). |
| 1717 |
return {fir::getBase(converter.genExprBox(loc, *e, stmtCtx)), |
| 1718 |
mlir::Value{}, mlir::Value{}}; |
| 1719 |
// Scalar: return address(format) and format length (and no kind value). |
| 1720 |
return lowerStringLit(converter, loc, stmtCtx, *pExpr, strTy, lenTy); |
| 1721 |
} |
| 1722 |
|
| 1723 |
if (Fortran::semantics::ExprHasTypeCategory( |
| 1724 |
*e, Fortran::common::TypeCategory::Integer) && |
| 1725 |
e->Rank() == 0 && Fortran::evaluate::UnwrapWholeSymbolDataRef(*e)) { |
| 1726 |
// Treat as a scalar integer variable containing an ASSIGN label. |
| 1727 |
return lowerReferenceAsStringSelect(converter, loc, *e, strTy, lenTy, |
| 1728 |
stmtCtx); |
| 1729 |
} |
| 1730 |
|
| 1731 |
// Legacy extension: it is possible that `*e` is not a scalar INTEGER |
| 1732 |
// variable containing a label value. The output appears to be the source text |
| 1733 |
// that initialized the variable? Needs more investigatation. |
| 1734 |
TODO(loc, "io-control-spec contains a reference to a non-integer, " |
| 1735 |
"non-scalar, or non-variable"); |
| 1736 |
} |
| 1737 |
|
| 1738 |
template <typename A> |
| 1739 |
std::tuple<mlir::Value, mlir::Value, mlir::Value> |
| 1740 |
getFormat(Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1741 |
const A &stmt, mlir::Type strTy, mlir::Type lenTy, |
| 1742 |
Fortran ::lower::StatementContext &stmtCtx) { |
| 1743 |
if (stmt.format && !formatIsActuallyNamelist(*stmt.format)) |
| 1744 |
return genFormat(converter, loc, *stmt.format, strTy, lenTy, stmtCtx); |
| 1745 |
return genFormat(converter, loc, *getIOControl<Fortran::parser::Format>(stmt), |
| 1746 |
strTy, lenTy, stmtCtx); |
| 1747 |
} |
| 1748 |
template <> |
| 1749 |
std::tuple<mlir::Value, mlir::Value, mlir::Value> |
| 1750 |
getFormat<Fortran::parser::PrintStmt>( |
| 1751 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1752 |
const Fortran::parser::PrintStmt &stmt, mlir::Type strTy, mlir::Type lenTy, |
| 1753 |
Fortran::lower::StatementContext &stmtCtx) { |
| 1754 |
return genFormat(converter, loc, std::get<Fortran::parser::Format>(stmt.t), |
| 1755 |
strTy, lenTy, stmtCtx); |
| 1756 |
} |
| 1757 |
|
| 1758 |
/// Get a buffer for an internal file data transfer. |
| 1759 |
template <typename A> |
| 1760 |
std::tuple<mlir::Value, mlir::Value> |
| 1761 |
getBuffer(Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1762 |
const A &stmt, mlir::Type strTy, mlir::Type lenTy, |
| 1763 |
Fortran::lower::StatementContext &stmtCtx) { |
| 1764 |
const Fortran::parser::IoUnit *iounit = |
| 1765 |
stmt.iounit ? &*stmt.iounit : getIOControl<Fortran::parser::IoUnit>(stmt); |
| 1766 |
if (iounit) |
| 1767 |
if (auto *var = std::get_if<Fortran::parser::Variable>(&iounit->u)) |
| 1768 |
if (auto *expr = Fortran::semantics::GetExpr(*var)) |
| 1769 |
return genBuffer(converter, loc, *expr, strTy, lenTy, stmtCtx); |
| 1770 |
llvm::report_fatal_error("failed to get IoUnit expr"); |
| 1771 |
} |
| 1772 |
|
| 1773 |
static mlir::Value genIOUnitNumber(Fortran::lower::AbstractConverter &converter, |
| 1774 |
mlir::Location loc, |
| 1775 |
const Fortran::lower::SomeExpr *iounit, |
| 1776 |
mlir::Type ty, ConditionSpecInfo &csi, |
| 1777 |
Fortran::lower::StatementContext &stmtCtx) { |
| 1778 |
auto &builder = converter.getFirOpBuilder(); |
| 1779 |
auto rawUnit = fir::getBase(converter.genExprValue(loc, iounit, stmtCtx)); |
| 1780 |
unsigned rawUnitWidth = |
| 1781 |
mlir::cast<mlir::IntegerType>(rawUnit.getType()).getWidth(); |
| 1782 |
unsigned runtimeArgWidth = mlir::cast<mlir::IntegerType>(ty).getWidth(); |
| 1783 |
// The IO runtime supports `int` unit numbers, if the unit number may |
| 1784 |
// overflow when passed to the IO runtime, check that the unit number is |
| 1785 |
// in range before calling the BeginXXX. |
| 1786 |
if (rawUnitWidth > runtimeArgWidth) { |
| 1787 |
mlir::func::FuncOp check = |
| 1788 |
rawUnitWidth <= 64 |
| 1789 |
? getIORuntimeFunc<mkIOKey(CheckUnitNumberInRange64)>(loc, builder) |
| 1790 |
: getIORuntimeFunc<mkIOKey(CheckUnitNumberInRange128)>(loc, |
| 1791 |
builder); |
| 1792 |
mlir::FunctionType funcTy = check.getFunctionType(); |
| 1793 |
llvm::SmallVector<mlir::Value> args; |
| 1794 |
args.push_back(builder.createConvert(loc, funcTy.getInput(0), rawUnit)); |
| 1795 |
args.push_back(builder.createBool(loc, csi.hasErrorConditionSpec())); |
| 1796 |
if (csi.ioMsg) { |
| 1797 |
args.push_back(builder.createConvert(loc, funcTy.getInput(2), |
| 1798 |
fir::getBase(*csi.ioMsg))); |
| 1799 |
args.push_back(builder.createConvert(loc, funcTy.getInput(3), |
| 1800 |
fir::getLen(*csi.ioMsg))); |
| 1801 |
} else { |
| 1802 |
args.push_back(builder.createNullConstant(loc, funcTy.getInput(2))); |
| 1803 |
args.push_back( |
| 1804 |
fir::factory::createZeroValue(builder, loc, funcTy.getInput(3))); |
| 1805 |
} |
| 1806 |
mlir::Value file = locToFilename(converter, loc, funcTy.getInput(4)); |
| 1807 |
mlir::Value line = locToLineNo(converter, loc, funcTy.getInput(5)); |
| 1808 |
args.push_back(file); |
| 1809 |
args.push_back(line); |
| 1810 |
auto checkCall = builder.create<fir::CallOp>(loc, check, args); |
| 1811 |
if (csi.hasErrorConditionSpec()) { |
| 1812 |
mlir::Value iostat = checkCall.getResult(0); |
| 1813 |
mlir::Type iostatTy = iostat.getType(); |
| 1814 |
mlir::Value zero = fir::factory::createZeroValue(builder, loc, iostatTy); |
| 1815 |
mlir::Value unitIsOK = builder.create<mlir::arith::CmpIOp>( |
| 1816 |
loc, mlir::arith::CmpIPredicate::eq, iostat, zero); |
| 1817 |
auto ifOp = builder.create<fir::IfOp>(loc, iostatTy, unitIsOK, |
| 1818 |
/*withElseRegion=*/true); |
| 1819 |
builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); |
| 1820 |
builder.create<fir::ResultOp>(loc, iostat); |
| 1821 |
builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); |
| 1822 |
stmtCtx.pushScope(); |
| 1823 |
csi.bigUnitIfOp = ifOp; |
| 1824 |
} |
| 1825 |
} |
| 1826 |
return builder.createConvert(loc, ty, rawUnit); |
| 1827 |
} |
| 1828 |
|
| 1829 |
static mlir::Value genIOUnit(Fortran::lower::AbstractConverter &converter, |
| 1830 |
mlir::Location loc, |
| 1831 |
const Fortran::parser::IoUnit *iounit, |
| 1832 |
mlir::Type ty, ConditionSpecInfo &csi, |
| 1833 |
Fortran::lower::StatementContext &stmtCtx, |
| 1834 |
int defaultUnitNumber) { |
| 1835 |
auto &builder = converter.getFirOpBuilder(); |
| 1836 |
if (iounit) |
| 1837 |
if (auto *e = std::get_if<Fortran::parser::FileUnitNumber>(&iounit->u)) |
| 1838 |
return genIOUnitNumber(converter, loc, Fortran::semantics::GetExpr(*e), |
| 1839 |
ty, csi, stmtCtx); |
| 1840 |
return builder.create<mlir::arith::ConstantOp>( |
| 1841 |
loc, builder.getIntegerAttr(ty, defaultUnitNumber)); |
| 1842 |
} |
| 1843 |
|
| 1844 |
template <typename A> |
| 1845 |
static mlir::Value |
| 1846 |
getIOUnit(Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1847 |
const A &stmt, mlir::Type ty, ConditionSpecInfo &csi, |
| 1848 |
Fortran::lower::StatementContext &stmtCtx, int defaultUnitNumber) { |
| 1849 |
const Fortran::parser::IoUnit *iounit = |
| 1850 |
stmt.iounit ? &*stmt.iounit : getIOControl<Fortran::parser::IoUnit>(stmt); |
| 1851 |
return genIOUnit(converter, loc, iounit, ty, csi, stmtCtx, defaultUnitNumber); |
| 1852 |
} |
| 1853 |
//===----------------------------------------------------------------------===// |
| 1854 |
// Generators for each IO statement type. |
| 1855 |
//===----------------------------------------------------------------------===// |
| 1856 |
|
| 1857 |
template <typename K, typename S> |
| 1858 |
static mlir::Value genBasicIOStmt(Fortran::lower::AbstractConverter &converter, |
| 1859 |
const S &stmt) { |
| 1860 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1861 |
Fortran::lower::StatementContext stmtCtx; |
| 1862 |
mlir::Location loc = converter.getCurrentLocation(); |
| 1863 |
ConditionSpecInfo csi = lowerErrorSpec(converter, loc, stmt.v); |
| 1864 |
mlir::func::FuncOp beginFunc = getIORuntimeFunc<K>(loc, builder); |
| 1865 |
mlir::FunctionType beginFuncTy = beginFunc.getFunctionType(); |
| 1866 |
mlir::Value unit = genIOUnitNumber( |
| 1867 |
converter, loc, getExpr<Fortran::parser::FileUnitNumber>(stmt), |
| 1868 |
beginFuncTy.getInput(0), csi, stmtCtx); |
| 1869 |
mlir::Value un = builder.createConvert(loc, beginFuncTy.getInput(0), unit); |
| 1870 |
mlir::Value file = locToFilename(converter, loc, beginFuncTy.getInput(1)); |
| 1871 |
mlir::Value line = locToLineNo(converter, loc, beginFuncTy.getInput(2)); |
| 1872 |
auto call = builder.create<fir::CallOp>(loc, beginFunc, |
| 1873 |
mlir::ValueRange{un, file, line}); |
| 1874 |
mlir::Value cookie = call.getResult(0); |
| 1875 |
genConditionHandlerCall(converter, loc, cookie, stmt.v, csi); |
| 1876 |
mlir::Value ok; |
| 1877 |
auto insertPt = builder.saveInsertionPoint(); |
| 1878 |
threadSpecs(converter, loc, cookie, stmt.v, csi.hasErrorConditionSpec(), ok); |
| 1879 |
builder.restoreInsertionPoint(insertPt); |
| 1880 |
return genEndIO(converter, converter.getCurrentLocation(), cookie, csi, |
| 1881 |
stmtCtx); |
| 1882 |
} |
| 1883 |
|
| 1884 |
mlir::Value Fortran::lower::genBackspaceStatement( |
| 1885 |
Fortran::lower::AbstractConverter &converter, |
| 1886 |
const Fortran::parser::BackspaceStmt &stmt) { |
| 1887 |
return genBasicIOStmt<mkIOKey(BeginBackspace)>(converter, stmt); |
| 1888 |
} |
| 1889 |
|
| 1890 |
mlir::Value Fortran::lower::genEndfileStatement( |
| 1891 |
Fortran::lower::AbstractConverter &converter, |
| 1892 |
const Fortran::parser::EndfileStmt &stmt) { |
| 1893 |
return genBasicIOStmt<mkIOKey(BeginEndfile)>(converter, stmt); |
| 1894 |
} |
| 1895 |
|
| 1896 |
mlir::Value |
| 1897 |
Fortran::lower::genFlushStatement(Fortran::lower::AbstractConverter &converter, |
| 1898 |
const Fortran::parser::FlushStmt &stmt) { |
| 1899 |
return genBasicIOStmt<mkIOKey(BeginFlush)>(converter, stmt); |
| 1900 |
} |
| 1901 |
|
| 1902 |
mlir::Value |
| 1903 |
Fortran::lower::genRewindStatement(Fortran::lower::AbstractConverter &converter, |
| 1904 |
const Fortran::parser::RewindStmt &stmt) { |
| 1905 |
return genBasicIOStmt<mkIOKey(BeginRewind)>(converter, stmt); |
| 1906 |
} |
| 1907 |
|
| 1908 |
static mlir::Value |
| 1909 |
genNewunitSpec(Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 1910 |
mlir::Value cookie, |
| 1911 |
const std::list<Fortran::parser::ConnectSpec> &specList) { |
| 1912 |
for (const auto &spec : specList) |
| 1913 |
if (auto *newunit = |
| 1914 |
std::get_if<Fortran::parser::ConnectSpec::Newunit>(&spec.u)) { |
| 1915 |
Fortran::lower::StatementContext stmtCtx; |
| 1916 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1917 |
mlir::func::FuncOp ioFunc = |
| 1918 |
getIORuntimeFunc<mkIOKey(GetNewUnit)>(loc, builder); |
| 1919 |
mlir::FunctionType ioFuncTy = ioFunc.getFunctionType(); |
| 1920 |
const auto *var = Fortran::semantics::GetExpr(newunit->v); |
| 1921 |
mlir::Value addr = builder.createConvert( |
| 1922 |
loc, ioFuncTy.getInput(1), |
| 1923 |
fir::getBase(converter.genExprAddr(loc, var, stmtCtx))); |
| 1924 |
auto kind = builder.createIntegerConstant(loc, ioFuncTy.getInput(2), |
| 1925 |
var->GetType().value().kind()); |
| 1926 |
llvm::SmallVector<mlir::Value> ioArgs = {cookie, addr, kind}; |
| 1927 |
return builder.create<fir::CallOp>(loc, ioFunc, ioArgs).getResult(0); |
| 1928 |
} |
| 1929 |
llvm_unreachable("missing Newunit spec"); |
| 1930 |
} |
| 1931 |
|
| 1932 |
mlir::Value |
| 1933 |
Fortran::lower::genOpenStatement(Fortran::lower::AbstractConverter &converter, |
| 1934 |
const Fortran::parser::OpenStmt &stmt) { |
| 1935 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1936 |
Fortran::lower::StatementContext stmtCtx; |
| 1937 |
mlir::func::FuncOp beginFunc; |
| 1938 |
llvm::SmallVector<mlir::Value> beginArgs; |
| 1939 |
mlir::Location loc = converter.getCurrentLocation(); |
| 1940 |
ConditionSpecInfo csi = lowerErrorSpec(converter, loc, stmt.v); |
| 1941 |
bool hasNewunitSpec = false; |
| 1942 |
if (hasSpec<Fortran::parser::FileUnitNumber>(stmt)) { |
| 1943 |
beginFunc = getIORuntimeFunc<mkIOKey(BeginOpenUnit)>(loc, builder); |
| 1944 |
mlir::FunctionType beginFuncTy = beginFunc.getFunctionType(); |
| 1945 |
mlir::Value unit = genIOUnitNumber( |
| 1946 |
converter, loc, getExpr<Fortran::parser::FileUnitNumber>(stmt), |
| 1947 |
beginFuncTy.getInput(0), csi, stmtCtx); |
| 1948 |
beginArgs.push_back(unit); |
| 1949 |
beginArgs.push_back(locToFilename(converter, loc, beginFuncTy.getInput(1))); |
| 1950 |
beginArgs.push_back(locToLineNo(converter, loc, beginFuncTy.getInput(2))); |
| 1951 |
} else { |
| 1952 |
hasNewunitSpec = hasSpec<Fortran::parser::ConnectSpec::Newunit>(stmt); |
| 1953 |
assert(hasNewunitSpec && "missing unit specifier"); |
| 1954 |
beginFunc = getIORuntimeFunc<mkIOKey(BeginOpenNewUnit)>(loc, builder); |
| 1955 |
mlir::FunctionType beginFuncTy = beginFunc.getFunctionType(); |
| 1956 |
beginArgs.push_back(locToFilename(converter, loc, beginFuncTy.getInput(0))); |
| 1957 |
beginArgs.push_back(locToLineNo(converter, loc, beginFuncTy.getInput(1))); |
| 1958 |
} |
| 1959 |
auto cookie = |
| 1960 |
builder.create<fir::CallOp>(loc, beginFunc, beginArgs).getResult(0); |
| 1961 |
genConditionHandlerCall(converter, loc, cookie, stmt.v, csi); |
| 1962 |
mlir::Value ok; |
| 1963 |
auto insertPt = builder.saveInsertionPoint(); |
| 1964 |
threadSpecs(converter, loc, cookie, stmt.v, csi.hasErrorConditionSpec(), ok); |
| 1965 |
if (hasNewunitSpec) |
| 1966 |
genNewunitSpec(converter, loc, cookie, stmt.v); |
| 1967 |
builder.restoreInsertionPoint(insertPt); |
| 1968 |
return genEndIO(converter, loc, cookie, csi, stmtCtx); |
| 1969 |
} |
| 1970 |
|
| 1971 |
mlir::Value |
| 1972 |
Fortran::lower::genCloseStatement(Fortran::lower::AbstractConverter &converter, |
| 1973 |
const Fortran::parser::CloseStmt &stmt) { |
| 1974 |
return genBasicIOStmt<mkIOKey(BeginClose)>(converter, stmt); |
| 1975 |
} |
| 1976 |
|
| 1977 |
mlir::Value |
| 1978 |
Fortran::lower::genWaitStatement(Fortran::lower::AbstractConverter &converter, |
| 1979 |
const Fortran::parser::WaitStmt &stmt) { |
| 1980 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 1981 |
Fortran::lower::StatementContext stmtCtx; |
| 1982 |
mlir::Location loc = converter.getCurrentLocation(); |
| 1983 |
ConditionSpecInfo csi = lowerErrorSpec(converter, loc, stmt.v); |
| 1984 |
bool hasId = hasSpec<Fortran::parser::IdExpr>(stmt); |
| 1985 |
mlir::func::FuncOp beginFunc = |
| 1986 |
hasId ? getIORuntimeFunc<mkIOKey(BeginWait)>(loc, builder) |
| 1987 |
: getIORuntimeFunc<mkIOKey(BeginWaitAll)>(loc, builder); |
| 1988 |
mlir::FunctionType beginFuncTy = beginFunc.getFunctionType(); |
| 1989 |
mlir::Value unit = genIOUnitNumber( |
| 1990 |
converter, loc, getExpr<Fortran::parser::FileUnitNumber>(stmt), |
| 1991 |
beginFuncTy.getInput(0), csi, stmtCtx); |
| 1992 |
llvm::SmallVector<mlir::Value> args{unit}; |
| 1993 |
if (hasId) { |
| 1994 |
mlir::Value id = fir::getBase(converter.genExprValue( |
| 1995 |
loc, getExpr<Fortran::parser::IdExpr>(stmt), stmtCtx)); |
| 1996 |
args.push_back(builder.createConvert(loc, beginFuncTy.getInput(1), id)); |
| 1997 |
args.push_back(locToFilename(converter, loc, beginFuncTy.getInput(2))); |
| 1998 |
args.push_back(locToLineNo(converter, loc, beginFuncTy.getInput(3))); |
| 1999 |
} else { |
| 2000 |
args.push_back(locToFilename(converter, loc, beginFuncTy.getInput(1))); |
| 2001 |
args.push_back(locToLineNo(converter, loc, beginFuncTy.getInput(2))); |
| 2002 |
} |
| 2003 |
auto cookie = builder.create<fir::CallOp>(loc, beginFunc, args).getResult(0); |
| 2004 |
genConditionHandlerCall(converter, loc, cookie, stmt.v, csi); |
| 2005 |
return genEndIO(converter, converter.getCurrentLocation(), cookie, csi, |
| 2006 |
stmtCtx); |
| 2007 |
} |
| 2008 |
|
| 2009 |
//===----------------------------------------------------------------------===// |
| 2010 |
// Data transfer statements. |
| 2011 |
// |
| 2012 |
// There are several dimensions to the API with regard to data transfer |
| 2013 |
// statements that need to be considered. |
| 2014 |
// |
| 2015 |
// - input (READ) vs. output (WRITE, PRINT) |
| 2016 |
// - unformatted vs. formatted vs. list vs. namelist |
| 2017 |
// - synchronous vs. asynchronous |
| 2018 |
// - external vs. internal |
| 2019 |
//===----------------------------------------------------------------------===// |
| 2020 |
|
| 2021 |
// Get the begin data transfer IO function to call for the given values. |
| 2022 |
template <bool isInput> |
| 2023 |
mlir::func::FuncOp |
| 2024 |
getBeginDataTransferFunc(mlir::Location loc, fir::FirOpBuilder &builder, |
| 2025 |
bool isFormatted, bool isListOrNml, bool isInternal, |
| 2026 |
bool isInternalWithDesc) { |
| 2027 |
if constexpr (isInput) { |
| 2028 |
if (isFormatted || isListOrNml) { |
| 2029 |
if (isInternal) { |
| 2030 |
if (isInternalWithDesc) { |
| 2031 |
if (isListOrNml) |
| 2032 |
return getIORuntimeFunc<mkIOKey(BeginInternalArrayListInput)>( |
| 2033 |
loc, builder); |
| 2034 |
return getIORuntimeFunc<mkIOKey(BeginInternalArrayFormattedInput)>( |
| 2035 |
loc, builder); |
| 2036 |
} |
| 2037 |
if (isListOrNml) |
| 2038 |
return getIORuntimeFunc<mkIOKey(BeginInternalListInput)>(loc, |
| 2039 |
builder); |
| 2040 |
return getIORuntimeFunc<mkIOKey(BeginInternalFormattedInput)>(loc, |
| 2041 |
builder); |
| 2042 |
} |
| 2043 |
if (isListOrNml) |
| 2044 |
return getIORuntimeFunc<mkIOKey(BeginExternalListInput)>(loc, builder); |
| 2045 |
return getIORuntimeFunc<mkIOKey(BeginExternalFormattedInput)>(loc, |
| 2046 |
builder); |
| 2047 |
} |
| 2048 |
return getIORuntimeFunc<mkIOKey(BeginUnformattedInput)>(loc, builder); |
| 2049 |
} else { |
| 2050 |
if (isFormatted || isListOrNml) { |
| 2051 |
if (isInternal) { |
| 2052 |
if (isInternalWithDesc) { |
| 2053 |
if (isListOrNml) |
| 2054 |
return getIORuntimeFunc<mkIOKey(BeginInternalArrayListOutput)>( |
| 2055 |
loc, builder); |
| 2056 |
return getIORuntimeFunc<mkIOKey(BeginInternalArrayFormattedOutput)>( |
| 2057 |
loc, builder); |
| 2058 |
} |
| 2059 |
if (isListOrNml) |
| 2060 |
return getIORuntimeFunc<mkIOKey(BeginInternalListOutput)>(loc, |
| 2061 |
builder); |
| 2062 |
return getIORuntimeFunc<mkIOKey(BeginInternalFormattedOutput)>(loc, |
| 2063 |
builder); |
| 2064 |
} |
| 2065 |
if (isListOrNml) |
| 2066 |
return getIORuntimeFunc<mkIOKey(BeginExternalListOutput)>(loc, builder); |
| 2067 |
return getIORuntimeFunc<mkIOKey(BeginExternalFormattedOutput)>(loc, |
| 2068 |
builder); |
| 2069 |
} |
| 2070 |
return getIORuntimeFunc<mkIOKey(BeginUnformattedOutput)>(loc, builder); |
| 2071 |
} |
| 2072 |
} |
| 2073 |
|
| 2074 |
/// Generate the arguments of a begin data transfer statement call. |
| 2075 |
template <bool hasIOCtrl, int defaultUnitNumber, typename A> |
| 2076 |
void genBeginDataTransferCallArgs( |
| 2077 |
llvm::SmallVectorImpl<mlir::Value> &ioArgs, |
| 2078 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 2079 |
const A &stmt, mlir::FunctionType ioFuncTy, bool isFormatted, |
| 2080 |
bool isListOrNml, [[maybe_unused]] bool isInternal, |
| 2081 |
const std::optional<fir::ExtendedValue> &descRef, ConditionSpecInfo &csi, |
| 2082 |
Fortran::lower::StatementContext &stmtCtx) { |
| 2083 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 2084 |
auto maybeGetFormatArgs = [&]() { |
| 2085 |
if (!isFormatted || isListOrNml) |
| 2086 |
return; |
| 2087 |
std::tuple triple = |
| 2088 |
getFormat(converter, loc, stmt, ioFuncTy.getInput(ioArgs.size()), |
| 2089 |
ioFuncTy.getInput(ioArgs.size() + 1), stmtCtx); |
| 2090 |
mlir::Value address = std::get<0>(triple); |
| 2091 |
mlir::Value length = std::get<1>(triple); |
| 2092 |
if (length) { |
| 2093 |
// Scalar format: string arg + length arg; no format descriptor arg |
| 2094 |
ioArgs.push_back(address); // format string |
| 2095 |
ioArgs.push_back(length); // format length |
| 2096 |
ioArgs.push_back( |
| 2097 |
builder.createNullConstant(loc, ioFuncTy.getInput(ioArgs.size()))); |
| 2098 |
return; |
| 2099 |
} |
| 2100 |
// Array format: no string arg, no length arg; format descriptor arg |
| 2101 |
ioArgs.push_back( |
| 2102 |
builder.createNullConstant(loc, ioFuncTy.getInput(ioArgs.size()))); |
| 2103 |
ioArgs.push_back( |
| 2104 |
builder.createNullConstant(loc, ioFuncTy.getInput(ioArgs.size()))); |
| 2105 |
ioArgs.push_back( // format descriptor |
| 2106 |
builder.createConvert(loc, ioFuncTy.getInput(ioArgs.size()), address)); |
| 2107 |
}; |
| 2108 |
if constexpr (hasIOCtrl) { // READ or WRITE |
| 2109 |
if (isInternal) { |
| 2110 |
// descriptor or scalar variable; maybe explicit format; scratch area |
| 2111 |
if (descRef) { |
| 2112 |
mlir::Value desc = builder.createBox(loc, *descRef); |
| 2113 |
ioArgs.push_back( |
| 2114 |
builder.createConvert(loc, ioFuncTy.getInput(ioArgs.size()), desc)); |
| 2115 |
} else { |
| 2116 |
std::tuple<mlir::Value, mlir::Value> pair = |
| 2117 |
getBuffer(converter, loc, stmt, ioFuncTy.getInput(ioArgs.size()), |
| 2118 |
ioFuncTy.getInput(ioArgs.size() + 1), stmtCtx); |
| 2119 |
ioArgs.push_back(std::get<0>(pair)); // scalar character variable |
| 2120 |
ioArgs.push_back(std::get<1>(pair)); // character length |
| 2121 |
} |
| 2122 |
maybeGetFormatArgs(); |
| 2123 |
ioArgs.push_back( // internal scratch area buffer |
| 2124 |
getDefaultScratch(builder, loc, ioFuncTy.getInput(ioArgs.size()))); |
| 2125 |
ioArgs.push_back( // buffer length |
| 2126 |
getDefaultScratchLen(builder, loc, ioFuncTy.getInput(ioArgs.size()))); |
| 2127 |
} else { // external IO - maybe explicit format; unit |
| 2128 |
maybeGetFormatArgs(); |
| 2129 |
ioArgs.push_back(getIOUnit(converter, loc, stmt, |
| 2130 |
ioFuncTy.getInput(ioArgs.size()), csi, stmtCtx, |
| 2131 |
defaultUnitNumber)); |
| 2132 |
} |
| 2133 |
} else { // PRINT - maybe explicit format; default unit |
| 2134 |
maybeGetFormatArgs(); |
| 2135 |
ioArgs.push_back(builder.create<mlir::arith::ConstantOp>( |
| 2136 |
loc, builder.getIntegerAttr(ioFuncTy.getInput(ioArgs.size()), |
| 2137 |
defaultUnitNumber))); |
| 2138 |
} |
| 2139 |
// File name and line number are always the last two arguments. |
| 2140 |
ioArgs.push_back( |
| 2141 |
locToFilename(converter, loc, ioFuncTy.getInput(ioArgs.size()))); |
| 2142 |
ioArgs.push_back( |
| 2143 |
locToLineNo(converter, loc, ioFuncTy.getInput(ioArgs.size()))); |
| 2144 |
} |
| 2145 |
|
| 2146 |
template <bool isInput, bool hasIOCtrl = true, typename A> |
| 2147 |
static mlir::Value |
| 2148 |
genDataTransferStmt(Fortran::lower::AbstractConverter &converter, |
| 2149 |
const A &stmt) { |
| 2150 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 2151 |
Fortran::lower::StatementContext stmtCtx; |
| 2152 |
mlir::Location loc = converter.getCurrentLocation(); |
| 2153 |
const bool isFormatted = isDataTransferFormatted(stmt); |
| 2154 |
const bool isList = isFormatted ? isDataTransferList(stmt) : false; |
| 2155 |
const bool isInternal = isDataTransferInternal(stmt); |
| 2156 |
std::optional<fir::ExtendedValue> descRef = |
| 2157 |
isInternal ? maybeGetInternalIODescriptor(converter, loc, stmt, stmtCtx) |
| 2158 |
: std::nullopt; |
| 2159 |
const bool isInternalWithDesc = descRef.has_value(); |
| 2160 |
const bool isNml = isDataTransferNamelist(stmt); |
| 2161 |
// Flang runtime currently implement asynchronous IO synchronously, so |
| 2162 |
// asynchronous IO statements are lowered as regular IO statements |
| 2163 |
// (except that GetAsynchronousId may be called to set the ID variable |
| 2164 |
// and SetAsynchronous will be call to tell the runtime that this is supposed |
| 2165 |
// to be (or not) an asynchronous IO statements). |
| 2166 |
|
| 2167 |
// Generate an EnableHandlers call and remaining specifier calls. |
| 2168 |
ConditionSpecInfo csi; |
| 2169 |
if constexpr (hasIOCtrl) { |
| 2170 |
csi = lowerErrorSpec(converter, loc, stmt.controls); |
| 2171 |
} |
| 2172 |
|
| 2173 |
// Generate the begin data transfer function call. |
| 2174 |
mlir::func::FuncOp ioFunc = getBeginDataTransferFunc<isInput>( |
| 2175 |
loc, builder, isFormatted, isList || isNml, isInternal, |
| 2176 |
isInternalWithDesc); |
| 2177 |
llvm::SmallVector<mlir::Value> ioArgs; |
| 2178 |
genBeginDataTransferCallArgs< |
| 2179 |
hasIOCtrl, isInput ? Fortran::runtime::io::DefaultInputUnit |
| 2180 |
: Fortran::runtime::io::DefaultOutputUnit>( |
| 2181 |
ioArgs, converter, loc, stmt, ioFunc.getFunctionType(), isFormatted, |
| 2182 |
isList || isNml, isInternal, descRef, csi, stmtCtx); |
| 2183 |
mlir::Value cookie = |
| 2184 |
builder.create<fir::CallOp>(loc, ioFunc, ioArgs).getResult(0); |
| 2185 |
|
| 2186 |
auto insertPt = builder.saveInsertionPoint(); |
| 2187 |
mlir::Value ok; |
| 2188 |
if constexpr (hasIOCtrl) { |
| 2189 |
genConditionHandlerCall(converter, loc, cookie, stmt.controls, csi); |
| 2190 |
threadSpecs(converter, loc, cookie, stmt.controls, |
| 2191 |
csi.hasErrorConditionSpec(), ok); |
| 2192 |
} |
| 2193 |
|
| 2194 |
// Generate data transfer list calls. |
| 2195 |
if constexpr (isInput) { // READ |
| 2196 |
if (isNml) |
| 2197 |
genNamelistIO(converter, cookie, |
| 2198 |
getIORuntimeFunc<mkIOKey(InputNamelist)>(loc, builder), |
| 2199 |
*getIOControl<Fortran::parser::Name>(stmt)->symbol, |
| 2200 |
csi.hasTransferConditionSpec(), ok, stmtCtx); |
| 2201 |
else |
| 2202 |
genInputItemList(converter, cookie, stmt.items, isFormatted, |
| 2203 |
csi.hasTransferConditionSpec(), ok, /*inLoop=*/false); |
| 2204 |
} else if constexpr (std::is_same_v<A, Fortran::parser::WriteStmt>) { |
| 2205 |
if (isNml) |
| 2206 |
genNamelistIO(converter, cookie, |
| 2207 |
getIORuntimeFunc<mkIOKey(OutputNamelist)>(loc, builder), |
| 2208 |
*getIOControl<Fortran::parser::Name>(stmt)->symbol, |
| 2209 |
csi.hasTransferConditionSpec(), ok, stmtCtx); |
| 2210 |
else |
| 2211 |
genOutputItemList(converter, cookie, stmt.items, isFormatted, |
| 2212 |
csi.hasTransferConditionSpec(), ok, |
| 2213 |
/*inLoop=*/false); |
| 2214 |
} else { // PRINT |
| 2215 |
genOutputItemList(converter, cookie, std::get<1>(stmt.t), isFormatted, |
| 2216 |
csi.hasTransferConditionSpec(), ok, |
| 2217 |
/*inLoop=*/false); |
| 2218 |
} |
| 2219 |
|
| 2220 |
builder.restoreInsertionPoint(insertPt); |
| 2221 |
if constexpr (hasIOCtrl) { |
| 2222 |
for (const auto &spec : stmt.controls) |
| 2223 |
if (const auto *size = |
| 2224 |
std::get_if<Fortran::parser::IoControlSpec::Size>(&spec.u)) { |
| 2225 |
// This call is not conditional on the current IO status (ok) because |
| 2226 |
// the size needs to be filled even if some error condition |
| 2227 |
// (end-of-file...) was met during the input statement (in which case |
| 2228 |
// the runtime may return zero for the size read). |
| 2229 |
genIOGetVar<mkIOKey(GetSize)>(converter, loc, cookie, *size); |
| 2230 |
} else if (const auto *idVar = |
| 2231 |
std::get_if<Fortran::parser::IdVariable>(&spec.u)) { |
| 2232 |
genIOGetVar<mkIOKey(GetAsynchronousId)>(converter, loc, cookie, *idVar); |
| 2233 |
} |
| 2234 |
} |
| 2235 |
// Generate end statement call/s. |
| 2236 |
mlir::Value result = genEndIO(converter, loc, cookie, csi, stmtCtx); |
| 2237 |
stmtCtx.finalizeAndReset(); |
| 2238 |
return result; |
| 2239 |
} |
| 2240 |
|
| 2241 |
void Fortran::lower::genPrintStatement( |
| 2242 |
Fortran::lower::AbstractConverter &converter, |
| 2243 |
const Fortran::parser::PrintStmt &stmt) { |
| 2244 |
// PRINT does not take an io-control-spec. It only has a format specifier, so |
| 2245 |
// it is a simplified case of WRITE. |
| 2246 |
genDataTransferStmt</*isInput=*/false, /*ioCtrl=*/false>(converter, stmt); |
| 2247 |
} |
| 2248 |
|
| 2249 |
mlir::Value |
| 2250 |
Fortran::lower::genWriteStatement(Fortran::lower::AbstractConverter &converter, |
| 2251 |
const Fortran::parser::WriteStmt &stmt) { |
| 2252 |
return genDataTransferStmt</*isInput=*/false>(converter, stmt); |
| 2253 |
} |
| 2254 |
|
| 2255 |
mlir::Value |
| 2256 |
Fortran::lower::genReadStatement(Fortran::lower::AbstractConverter &converter, |
| 2257 |
const Fortran::parser::ReadStmt &stmt) { |
| 2258 |
return genDataTransferStmt</*isInput=*/true>(converter, stmt); |
| 2259 |
} |
| 2260 |
|
| 2261 |
/// Get the file expression from the inquire spec list. Also return if the |
| 2262 |
/// expression is a file name. |
| 2263 |
static std::pair<const Fortran::lower::SomeExpr *, bool> |
| 2264 |
getInquireFileExpr(const std::list<Fortran::parser::InquireSpec> *stmt) { |
| 2265 |
if (!stmt) |
| 2266 |
return {nullptr, /*filename?=*/false}; |
| 2267 |
for (const Fortran::parser::InquireSpec &spec : *stmt) { |
| 2268 |
if (auto *f = std::get_if<Fortran::parser::FileUnitNumber>(&spec.u)) |
| 2269 |
return {Fortran::semantics::GetExpr(*f), /*filename?=*/false}; |
| 2270 |
if (auto *f = std::get_if<Fortran::parser::FileNameExpr>(&spec.u)) |
| 2271 |
return {Fortran::semantics::GetExpr(*f), /*filename?=*/true}; |
| 2272 |
} |
| 2273 |
// semantics should have already caught this condition |
| 2274 |
llvm::report_fatal_error("inquire spec must have a file"); |
| 2275 |
} |
| 2276 |
|
| 2277 |
/// Generate calls to the four distinct INQUIRE subhandlers. An INQUIRE may |
| 2278 |
/// return values of type CHARACTER, INTEGER, or LOGICAL. There is one |
| 2279 |
/// additional special case for INQUIRE with both PENDING and ID specifiers. |
| 2280 |
template <typename A> |
| 2281 |
static mlir::Value genInquireSpec(Fortran::lower::AbstractConverter &converter, |
| 2282 |
mlir::Location loc, mlir::Value cookie, |
| 2283 |
mlir::Value idExpr, const A &var, |
| 2284 |
Fortran::lower::StatementContext &stmtCtx) { |
| 2285 |
// default case: do nothing |
| 2286 |
return {}; |
| 2287 |
} |
| 2288 |
/// Specialization for CHARACTER. |
| 2289 |
template <> |
| 2290 |
mlir::Value genInquireSpec<Fortran::parser::InquireSpec::CharVar>( |
| 2291 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 2292 |
mlir::Value cookie, mlir::Value idExpr, |
| 2293 |
const Fortran::parser::InquireSpec::CharVar &var, |
| 2294 |
Fortran::lower::StatementContext &stmtCtx) { |
| 2295 |
// IOMSG is handled with exception conditions |
| 2296 |
if (std::get<Fortran::parser::InquireSpec::CharVar::Kind>(var.t) == |
| 2297 |
Fortran::parser::InquireSpec::CharVar::Kind::Iomsg) |
| 2298 |
return {}; |
| 2299 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 2300 |
mlir::func::FuncOp specFunc = |
| 2301 |
getIORuntimeFunc<mkIOKey(InquireCharacter)>(loc, builder); |
| 2302 |
mlir::FunctionType specFuncTy = specFunc.getFunctionType(); |
| 2303 |
const auto *varExpr = Fortran::semantics::GetExpr( |
| 2304 |
std::get<Fortran::parser::ScalarDefaultCharVariable>(var.t)); |
| 2305 |
fir::ExtendedValue str = converter.genExprAddr(loc, varExpr, stmtCtx); |
| 2306 |
llvm::SmallVector<mlir::Value> args = { |
| 2307 |
builder.createConvert(loc, specFuncTy.getInput(0), cookie), |
| 2308 |
builder.createIntegerConstant( |
| 2309 |
loc, specFuncTy.getInput(1), |
| 2310 |
Fortran::runtime::io::HashInquiryKeyword(std::string{ |
| 2311 |
Fortran::parser::InquireSpec::CharVar::EnumToString( |
| 2312 |
std::get<Fortran::parser::InquireSpec::CharVar::Kind>(var.t))} |
| 2313 |
.c_str())), |
| 2314 |
builder.createConvert(loc, specFuncTy.getInput(2), fir::getBase(str)), |
| 2315 |
builder.createConvert(loc, specFuncTy.getInput(3), fir::getLen(str))}; |
| 2316 |
return builder.create<fir::CallOp>(loc, specFunc, args).getResult(0); |
| 2317 |
} |
| 2318 |
/// Specialization for INTEGER. |
| 2319 |
template <> |
| 2320 |
mlir::Value genInquireSpec<Fortran::parser::InquireSpec::IntVar>( |
| 2321 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 2322 |
mlir::Value cookie, mlir::Value idExpr, |
| 2323 |
const Fortran::parser::InquireSpec::IntVar &var, |
| 2324 |
Fortran::lower::StatementContext &stmtCtx) { |
| 2325 |
// IOSTAT is handled with exception conditions |
| 2326 |
if (std::get<Fortran::parser::InquireSpec::IntVar::Kind>(var.t) == |
| 2327 |
Fortran::parser::InquireSpec::IntVar::Kind::Iostat) |
| 2328 |
return {}; |
| 2329 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 2330 |
mlir::func::FuncOp specFunc = |
| 2331 |
getIORuntimeFunc<mkIOKey(InquireInteger64)>(loc, builder); |
| 2332 |
mlir::FunctionType specFuncTy = specFunc.getFunctionType(); |
| 2333 |
const auto *varExpr = Fortran::semantics::GetExpr( |
| 2334 |
std::get<Fortran::parser::ScalarIntVariable>(var.t)); |
| 2335 |
mlir::Value addr = fir::getBase(converter.genExprAddr(loc, varExpr, stmtCtx)); |
| 2336 |
mlir::Type eleTy = fir::dyn_cast_ptrEleTy(addr.getType()); |
| 2337 |
if (!eleTy) |
| 2338 |
fir::emitFatalError(loc, |
| 2339 |
"internal error: expected a memory reference type"); |
| 2340 |
auto width = mlir::cast<mlir::IntegerType>(eleTy).getWidth(); |
| 2341 |
mlir::IndexType idxTy = builder.getIndexType(); |
| 2342 |
mlir::Value kind = builder.createIntegerConstant(loc, idxTy, width / 8); |
| 2343 |
llvm::SmallVector<mlir::Value> args = { |
| 2344 |
builder.createConvert(loc, specFuncTy.getInput(0), cookie), |
| 2345 |
builder.createIntegerConstant( |
| 2346 |
loc, specFuncTy.getInput(1), |
| 2347 |
Fortran::runtime::io::HashInquiryKeyword(std::string{ |
| 2348 |
Fortran::parser::InquireSpec::IntVar::EnumToString( |
| 2349 |
std::get<Fortran::parser::InquireSpec::IntVar::Kind>(var.t))} |
| 2350 |
.c_str())), |
| 2351 |
builder.createConvert(loc, specFuncTy.getInput(2), addr), |
| 2352 |
builder.createConvert(loc, specFuncTy.getInput(3), kind)}; |
| 2353 |
return builder.create<fir::CallOp>(loc, specFunc, args).getResult(0); |
| 2354 |
} |
| 2355 |
/// Specialization for LOGICAL and (PENDING + ID). |
| 2356 |
template <> |
| 2357 |
mlir::Value genInquireSpec<Fortran::parser::InquireSpec::LogVar>( |
| 2358 |
Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 2359 |
mlir::Value cookie, mlir::Value idExpr, |
| 2360 |
const Fortran::parser::InquireSpec::LogVar &var, |
| 2361 |
Fortran::lower::StatementContext &stmtCtx) { |
| 2362 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 2363 |
auto logVarKind = std::get<Fortran::parser::InquireSpec::LogVar::Kind>(var.t); |
| 2364 |
bool pendId = |
| 2365 |
idExpr && |
| 2366 |
logVarKind == Fortran::parser::InquireSpec::LogVar::Kind::Pending; |
| 2367 |
mlir::func::FuncOp specFunc = |
| 2368 |
pendId ? getIORuntimeFunc<mkIOKey(InquirePendingId)>(loc, builder) |
| 2369 |
: getIORuntimeFunc<mkIOKey(InquireLogical)>(loc, builder); |
| 2370 |
mlir::FunctionType specFuncTy = specFunc.getFunctionType(); |
| 2371 |
mlir::Value addr = fir::getBase(converter.genExprAddr( |
| 2372 |
loc, |
| 2373 |
Fortran::semantics::GetExpr( |
| 2374 |
std::get<Fortran::parser::Scalar< |
| 2375 |
Fortran::parser::Logical<Fortran::parser::Variable>>>(var.t)), |
| 2376 |
stmtCtx)); |
| 2377 |
llvm::SmallVector<mlir::Value> args = { |
| 2378 |
builder.createConvert(loc, specFuncTy.getInput(0), cookie)}; |
| 2379 |
if (pendId) |
| 2380 |
args.push_back(builder.createConvert(loc, specFuncTy.getInput(1), idExpr)); |
| 2381 |
else |
| 2382 |
args.push_back(builder.createIntegerConstant( |
| 2383 |
loc, specFuncTy.getInput(1), |
| 2384 |
Fortran::runtime::io::HashInquiryKeyword(std::string{ |
| 2385 |
Fortran::parser::InquireSpec::LogVar::EnumToString(logVarKind)} |
| 2386 |
.c_str()))); |
| 2387 |
args.push_back(builder.createConvert(loc, specFuncTy.getInput(2), addr)); |
| 2388 |
auto call = builder.create<fir::CallOp>(loc, specFunc, args); |
| 2389 |
boolRefToLogical(loc, builder, addr); |
| 2390 |
return call.getResult(0); |
| 2391 |
} |
| 2392 |
|
| 2393 |
/// If there is an IdExpr in the list of inquire-specs, then lower it and return |
| 2394 |
/// the resulting Value. Otherwise, return null. |
| 2395 |
static mlir::Value |
| 2396 |
lowerIdExpr(Fortran::lower::AbstractConverter &converter, mlir::Location loc, |
| 2397 |
const std::list<Fortran::parser::InquireSpec> &ispecs, |
| 2398 |
Fortran::lower::StatementContext &stmtCtx) { |
| 2399 |
for (const Fortran::parser::InquireSpec &spec : ispecs) |
| 2400 |
if (mlir::Value v = Fortran::common::visit( |
| 2401 |
Fortran::common::visitors{ |
| 2402 |
[&](const Fortran::parser::IdExpr &idExpr) { |
| 2403 |
return fir::getBase(converter.genExprValue( |
| 2404 |
loc, Fortran::semantics::GetExpr(idExpr), stmtCtx)); |
| 2405 |
}, |
| 2406 |
[](const auto &) { return mlir::Value{}; }}, |
| 2407 |
spec.u)) |
| 2408 |
return v; |
| 2409 |
return {}; |
| 2410 |
} |
| 2411 |
|
| 2412 |
/// For each inquire-spec, build the appropriate call, threading the cookie. |
| 2413 |
static void threadInquire(Fortran::lower::AbstractConverter &converter, |
| 2414 |
mlir::Location loc, mlir::Value cookie, |
| 2415 |
const std::list<Fortran::parser::InquireSpec> &ispecs, |
| 2416 |
bool checkResult, mlir::Value &ok, |
| 2417 |
Fortran::lower::StatementContext &stmtCtx) { |
| 2418 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 2419 |
mlir::Value idExpr = lowerIdExpr(converter, loc, ispecs, stmtCtx); |
| 2420 |
for (const Fortran::parser::InquireSpec &spec : ispecs) { |
| 2421 |
makeNextConditionalOn(builder, loc, checkResult, ok); |
| 2422 |
ok = Fortran::common::visit(Fortran::common::visitors{[&](const auto &x) { |
| 2423 |
return genInquireSpec(converter, loc, cookie, |
| 2424 |
idExpr, x, stmtCtx); |
| 2425 |
}}, |
| 2426 |
spec.u); |
| 2427 |
} |
| 2428 |
} |
| 2429 |
|
| 2430 |
mlir::Value Fortran::lower::genInquireStatement( |
| 2431 |
Fortran::lower::AbstractConverter &converter, |
| 2432 |
const Fortran::parser::InquireStmt &stmt) { |
| 2433 |
fir::FirOpBuilder &builder = converter.getFirOpBuilder(); |
| 2434 |
Fortran::lower::StatementContext stmtCtx; |
| 2435 |
mlir::Location loc = converter.getCurrentLocation(); |
| 2436 |
mlir::func::FuncOp beginFunc; |
| 2437 |
llvm::SmallVector<mlir::Value> beginArgs; |
| 2438 |
const auto *list = |
| 2439 |
std::get_if<std::list<Fortran::parser::InquireSpec>>(&stmt.u); |
| 2440 |
auto exprPair = getInquireFileExpr(list); |
| 2441 |
auto inquireFileUnit = [&]() -> bool { |
| 2442 |
return exprPair.first && !exprPair.second; |
| 2443 |
}; |
| 2444 |
auto inquireFileName = [&]() -> bool { |
| 2445 |
return exprPair.first && exprPair.second; |
| 2446 |
}; |
| 2447 |
|
| 2448 |
ConditionSpecInfo csi = |
| 2449 |
list ? lowerErrorSpec(converter, loc, *list) : ConditionSpecInfo{}; |
| 2450 |
|
| 2451 |
// Make one of three BeginInquire calls. |
| 2452 |
if (inquireFileUnit()) { |
| 2453 |
// Inquire by unit -- [UNIT=]file-unit-number. |
| 2454 |
beginFunc = getIORuntimeFunc<mkIOKey(BeginInquireUnit)>(loc, builder); |
| 2455 |
mlir::FunctionType beginFuncTy = beginFunc.getFunctionType(); |
| 2456 |
mlir::Value unit = genIOUnitNumber(converter, loc, exprPair.first, |
| 2457 |
beginFuncTy.getInput(0), csi, stmtCtx); |
| 2458 |
beginArgs = {unit, locToFilename(converter, loc, beginFuncTy.getInput(1)), |
| 2459 |
locToLineNo(converter, loc, beginFuncTy.getInput(2))}; |
| 2460 |
} else if (inquireFileName()) { |
| 2461 |
// Inquire by file -- FILE=file-name-expr. |
| 2462 |
beginFunc = getIORuntimeFunc<mkIOKey(BeginInquireFile)>(loc, builder); |
| 2463 |
mlir::FunctionType beginFuncTy = beginFunc.getFunctionType(); |
| 2464 |
fir::ExtendedValue file = |
| 2465 |
converter.genExprAddr(loc, exprPair.first, stmtCtx); |
| 2466 |
beginArgs = { |
| 2467 |
builder.createConvert(loc, beginFuncTy.getInput(0), fir::getBase(file)), |
| 2468 |
builder.createConvert(loc, beginFuncTy.getInput(1), fir::getLen(file)), |
| 2469 |
locToFilename(converter, loc, beginFuncTy.getInput(2)), |
| 2470 |
locToLineNo(converter, loc, beginFuncTy.getInput(3))}; |
| 2471 |
} else { |
| 2472 |
// Inquire by output list -- IOLENGTH=scalar-int-variable. |
| 2473 |
const auto *ioLength = |
| 2474 |
std::get_if<Fortran::parser::InquireStmt::Iolength>(&stmt.u); |
| 2475 |
assert(ioLength && "must have an IOLENGTH specifier"); |
| 2476 |
beginFunc = getIORuntimeFunc<mkIOKey(BeginInquireIoLength)>(loc, builder); |
| 2477 |
mlir::FunctionType beginFuncTy = beginFunc.getFunctionType(); |
| 2478 |
beginArgs = {locToFilename(converter, loc, beginFuncTy.getInput(0)), |
| 2479 |
locToLineNo(converter, loc, beginFuncTy.getInput(1))}; |
| 2480 |
auto cookie = |
| 2481 |
builder.create<fir::CallOp>(loc, beginFunc, beginArgs).getResult(0); |
| 2482 |
mlir::Value ok; |
| 2483 |
genOutputItemList( |
| 2484 |
converter, cookie, |
| 2485 |
std::get<std::list<Fortran::parser::OutputItem>>(ioLength->t), |
| 2486 |
/*isFormatted=*/false, /*checkResult=*/false, ok, /*inLoop=*/false); |
| 2487 |
auto *ioLengthVar = Fortran::semantics::GetExpr( |
| 2488 |
std::get<Fortran::parser::ScalarIntVariable>(ioLength->t)); |
| 2489 |
mlir::Value ioLengthVarAddr = |
| 2490 |
fir::getBase(converter.genExprAddr(loc, ioLengthVar, stmtCtx)); |
| 2491 |
llvm::SmallVector<mlir::Value> args = {cookie}; |
| 2492 |
mlir::Value length = |
| 2493 |
builder |
| 2494 |
.create<fir::CallOp>( |
| 2495 |
loc, getIORuntimeFunc<mkIOKey(GetIoLength)>(loc, builder), args) |
| 2496 |
.getResult(0); |
| 2497 |
mlir::Value length1 = |
| 2498 |
builder.createConvert(loc, converter.genType(*ioLengthVar), length); |
| 2499 |
builder.create<fir::StoreOp>(loc, length1, ioLengthVarAddr); |
| 2500 |
return genEndIO(converter, loc, cookie, csi, stmtCtx); |
| 2501 |
} |
| 2502 |
|
| 2503 |
// Common handling for inquire by unit or file. |
| 2504 |
assert(list && "inquire-spec list must be present"); |
| 2505 |
auto cookie = |
| 2506 |
builder.create<fir::CallOp>(loc, beginFunc, beginArgs).getResult(0); |
| 2507 |
genConditionHandlerCall(converter, loc, cookie, *list, csi); |
| 2508 |
// Handle remaining arguments in specifier list. |
| 2509 |
mlir::Value ok; |
| 2510 |
auto insertPt = builder.saveInsertionPoint(); |
| 2511 |
threadInquire(converter, loc, cookie, *list, csi.hasErrorConditionSpec(), ok, |
| 2512 |
stmtCtx); |
| 2513 |
builder.restoreInsertionPoint(insertPt); |
| 2514 |
// Generate end statement call. |
| 2515 |
return genEndIO(converter, loc, cookie, csi, stmtCtx); |
| 2516 |
} |