FLANG
io-api.h
1//===-- include/flang/Runtime/io-api.h --------------------------*- C++ -*-===//
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// Defines the API of the I/O runtime support library for lowering.
10
11#ifndef FORTRAN_RUNTIME_IO_API_H_
12#define FORTRAN_RUNTIME_IO_API_H_
13
14#include "flang/Common/uint128.h"
15#include "flang/Runtime/entry-names.h"
16#include "flang/Runtime/iostat-consts.h"
17#include "flang/Runtime/magic-numbers.h"
18#include <cinttypes>
19#include <cstddef>
20
21namespace Fortran::runtime {
22class Descriptor;
23} // namespace Fortran::runtime
24
25namespace Fortran::runtime::io {
26
27struct NonTbpDefinedIoTable;
28class NamelistGroup;
29class IoStatementState;
30using Cookie = IoStatementState *;
31using ExternalUnit = int;
32using AsynchronousId = int;
33
34static constexpr ExternalUnit DefaultOutputUnit{FORTRAN_DEFAULT_OUTPUT_UNIT};
35static constexpr ExternalUnit DefaultInputUnit{FORTRAN_DEFAULT_INPUT_UNIT};
36
37// INQUIRE specifiers are encoded as simple base-26 packings of
38// the spellings of their keywords.
39using InquiryKeywordHash = std::uint64_t;
40constexpr InquiryKeywordHash HashInquiryKeyword(const char *p) {
41 InquiryKeywordHash hash{1};
42 while (char ch{*p++}) {
43 std::uint64_t letter{0};
44 if (ch >= 'a' && ch <= 'z') {
45 letter = ch - 'a';
46 } else {
47 letter = ch - 'A';
48 }
49 hash = 26 * hash + letter;
50 }
51 return hash;
52}
53
54extern "C" {
55
56#define IONAME(name) RTNAME(io##name)
57
58#ifndef IODECL
59#define IODECL(name) RT_API_ATTRS IONAME(name)
60#endif
61
62#ifndef IODEF
63#define IODEF(name) RT_API_ATTRS IONAME(name)
64#endif
65
66// These functions initiate data transfer statements (READ, WRITE, PRINT).
67// Example: PRINT *, 666 is implemented as the series of calls:
68// Cookie cookie{BeginExternalListOutput(DefaultOutputUnit,
69// __FILE__, __LINE__)};
70// OutputInteger32(cookie, 666);
71// EndIoStatement(cookie);
72// Formatted I/O with explicit formats can supply the format as a
73// const char * pointer with a length, or with a descriptor.
74
75// Internal I/O initiation
76// Internal I/O can loan the runtime library an optional block of memory
77// in which the library can maintain state across the calls that implement
78// the internal transfer; use of these blocks can reduce the need for dynamic
79// memory allocation &/or thread-local storage. The block must be sufficiently
80// aligned to hold a pointer.
81constexpr std::size_t RecommendedInternalIoScratchAreaBytes(
82 int maxFormatParenthesesNestingDepth) {
83 return 32 + 8 * maxFormatParenthesesNestingDepth;
84}
85
86// For NAMELIST I/O, use the API for the appropriate form of list-directed
87// I/O initiation and configuration, then call OutputNamelist/InputNamelist
88// below.
89
90// Internal I/O to/from character arrays &/or non-default-kind character
91// requires a descriptor, which is copied.
92Cookie IODECL(BeginInternalArrayListOutput)(const Descriptor &,
93 void **scratchArea = nullptr, std::size_t scratchBytes = 0,
94 const char *sourceFile = nullptr, int sourceLine = 0);
95Cookie IODECL(BeginInternalArrayListInput)(const Descriptor &,
96 void **scratchArea = nullptr, std::size_t scratchBytes = 0,
97 const char *sourceFile = nullptr, int sourceLine = 0);
98Cookie IODECL(BeginInternalArrayFormattedOutput)(const Descriptor &,
99 const char *format, std::size_t formatLength,
100 const Descriptor *formatDescriptor = nullptr, void **scratchArea = nullptr,
101 std::size_t scratchBytes = 0, const char *sourceFile = nullptr,
102 int sourceLine = 0);
103Cookie IODECL(BeginInternalArrayFormattedInput)(const Descriptor &,
104 const char *format, std::size_t formatLength,
105 const Descriptor *formatDescriptor = nullptr, void **scratchArea = nullptr,
106 std::size_t scratchBytes = 0, const char *sourceFile = nullptr,
107 int sourceLine = 0);
108
109// Internal I/O to/from a default-kind character scalar can avoid a
110// descriptor.
111Cookie IODECL(BeginInternalListOutput)(char *internal,
112 std::size_t internalLength, void **scratchArea = nullptr,
113 std::size_t scratchBytes = 0, const char *sourceFile = nullptr,
114 int sourceLine = 0);
115Cookie IODECL(BeginInternalListInput)(const char *internal,
116 std::size_t internalLength, void **scratchArea = nullptr,
117 std::size_t scratchBytes = 0, const char *sourceFile = nullptr,
118 int sourceLine = 0);
119Cookie IODECL(BeginInternalFormattedOutput)(char *internal,
120 std::size_t internalLength, const char *format, std::size_t formatLength,
121 const Descriptor *formatDescriptor = nullptr, void **scratchArea = nullptr,
122 std::size_t scratchBytes = 0, const char *sourceFile = nullptr,
123 int sourceLine = 0);
124Cookie IODECL(BeginInternalFormattedInput)(const char *internal,
125 std::size_t internalLength, const char *format, std::size_t formatLength,
126 const Descriptor *formatDescriptor = nullptr, void **scratchArea = nullptr,
127 std::size_t scratchBytes = 0, const char *sourceFile = nullptr,
128 int sourceLine = 0);
129
130// External unit numbers must fit in default integers. When the integer
131// provided as UNIT is of a wider type than the default integer, it could
132// overflow when converted to a default integer.
133// CheckUnitNumberInRange should be called to verify that a unit number of a
134// wide integer type can fit in a default integer. Since it should be called
135// before the BeginXXX(unit, ...) call, it has its own error handling interface.
136// If handleError is false, and the unit number is out of range, the program
137// will be terminated. Otherwise, if unit is out of range, a nonzero Iostat
138// code is returned and ioMsg is set if it is not a nullptr.
139enum Iostat IODECL(CheckUnitNumberInRange64)(std::int64_t unit,
140 bool handleError, char *ioMsg = nullptr, std::size_t ioMsgLength = 0,
141 const char *sourceFile = nullptr, int sourceLine = 0);
142enum Iostat IODECL(CheckUnitNumberInRange128)(common::int128_t unit,
143 bool handleError, char *ioMsg = nullptr, std::size_t ioMsgLength = 0,
144 const char *sourceFile = nullptr, int sourceLine = 0);
145
146// External synchronous I/O initiation
147Cookie IODECL(BeginExternalListOutput)(ExternalUnit = DefaultOutputUnit,
148 const char *sourceFile = nullptr, int sourceLine = 0);
149Cookie IODECL(BeginExternalListInput)(ExternalUnit = DefaultInputUnit,
150 const char *sourceFile = nullptr, int sourceLine = 0);
151Cookie IODECL(BeginExternalFormattedOutput)(const char *format, std::size_t,
152 const Descriptor *formatDescriptor = nullptr,
153 ExternalUnit = DefaultOutputUnit, const char *sourceFile = nullptr,
154 int sourceLine = 0);
155Cookie IODECL(BeginExternalFormattedInput)(const char *format, std::size_t,
156 const Descriptor *formatDescriptor = nullptr,
157 ExternalUnit = DefaultInputUnit, const char *sourceFile = nullptr,
158 int sourceLine = 0);
159Cookie IODECL(BeginUnformattedOutput)(ExternalUnit = DefaultOutputUnit,
160 const char *sourceFile = nullptr, int sourceLine = 0);
161Cookie IODECL(BeginUnformattedInput)(ExternalUnit = DefaultInputUnit,
162 const char *sourceFile = nullptr, int sourceLine = 0);
163
164// WAIT(ID=)
165Cookie IODECL(BeginWait)(ExternalUnit, AsynchronousId,
166 const char *sourceFile = nullptr, int sourceLine = 0);
167// WAIT(no ID=)
168Cookie IODECL(BeginWaitAll)(
169 ExternalUnit, const char *sourceFile = nullptr, int sourceLine = 0);
170
171// Other I/O statements
172Cookie IODECL(BeginClose)(
173 ExternalUnit, const char *sourceFile = nullptr, int sourceLine = 0);
174Cookie IODECL(BeginFlush)(
175 ExternalUnit, const char *sourceFile = nullptr, int sourceLine = 0);
176Cookie IODECL(BeginBackspace)(
177 ExternalUnit, const char *sourceFile = nullptr, int sourceLine = 0);
178Cookie IODECL(BeginEndfile)(
179 ExternalUnit, const char *sourceFile = nullptr, int sourceLine = 0);
180Cookie IODECL(BeginRewind)(
181 ExternalUnit, const char *sourceFile = nullptr, int sourceLine = 0);
182
183// OPEN(UNIT=) and OPEN(NEWUNIT=) have distinct interfaces.
184Cookie IODECL(BeginOpenUnit)(
185 ExternalUnit, const char *sourceFile = nullptr, int sourceLine = 0);
186Cookie IODECL(BeginOpenNewUnit)(
187 const char *sourceFile = nullptr, int sourceLine = 0);
188
189// The variant forms of INQUIRE() statements have distinct interfaces.
190// BeginInquireIoLength() is basically a no-op output statement.
191Cookie IODECL(BeginInquireUnit)(
192 ExternalUnit, const char *sourceFile = nullptr, int sourceLine = 0);
193Cookie IODECL(BeginInquireFile)(const char *, std::size_t,
194 const char *sourceFile = nullptr, int sourceLine = 0);
195Cookie IODECL(BeginInquireIoLength)(
196 const char *sourceFile = nullptr, int sourceLine = 0);
197
198// If an I/O statement has any IOSTAT=, ERR=, END=, or EOR= specifiers,
199// call EnableHandlers() immediately after the Begin...() call.
200// An output or OPEN statement may not enable HasEnd or HasEor.
201// This call makes the runtime library defer those particular error/end
202// conditions to the EndIoStatement() call rather than terminating
203// the image. E.g., for READ(*,*,END=666) A, B, (C(J),J=1,N)
204// Cookie cookie{BeginExternalListInput(DefaultInputUnit,__FILE__,__LINE__)};
205// EnableHandlers(cookie, false, false, true /*END=*/, false);
206// if (InputReal64(cookie, &A)) {
207// if (InputReal64(cookie, &B)) {
208// for (int J{1}; J<=N; ++J) {
209// if (!InputReal64(cookie, &C[J])) break;
210// }
211// }
212// }
213// if (EndIoStatement(cookie) == FORTRAN_RUTIME_IOSTAT_END) goto label666;
214void IODECL(EnableHandlers)(Cookie, bool hasIoStat = false, bool hasErr = false,
215 bool hasEnd = false, bool hasEor = false, bool hasIoMsg = false);
216
217// ASYNCHRONOUS='YES' or 'NO' on READ/WRITE/OPEN
218// Use GetAsynchronousId() to handle ID=.
219bool IODECL(SetAsynchronous)(Cookie, const char *, std::size_t);
220
221// Control list options. These return false on a error that the
222// Begin...() call has specified will be handled by the caller.
223// The interfaces that pass a default-kind CHARACTER argument
224// are limited to passing specific case-insensitive keyword values.
225// ADVANCE=YES, NO
226bool IODECL(SetAdvance)(Cookie, const char *, std::size_t);
227// BLANK=NULL, ZERO
228bool IODECL(SetBlank)(Cookie, const char *, std::size_t);
229// DECIMAL=COMMA, POINT
230bool IODECL(SetDecimal)(Cookie, const char *, std::size_t);
231// DELIM=APOSTROPHE, QUOTE, NONE
232bool IODECL(SetDelim)(Cookie, const char *, std::size_t);
233// PAD=YES, NO
234bool IODECL(SetPad)(Cookie, const char *, std::size_t);
235bool IODECL(SetPos)(Cookie, std::int64_t);
236bool IODECL(SetRec)(Cookie, std::int64_t);
237// ROUND=UP, DOWN, ZERO, NEAREST, COMPATIBLE, PROCESSOR_DEFINED
238bool IODECL(SetRound)(Cookie, const char *, std::size_t);
239// SIGN=PLUS, SUPPRESS, PROCESSOR_DEFINED
240bool IODECL(SetSign)(Cookie, const char *, std::size_t);
241
242// Data item transfer for modes other than NAMELIST:
243// Any data object that can be passed as an actual argument without the
244// use of a temporary can be transferred by means of a descriptor;
245// vector-valued subscripts and coindexing will require elementwise
246// transfers &/or data copies. Unformatted transfers to/from contiguous
247// blocks of local image memory can avoid the descriptor, and there
248// are specializations for the most common scalar types.
249//
250// These functions return false when the I/O statement has encountered an
251// error or end-of-file/record condition that the caller has indicated
252// should not cause termination of the image by the runtime library.
253// Once the statement has encountered an error, all following items will be
254// ignored and also return false; but compiled code should check for errors
255// and avoid the following items when they might crash.
256bool IODECL(OutputDescriptor)(Cookie, const Descriptor &);
257bool IODECL(InputDescriptor)(Cookie, const Descriptor &);
258// Formatted (including list directed) I/O data items
259bool IODECL(OutputInteger8)(Cookie, std::int8_t);
260bool IODECL(OutputInteger16)(Cookie, std::int16_t);
261bool IODECL(OutputInteger32)(Cookie, std::int32_t);
262bool IODECL(OutputInteger64)(Cookie, std::int64_t);
263bool IODECL(OutputInteger128)(Cookie, common::int128_t);
264bool IODECL(InputInteger)(Cookie, std::int64_t &, int kind = 8);
265bool IODECL(OutputReal32)(Cookie, float);
266bool IODECL(InputReal32)(Cookie, float &);
267bool IODECL(OutputReal64)(Cookie, double);
268bool IODECL(InputReal64)(Cookie, double &);
269bool IODECL(OutputComplex32)(Cookie, float, float);
270bool IODECL(InputComplex32)(Cookie, float[2]);
271bool IODECL(OutputComplex64)(Cookie, double, double);
272bool IODECL(InputComplex64)(Cookie, double[2]);
273bool IODECL(OutputCharacter)(Cookie, const char *, std::size_t, int kind = 1);
274bool IODECL(OutputAscii)(Cookie, const char *, std::size_t);
275bool IODECL(InputCharacter)(Cookie, char *, std::size_t, int kind = 1);
276bool IODECL(InputAscii)(Cookie, char *, std::size_t);
277bool IODECL(OutputLogical)(Cookie, bool);
278bool IODECL(InputLogical)(Cookie, bool &);
279
280// NAMELIST I/O must be the only data item in an (otherwise)
281// list-directed I/O statement.
282bool IODECL(OutputNamelist)(Cookie, const NamelistGroup &);
283bool IODECL(InputNamelist)(Cookie, const NamelistGroup &);
284
285// When an I/O list item has a derived type with a specific defined
286// I/O subroutine of the appropriate generic kind for the active
287// I/O data transfer statement (read/write, formatted/unformatted)
288// that pertains to the type or its components, and those subroutines
289// are dynamic or neither type-bound nor defined with interfaces
290// in the same scope as the derived type (or an IMPORT statement has
291// made such a generic interface inaccessible), these data item transfer
292// APIs enable the I/O runtime to make the right calls to defined I/O
293// subroutines.
294bool IODECL(OutputDerivedType)(
295 Cookie, const Descriptor &, const NonTbpDefinedIoTable *);
296bool IODECL(InputDerivedType)(
297 Cookie, const Descriptor &, const NonTbpDefinedIoTable *);
298
299// Additional specifier interfaces for the connection-list of
300// on OPEN statement (only). SetBlank(), SetDecimal(),
301// SetDelim(), GetIoMsg(), SetPad(), SetRound(), SetSign(),
302// & SetAsynchronous() are also acceptable for OPEN.
303// ACCESS=SEQUENTIAL, DIRECT, STREAM
304bool IODECL(SetAccess)(Cookie, const char *, std::size_t);
305// ACTION=READ, WRITE, or READWRITE
306bool IODECL(SetAction)(Cookie, const char *, std::size_t);
307// CARRIAGECONTROL=LIST, FORTRAN, NONE
308bool IODECL(SetCarriagecontrol)(Cookie, const char *, std::size_t);
309// CONVERT=NATIVE, LITTLE_ENDIAN, BIG_ENDIAN, or SWAP
310bool IODECL(SetConvert)(Cookie, const char *, std::size_t);
311// ENCODING=UTF-8, DEFAULT
312bool IODECL(SetEncoding)(Cookie, const char *, std::size_t);
313// FORM=FORMATTED, UNFORMATTED
314bool IODECL(SetForm)(Cookie, const char *, std::size_t);
315// POSITION=ASIS, REWIND, APPEND
316bool IODECL(SetPosition)(Cookie, const char *, std::size_t);
317bool IODECL(SetRecl)(Cookie, std::size_t); // RECL=
318
319// STATUS can be set during an OPEN or CLOSE statement.
320// For OPEN: STATUS=OLD, NEW, SCRATCH, REPLACE, UNKNOWN
321// For CLOSE: STATUS=KEEP, DELETE
322bool IODECL(SetStatus)(Cookie, const char *, std::size_t);
323
324bool IODECL(SetFile)(Cookie, const char *, std::size_t chars);
325
326// Acquires the runtime-created unit number for OPEN(NEWUNIT=)
327bool IODECL(GetNewUnit)(Cookie, int &, int kind = 4);
328
329// READ(SIZE=), after all input items
330std::size_t IODECL(GetSize)(Cookie);
331
332// INQUIRE(IOLENGTH=), after all output items
333std::size_t IODECL(GetIoLength)(Cookie);
334
335// GetIoMsg() does not modify its argument unless an error or
336// end-of-record/file condition is present.
337void IODECL(GetIoMsg)(Cookie, char *, std::size_t); // IOMSG=
338
339// Defines ID= on READ/WRITE(ASYNCHRONOUS='YES')
340AsynchronousId IODECL(GetAsynchronousId)(Cookie);
341
342// INQUIRE() specifiers are mostly identified by their NUL-terminated
343// case-insensitive names.
344// ACCESS, ACTION, ASYNCHRONOUS, BLANK, CONVERT, DECIMAL, DELIM, DIRECT,
345// ENCODING, FORM, FORMATTED, NAME, PAD, POSITION, READ, READWRITE, ROUND,
346// SEQUENTIAL, SIGN, STREAM, UNFORMATTED, WRITE:
347bool IODECL(InquireCharacter)(Cookie, InquiryKeywordHash, char *, std::size_t);
348// EXIST, NAMED, OPENED, and PENDING (without ID):
349bool IODECL(InquireLogical)(Cookie, InquiryKeywordHash, bool &);
350// PENDING with ID
351bool IODECL(InquirePendingId)(Cookie, AsynchronousId, bool &);
352// NEXTREC, NUMBER, POS, RECL, SIZE
353bool IODECL(InquireInteger64)(
354 Cookie, InquiryKeywordHash, std::int64_t &, int kind = 8);
355
356// This function must be called to end an I/O statement, and its
357// cookie value may not be used afterwards unless it is recycled
358// by the runtime library to serve a later I/O statement.
359// The return value can be used to implement IOSTAT=, ERR=, END=, & EOR=;
360// store it into the IOSTAT= variable if there is one, and test
361// it to implement the various branches. The error condition
362// returned is guaranteed to only be one of the problems that the
363// EnableHandlers() call has indicated should be handled in compiled code
364// rather than by terminating the image.
365enum Iostat IODECL(EndIoStatement)(Cookie);
366
367} // extern "C"
368} // namespace Fortran::runtime::io
369
370#endif /* FORTRAN_RUNTIME_IO_API_H_ */