PR c++/82357 - bit-field in template
[official-gcc.git] / gcc / fortran / gfortran.texi
blob4b4688cd0a29d3c06a6c5ca7f4e9702745f77d42
1 \input texinfo  @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename gfortran.info
4 @set copyrights-gfortran 1999-2017
6 @include gcc-common.texi
8 @settitle The GNU Fortran Compiler
10 @c Create a separate index for command line options
11 @defcodeindex op
12 @c Merge the standard indexes into a single one.
13 @syncodeindex fn cp
14 @syncodeindex vr cp
15 @syncodeindex ky cp
16 @syncodeindex pg cp
17 @syncodeindex tp cp
19 @c TODO: The following "Part" definitions are included here temporarily
20 @c until they are incorporated into the official Texinfo distribution.
21 @c They borrow heavily from Texinfo's \unnchapentry definitions.
23 @tex
24 \gdef\part#1#2{%
25   \pchapsepmacro
26   \gdef\thischapter{}
27   \begingroup
28     \vglue\titlepagetopglue
29     \titlefonts \rm
30     \leftline{Part #1:@* #2}
31     \vskip4pt \hrule height 4pt width \hsize \vskip4pt
32   \endgroup
33   \writetocentry{part}{#2}{#1}
35 \gdef\blankpart{%
36   \writetocentry{blankpart}{}{}
38 % Part TOC-entry definition for summary contents.
39 \gdef\dosmallpartentry#1#2#3#4{%
40   \vskip .5\baselineskip plus.2\baselineskip
41   \begingroup
42     \let\rm=\bf \rm
43     \tocentry{Part #2: #1}{\doshortpageno\bgroup#4\egroup}
44   \endgroup
46 \gdef\dosmallblankpartentry#1#2#3#4{%
47   \vskip .5\baselineskip plus.2\baselineskip
49 % Part TOC-entry definition for regular contents.  This has to be
50 % equated to an existing entry to not cause problems when the PDF
51 % outline is created.
52 \gdef\dopartentry#1#2#3#4{%
53   \unnchapentry{Part #2: #1}{}{#3}{#4}
55 \gdef\doblankpartentry#1#2#3#4{}
56 @end tex
58 @c %**end of header
60 @c Use with @@smallbook.
62 @c %** start of document
64 @c Cause even numbered pages to be printed on the left hand side of
65 @c the page and odd numbered pages to be printed on the right hand
66 @c side of the page.  Using this, you can print on both sides of a
67 @c sheet of paper and have the text on the same part of the sheet.
69 @c The text on right hand pages is pushed towards the right hand
70 @c margin and the text on left hand pages is pushed toward the left
71 @c hand margin.
72 @c (To provide the reverse effect, set bindingoffset to -0.75in.)
74 @c @tex
75 @c \global\bindingoffset=0.75in
76 @c \global\normaloffset =0.75in
77 @c @end tex
79 @copying
80 Copyright @copyright{} @value{copyrights-gfortran} Free Software Foundation, Inc.
82 Permission is granted to copy, distribute and/or modify this document
83 under the terms of the GNU Free Documentation License, Version 1.3 or
84 any later version published by the Free Software Foundation; with the
85 Invariant Sections being ``Funding Free Software'', the Front-Cover
86 Texts being (a) (see below), and with the Back-Cover Texts being (b)
87 (see below).  A copy of the license is included in the section entitled
88 ``GNU Free Documentation License''.
90 (a) The FSF's Front-Cover Text is:
92      A GNU Manual
94 (b) The FSF's Back-Cover Text is:
96      You have freedom to copy and modify this GNU Manual, like GNU
97      software.  Copies published by the Free Software Foundation raise
98      funds for GNU development.
99 @end copying
101 @ifinfo
102 @dircategory Software development
103 @direntry
104 * gfortran: (gfortran).                  The GNU Fortran Compiler.
105 @end direntry
106 This file documents the use and the internals of
107 the GNU Fortran compiler, (@command{gfortran}).
109 Published by the Free Software Foundation
110 51 Franklin Street, Fifth Floor
111 Boston, MA 02110-1301 USA
113 @insertcopying
114 @end ifinfo
117 @setchapternewpage odd
118 @titlepage
119 @title Using GNU Fortran
120 @versionsubtitle
121 @author The @t{gfortran} team
122 @page
123 @vskip 0pt plus 1filll
124 Published by the Free Software Foundation@*
125 51 Franklin Street, Fifth Floor@*
126 Boston, MA 02110-1301, USA@*
127 @c Last printed ??ber, 19??.@*
128 @c Printed copies are available for $? each.@*
129 @c ISBN ???
130 @sp 1
131 @insertcopying
132 @end titlepage
134 @c TODO: The following "Part" definitions are included here temporarily
135 @c until they are incorporated into the official Texinfo distribution.
137 @tex
138 \global\let\partentry=\dosmallpartentry
139 \global\let\blankpartentry=\dosmallblankpartentry
140 @end tex
141 @summarycontents
143 @tex
144 \global\let\partentry=\dopartentry
145 \global\let\blankpartentry=\doblankpartentry
146 @end tex
147 @contents
149 @page
151 @c ---------------------------------------------------------------------
152 @c TexInfo table of contents.
153 @c ---------------------------------------------------------------------
155 @ifnottex
156 @node Top
157 @top Introduction
158 @cindex Introduction
160 This manual documents the use of @command{gfortran},
161 the GNU Fortran compiler.  You can find in this manual how to invoke
162 @command{gfortran}, as well as its features and incompatibilities.
164 @ifset DEVELOPMENT
165 @emph{Warning:} This document, and the compiler it describes, are still
166 under development.  While efforts are made to keep it up-to-date, it might
167 not accurately reflect the status of the most recent GNU Fortran compiler.
168 @end ifset
170 @comment
171 @comment  When you add a new menu item, please keep the right hand
172 @comment  aligned to the same column.  Do not use tabs.  This provides
173 @comment  better formatting.
174 @comment
175 @menu
176 * Introduction::
178 Part I: Invoking GNU Fortran
179 * Invoking GNU Fortran:: Command options supported by @command{gfortran}.
180 * Runtime::              Influencing runtime behavior with environment variables.
182 Part II: Language Reference
183 * Fortran 2003 and 2008 status::  Fortran 2003 and 2008 features supported by GNU Fortran.
184 * Compiler Characteristics::      User-visible implementation details.
185 * Extensions::                    Language extensions implemented by GNU Fortran.
186 * Mixed-Language Programming::    Interoperability with C
187 * Coarray Programming::
188 * Intrinsic Procedures:: Intrinsic procedures supported by GNU Fortran.
189 * Intrinsic Modules::    Intrinsic modules supported by GNU Fortran.
191 * Contributing::         How you can help.
192 * Copying::              GNU General Public License says
193                          how you can copy and share GNU Fortran.
194 * GNU Free Documentation License::
195                          How you can copy and share this manual.
196 * Funding::              How to help assure continued work for free software.
197 * Option Index::         Index of command line options
198 * Keyword Index::        Index of concepts
199 @end menu
200 @end ifnottex
202 @c ---------------------------------------------------------------------
203 @c Introduction
204 @c ---------------------------------------------------------------------
206 @node Introduction
207 @chapter Introduction
209 @c The following duplicates the text on the TexInfo table of contents.
210 @iftex
211 This manual documents the use of @command{gfortran}, the GNU Fortran
212 compiler.  You can find in this manual how to invoke @command{gfortran},
213 as well as its features and incompatibilities.
215 @ifset DEVELOPMENT
216 @emph{Warning:} This document, and the compiler it describes, are still
217 under development.  While efforts are made to keep it up-to-date, it
218 might not accurately reflect the status of the most recent GNU Fortran
219 compiler.
220 @end ifset
221 @end iftex
223 The GNU Fortran compiler front end was
224 designed initially as a free replacement for,
225 or alternative to, the Unix @command{f95} command;
226 @command{gfortran} is the command you will use to invoke the compiler.
228 @menu
229 * About GNU Fortran::    What you should know about the GNU Fortran compiler.
230 * GNU Fortran and GCC::  You can compile Fortran, C, or other programs.
231 * Preprocessing and conditional compilation:: The Fortran preprocessor
232 * GNU Fortran and G77::  Why we chose to start from scratch.
233 * Project Status::       Status of GNU Fortran, roadmap, proposed extensions.
234 * Standards::            Standards supported by GNU Fortran.
235 @end menu
238 @c ---------------------------------------------------------------------
239 @c About GNU Fortran
240 @c ---------------------------------------------------------------------
242 @node About GNU Fortran
243 @section About GNU Fortran
245 The GNU Fortran compiler supports the Fortran 77, 90 and 95 standards
246 completely, parts of the Fortran 2003 and Fortran 2008 standards, and
247 several vendor extensions.  The development goal is to provide the
248 following features:
250 @itemize @bullet
251 @item
252 Read a user's program,
253 stored in a file and containing instructions written
254 in Fortran 77, Fortran 90, Fortran 95, Fortran 2003 or Fortran 2008.
255 This file contains @dfn{source code}.
257 @item
258 Translate the user's program into instructions a computer
259 can carry out more quickly than it takes to translate the
260 instructions in the first
261 place.  The result after compilation of a program is
262 @dfn{machine code},
263 code designed to be efficiently translated and processed
264 by a machine such as your computer.
265 Humans usually are not as good writing machine code
266 as they are at writing Fortran (or C++, Ada, or Java),
267 because it is easy to make tiny mistakes writing machine code.
269 @item
270 Provide the user with information about the reasons why
271 the compiler is unable to create a binary from the source code.
272 Usually this will be the case if the source code is flawed.
273 The Fortran 90 standard requires that the compiler can point out
274 mistakes to the user.
275 An incorrect usage of the language causes an @dfn{error message}.
277 The compiler will also attempt to diagnose cases where the
278 user's program contains a correct usage of the language,
279 but instructs the computer to do something questionable.
280 This kind of diagnostics message is called a @dfn{warning message}.
282 @item
283 Provide optional information about the translation passes
284 from the source code to machine code.
285 This can help a user of the compiler to find the cause of
286 certain bugs which may not be obvious in the source code,
287 but may be more easily found at a lower level compiler output.
288 It also helps developers to find bugs in the compiler itself.
290 @item
291 Provide information in the generated machine code that can
292 make it easier to find bugs in the program (using a debugging tool,
293 called a @dfn{debugger}, such as the GNU Debugger @command{gdb}).
295 @item
296 Locate and gather machine code already generated to
297 perform actions requested by statements in the user's program.
298 This machine code is organized into @dfn{modules} and is located
299 and @dfn{linked} to the user program.
300 @end itemize
302 The GNU Fortran compiler consists of several components:
304 @itemize @bullet
305 @item
306 A version of the @command{gcc} command
307 (which also might be installed as the system's @command{cc} command)
308 that also understands and accepts Fortran source code.
309 The @command{gcc} command is the @dfn{driver} program for
310 all the languages in the GNU Compiler Collection (GCC);
311 With @command{gcc},
312 you can compile the source code of any language for
313 which a front end is available in GCC.
315 @item
316 The @command{gfortran} command itself,
317 which also might be installed as the
318 system's @command{f95} command.
319 @command{gfortran} is just another driver program,
320 but specifically for the Fortran compiler only.
321 The difference with @command{gcc} is that @command{gfortran}
322 will automatically link the correct libraries to your program.
324 @item
325 A collection of run-time libraries.
326 These libraries contain the machine code needed to support
327 capabilities of the Fortran language that are not directly
328 provided by the machine code generated by the
329 @command{gfortran} compilation phase,
330 such as intrinsic functions and subroutines,
331 and routines for interaction with files and the operating system.
332 @c and mechanisms to spawn,
333 @c unleash and pause threads in parallelized code.
335 @item
336 The Fortran compiler itself, (@command{f951}).
337 This is the GNU Fortran parser and code generator,
338 linked to and interfaced with the GCC backend library.
339 @command{f951} ``translates'' the source code to
340 assembler code.  You would typically not use this
341 program directly;
342 instead, the @command{gcc} or @command{gfortran} driver
343 programs will call it for you.
344 @end itemize
347 @c ---------------------------------------------------------------------
348 @c GNU Fortran and GCC
349 @c ---------------------------------------------------------------------
351 @node GNU Fortran and GCC
352 @section GNU Fortran and GCC
353 @cindex GNU Compiler Collection
354 @cindex GCC
356 GNU Fortran is a part of GCC, the @dfn{GNU Compiler Collection}.  GCC
357 consists of a collection of front ends for various languages, which
358 translate the source code into a language-independent form called
359 @dfn{GENERIC}.  This is then processed by a common middle end which
360 provides optimization, and then passed to one of a collection of back
361 ends which generate code for different computer architectures and
362 operating systems.
364 Functionally, this is implemented with a driver program (@command{gcc})
365 which provides the command-line interface for the compiler.  It calls
366 the relevant compiler front-end program (e.g., @command{f951} for
367 Fortran) for each file in the source code, and then calls the assembler
368 and linker as appropriate to produce the compiled output.  In a copy of
369 GCC which has been compiled with Fortran language support enabled,
370 @command{gcc} will recognize files with @file{.f}, @file{.for}, @file{.ftn},
371 @file{.f90}, @file{.f95}, @file{.f03} and @file{.f08} extensions as
372 Fortran source code, and compile it accordingly.  A @command{gfortran}
373 driver program is also provided, which is identical to @command{gcc}
374 except that it automatically links the Fortran runtime libraries into the
375 compiled program.
377 Source files with @file{.f}, @file{.for}, @file{.fpp}, @file{.ftn}, @file{.F},
378 @file{.FOR}, @file{.FPP}, and @file{.FTN} extensions are treated as fixed form.
379 Source files with @file{.f90}, @file{.f95}, @file{.f03}, @file{.f08},
380 @file{.F90}, @file{.F95}, @file{.F03} and @file{.F08} extensions are
381 treated as free form.  The capitalized versions of either form are run
382 through preprocessing.  Source files with the lower case @file{.fpp}
383 extension are also run through preprocessing.
385 This manual specifically documents the Fortran front end, which handles
386 the programming language's syntax and semantics.  The aspects of GCC
387 which relate to the optimization passes and the back-end code generation
388 are documented in the GCC manual; see 
389 @ref{Top,,Introduction,gcc,Using the GNU Compiler Collection (GCC)}.
390 The two manuals together provide a complete reference for the GNU
391 Fortran compiler.
394 @c ---------------------------------------------------------------------
395 @c Preprocessing and conditional compilation
396 @c ---------------------------------------------------------------------
398 @node Preprocessing and conditional compilation
399 @section Preprocessing and conditional compilation
400 @cindex CPP
401 @cindex FPP
402 @cindex Conditional compilation
403 @cindex Preprocessing
404 @cindex preprocessor, include file handling
406 Many Fortran compilers including GNU Fortran allow passing the source code
407 through a C preprocessor (CPP; sometimes also called the Fortran preprocessor,
408 FPP) to allow for conditional compilation.  In the case of GNU Fortran,
409 this is the GNU C Preprocessor in the traditional mode.  On systems with
410 case-preserving file names, the preprocessor is automatically invoked if the
411 filename extension is @file{.F}, @file{.FOR}, @file{.FTN}, @file{.fpp},
412 @file{.FPP}, @file{.F90}, @file{.F95}, @file{.F03} or @file{.F08}.  To manually
413 invoke the preprocessor on any file, use @option{-cpp}, to disable
414 preprocessing on files where the preprocessor is run automatically, use
415 @option{-nocpp}.
417 If a preprocessed file includes another file with the Fortran @code{INCLUDE}
418 statement, the included file is not preprocessed.  To preprocess included
419 files, use the equivalent preprocessor statement @code{#include}.
421 If GNU Fortran invokes the preprocessor, @code{__GFORTRAN__}
422 is defined and @code{__GNUC__}, @code{__GNUC_MINOR__} and
423 @code{__GNUC_PATCHLEVEL__} can be used to determine the version of the
424 compiler.  See @ref{Top,,Overview,cpp,The C Preprocessor} for details.
426 While CPP is the de-facto standard for preprocessing Fortran code,
427 Part 3 of the Fortran 95 standard (ISO/IEC 1539-3:1998) defines
428 Conditional Compilation, which is not widely used and not directly
429 supported by the GNU Fortran compiler.  You can use the program coco
430 to preprocess such files (@uref{http://www.daniellnagle.com/coco.html}).
433 @c ---------------------------------------------------------------------
434 @c GNU Fortran and G77
435 @c ---------------------------------------------------------------------
437 @node GNU Fortran and G77
438 @section GNU Fortran and G77
439 @cindex Fortran 77
440 @cindex @command{g77}
442 The GNU Fortran compiler is the successor to @command{g77}, the Fortran 
443 77 front end included in GCC prior to version 4.  It is an entirely new 
444 program that has been designed to provide Fortran 95 support and 
445 extensibility for future Fortran language standards, as well as providing 
446 backwards compatibility for Fortran 77 and nearly all of the GNU language 
447 extensions supported by @command{g77}.
450 @c ---------------------------------------------------------------------
451 @c Project Status
452 @c ---------------------------------------------------------------------
454 @node Project Status
455 @section Project Status
457 @quotation
458 As soon as @command{gfortran} can parse all of the statements correctly,
459 it will be in the ``larva'' state.
460 When we generate code, the ``puppa'' state.
461 When @command{gfortran} is done,
462 we'll see if it will be a beautiful butterfly,
463 or just a big bug....
465 --Andy Vaught, April 2000
466 @end quotation
468 The start of the GNU Fortran 95 project was announced on
469 the GCC homepage in March 18, 2000
470 (even though Andy had already been working on it for a while,
471 of course).
473 The GNU Fortran compiler is able to compile nearly all
474 standard-compliant Fortran 95, Fortran 90, and Fortran 77 programs,
475 including a number of standard and non-standard extensions, and can be
476 used on real-world programs.  In particular, the supported extensions
477 include OpenMP, Cray-style pointers, some old vendor extensions, and several
478 Fortran 2003 and Fortran 2008 features, including TR 15581.  However, it is
479 still under development and has a few remaining rough edges.
480 There also is initial support for OpenACC.
481 Note that this is an experimental feature, incomplete, and subject to
482 change in future versions of GCC.  See
483 @uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
485 At present, the GNU Fortran compiler passes the
486 @uref{http://www.fortran-2000.com/ArnaudRecipes/fcvs21_f95.html, 
487 NIST Fortran 77 Test Suite}, and produces acceptable results on the
488 @uref{http://www.netlib.org/lapack/faq.html#1.21, LAPACK Test Suite}.
489 It also provides respectable performance on 
490 the @uref{http://www.polyhedron.com/fortran-compiler-comparisons/polyhedron-benchmark-suite,
491 Polyhedron Fortran
492 compiler benchmarks} and the
493 @uref{http://www.netlib.org/benchmark/livermore,
494 Livermore Fortran Kernels test}.  It has been used to compile a number of
495 large real-world programs, including
496 @uref{http://hirlam.org/, the HARMONIE and HIRLAM weather forecasting code} and
497 @uref{http://physical-chemistry.scb.uwa.edu.au/tonto/wiki/index.php/Main_Page,
498 the Tonto quantum chemistry package}; see
499 @url{https://gcc.gnu.org/@/wiki/@/GfortranApps} for an extended list.
501 Among other things, the GNU Fortran compiler is intended as a replacement
502 for G77.  At this point, nearly all programs that could be compiled with
503 G77 can be compiled with GNU Fortran, although there are a few minor known
504 regressions.
506 The primary work remaining to be done on GNU Fortran falls into three
507 categories: bug fixing (primarily regarding the treatment of invalid code
508 and providing useful error messages), improving the compiler optimizations
509 and the performance of compiled code, and extending the compiler to support
510 future standards---in particular, Fortran 2003 and Fortran 2008.
513 @c ---------------------------------------------------------------------
514 @c Standards
515 @c ---------------------------------------------------------------------
517 @node Standards
518 @section Standards
519 @cindex Standards
521 @menu
522 * Varying Length Character Strings::
523 @end menu
525 The GNU Fortran compiler implements
526 ISO/IEC 1539:1997 (Fortran 95).  As such, it can also compile essentially all
527 standard-compliant Fortran 90 and Fortran 77 programs.   It also supports
528 the ISO/IEC TR-15581 enhancements to allocatable arrays.
530 GNU Fortran also have a partial support for ISO/IEC 1539-1:2004 (Fortran
531 2003), ISO/IEC 1539-1:2010 (Fortran 2008), the Technical Specification
532 @code{Further Interoperability of Fortran with C} (ISO/IEC TS 29113:2012).
533 Full support of those standards and future Fortran standards is planned.
534 The current status of the support is can be found in the
535 @ref{Fortran 2003 status}, @ref{Fortran 2008 status}, @ref{TS 29113 status}
536 and @ref{TS 18508 status} sections of the documentation.
538 Additionally, the GNU Fortran compilers supports the OpenMP specification
539 (version 4.0 and most of the features of the 4.5 version,
540 @url{http://openmp.org/@/wp/@/openmp-specifications/}).
541 There also is initial support for the OpenACC specification (targeting
542 version 2.0, @uref{http://www.openacc.org/}).
543 Note that this is an experimental feature, incomplete, and subject to
544 change in future versions of GCC.  See
545 @uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
547 @node Varying Length Character Strings
548 @subsection Varying Length Character Strings
549 @cindex Varying length character strings
550 @cindex Varying length strings
551 @cindex strings, varying length
553 The Fortran 95 standard specifies in Part 2 (ISO/IEC 1539-2:2000)
554 varying length character strings.  While GNU Fortran currently does not
555 support such strings directly, there exist two Fortran implementations
556 for them, which work with GNU Fortran.  They can be found at
557 @uref{http://www.fortran.com/@/iso_varying_string.f95} and at
558 @uref{ftp://ftp.nag.co.uk/@/sc22wg5/@/ISO_VARYING_STRING/}.
560 Deferred-length character strings of Fortran 2003 supports part of
561 the features of @code{ISO_VARYING_STRING} and should be considered as
562 replacement. (Namely, allocatable or pointers of the type
563 @code{character(len=:)}.)
566 @c =====================================================================
567 @c PART I: INVOCATION REFERENCE
568 @c =====================================================================
570 @tex
571 \part{I}{Invoking GNU Fortran}
572 @end tex
574 @c ---------------------------------------------------------------------
575 @c Compiler Options
576 @c ---------------------------------------------------------------------
578 @include invoke.texi
581 @c ---------------------------------------------------------------------
582 @c Runtime
583 @c ---------------------------------------------------------------------
585 @node Runtime
586 @chapter Runtime:  Influencing runtime behavior with environment variables
587 @cindex environment variable
589 The behavior of the @command{gfortran} can be influenced by
590 environment variables.
592 Malformed environment variables are silently ignored.
594 @menu
595 * TMPDIR:: Directory for scratch files
596 * GFORTRAN_STDIN_UNIT:: Unit number for standard input
597 * GFORTRAN_STDOUT_UNIT:: Unit number for standard output
598 * GFORTRAN_STDERR_UNIT:: Unit number for standard error
599 * GFORTRAN_UNBUFFERED_ALL:: Do not buffer I/O for all units.
600 * GFORTRAN_UNBUFFERED_PRECONNECTED:: Do not buffer I/O for preconnected units.
601 * GFORTRAN_SHOW_LOCUS::  Show location for runtime errors
602 * GFORTRAN_OPTIONAL_PLUS:: Print leading + where permitted
603 * GFORTRAN_DEFAULT_RECL:: Default record length for new files
604 * GFORTRAN_LIST_SEPARATOR::  Separator for list output
605 * GFORTRAN_CONVERT_UNIT::  Set endianness for unformatted I/O
606 * GFORTRAN_ERROR_BACKTRACE:: Show backtrace on run-time errors
607 @end menu
609 @node TMPDIR
610 @section @env{TMPDIR}---Directory for scratch files
612 When opening a file with @code{STATUS='SCRATCH'}, GNU Fortran tries to
613 create the file in one of the potential directories by testing each
614 directory in the order below.
616 @enumerate
617 @item
618 The environment variable @env{TMPDIR}, if it exists.
620 @item
621 On the MinGW target, the directory returned by the @code{GetTempPath}
622 function. Alternatively, on the Cygwin target, the @env{TMP} and
623 @env{TEMP} environment variables, if they exist, in that order.
625 @item
626 The @code{P_tmpdir} macro if it is defined, otherwise the directory
627 @file{/tmp}.
628 @end enumerate
630 @node GFORTRAN_STDIN_UNIT
631 @section @env{GFORTRAN_STDIN_UNIT}---Unit number for standard input
633 This environment variable can be used to select the unit number
634 preconnected to standard input.  This must be a positive integer.
635 The default value is 5.
637 @node GFORTRAN_STDOUT_UNIT
638 @section @env{GFORTRAN_STDOUT_UNIT}---Unit number for standard output
640 This environment variable can be used to select the unit number
641 preconnected to standard output.  This must be a positive integer.
642 The default value is 6.
644 @node GFORTRAN_STDERR_UNIT
645 @section @env{GFORTRAN_STDERR_UNIT}---Unit number for standard error
647 This environment variable can be used to select the unit number
648 preconnected to standard error.  This must be a positive integer.
649 The default value is 0.
651 @node GFORTRAN_UNBUFFERED_ALL
652 @section @env{GFORTRAN_UNBUFFERED_ALL}---Do not buffer I/O on all units
654 This environment variable controls whether all I/O is unbuffered.  If
655 the first letter is @samp{y}, @samp{Y} or @samp{1}, all I/O is
656 unbuffered.  This will slow down small sequential reads and writes.  If
657 the first letter is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.
658 This is the default.
660 @node GFORTRAN_UNBUFFERED_PRECONNECTED
661 @section @env{GFORTRAN_UNBUFFERED_PRECONNECTED}---Do not buffer I/O on preconnected units
663 The environment variable named @env{GFORTRAN_UNBUFFERED_PRECONNECTED} controls
664 whether I/O on a preconnected unit (i.e.@: STDOUT or STDERR) is unbuffered.  If 
665 the first letter is @samp{y}, @samp{Y} or @samp{1}, I/O is unbuffered.  This
666 will slow down small sequential reads and writes.  If the first letter
667 is @samp{n}, @samp{N} or @samp{0}, I/O is buffered.  This is the default.
669 @node GFORTRAN_SHOW_LOCUS
670 @section @env{GFORTRAN_SHOW_LOCUS}---Show location for runtime errors
672 If the first letter is @samp{y}, @samp{Y} or @samp{1}, filename and
673 line numbers for runtime errors are printed.  If the first letter is
674 @samp{n}, @samp{N} or @samp{0}, do not print filename and line numbers
675 for runtime errors.  The default is to print the location.
677 @node GFORTRAN_OPTIONAL_PLUS
678 @section @env{GFORTRAN_OPTIONAL_PLUS}---Print leading + where permitted
680 If the first letter is @samp{y}, @samp{Y} or @samp{1},
681 a plus sign is printed
682 where permitted by the Fortran standard.  If the first letter
683 is @samp{n}, @samp{N} or @samp{0}, a plus sign is not printed
684 in most cases.  Default is not to print plus signs.
686 @node GFORTRAN_DEFAULT_RECL
687 @section @env{GFORTRAN_DEFAULT_RECL}---Default record length for new files
689 This environment variable specifies the default record length, in
690 bytes, for files which are opened without a @code{RECL} tag in the
691 @code{OPEN} statement.  This must be a positive integer.  The
692 default value is 1073741824 bytes (1 GB).
694 @node GFORTRAN_LIST_SEPARATOR
695 @section @env{GFORTRAN_LIST_SEPARATOR}---Separator for list output
697 This environment variable specifies the separator when writing
698 list-directed output.  It may contain any number of spaces and
699 at most one comma.  If you specify this on the command line,
700 be sure to quote spaces, as in
701 @smallexample
702 $ GFORTRAN_LIST_SEPARATOR='  ,  ' ./a.out
703 @end smallexample
704 when @command{a.out} is the compiled Fortran program that you want to run.
705 Default is a single space.
707 @node GFORTRAN_CONVERT_UNIT
708 @section @env{GFORTRAN_CONVERT_UNIT}---Set endianness for unformatted I/O
710 By setting the @env{GFORTRAN_CONVERT_UNIT} variable, it is possible
711 to change the representation of data for unformatted files.
712 The syntax for the @env{GFORTRAN_CONVERT_UNIT} variable is:
713 @smallexample
714 GFORTRAN_CONVERT_UNIT: mode | mode ';' exception | exception ;
715 mode: 'native' | 'swap' | 'big_endian' | 'little_endian' ;
716 exception: mode ':' unit_list | unit_list ;
717 unit_list: unit_spec | unit_list unit_spec ;
718 unit_spec: INTEGER | INTEGER '-' INTEGER ;
719 @end smallexample
720 The variable consists of an optional default mode, followed by
721 a list of optional exceptions, which are separated by semicolons
722 from the preceding default and each other.  Each exception consists
723 of a format and a comma-separated list of units.  Valid values for
724 the modes are the same as for the @code{CONVERT} specifier:
726 @itemize @w{}
727 @item @code{NATIVE} Use the native format.  This is the default.
728 @item @code{SWAP} Swap between little- and big-endian.
729 @item @code{LITTLE_ENDIAN} Use the little-endian format
730 for unformatted files.
731 @item @code{BIG_ENDIAN} Use the big-endian format for unformatted files.
732 @end itemize
733 A missing mode for an exception is taken to mean @code{BIG_ENDIAN}.
734 Examples of values for @env{GFORTRAN_CONVERT_UNIT} are:
735 @itemize @w{}
736 @item @code{'big_endian'}  Do all unformatted I/O in big_endian mode.
737 @item @code{'little_endian;native:10-20,25'}  Do all unformatted I/O 
738 in little_endian mode, except for units 10 to 20 and 25, which are in
739 native format.
740 @item @code{'10-20'}  Units 10 to 20 are big-endian, the rest is native.
741 @end itemize
743 Setting the environment variables should be done on the command
744 line or via the @command{export}
745 command for @command{sh}-compatible shells and via @command{setenv}
746 for @command{csh}-compatible shells.
748 Example for @command{sh}:
749 @smallexample
750 $ gfortran foo.f90
751 $ GFORTRAN_CONVERT_UNIT='big_endian;native:10-20' ./a.out
752 @end smallexample
754 Example code for @command{csh}:
755 @smallexample
756 % gfortran foo.f90
757 % setenv GFORTRAN_CONVERT_UNIT 'big_endian;native:10-20'
758 % ./a.out
759 @end smallexample
761 Using anything but the native representation for unformatted data
762 carries a significant speed overhead.  If speed in this area matters
763 to you, it is best if you use this only for data that needs to be
764 portable.
766 @xref{CONVERT specifier}, for an alternative way to specify the
767 data representation for unformatted files.  @xref{Runtime Options}, for
768 setting a default data representation for the whole program.  The
769 @code{CONVERT} specifier overrides the @option{-fconvert} compile options.
771 @emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
772 environment variable will override the CONVERT specifier in the
773 open statement}.  This is to give control over data formats to
774 users who do not have the source code of their program available.
776 @node GFORTRAN_ERROR_BACKTRACE
777 @section @env{GFORTRAN_ERROR_BACKTRACE}---Show backtrace on run-time errors
779 If the @env{GFORTRAN_ERROR_BACKTRACE} variable is set to @samp{y},
780 @samp{Y} or @samp{1} (only the first letter is relevant) then a
781 backtrace is printed when a serious run-time error occurs.  To disable
782 the backtracing, set the variable to @samp{n}, @samp{N}, @samp{0}.
783 Default is to print a backtrace unless the @option{-fno-backtrace}
784 compile option was used.
786 @c =====================================================================
787 @c PART II: LANGUAGE REFERENCE
788 @c =====================================================================
790 @tex
791 \part{II}{Language Reference}
792 @end tex
794 @c ---------------------------------------------------------------------
795 @c Fortran 2003 and 2008 Status
796 @c ---------------------------------------------------------------------
798 @node Fortran 2003 and 2008 status
799 @chapter Fortran 2003 and 2008 Status
801 @menu
802 * Fortran 2003 status::
803 * Fortran 2008 status::
804 * TS 29113 status::
805 * TS 18508 status::
806 @end menu
808 @node Fortran 2003 status
809 @section Fortran 2003 status
811 GNU Fortran supports several Fortran 2003 features; an incomplete
812 list can be found below.  See also the
813 @uref{https://gcc.gnu.org/wiki/Fortran2003, wiki page} about Fortran 2003.
815 @itemize
816 @item Procedure pointers including procedure-pointer components with
817 @code{PASS} attribute.
819 @item Procedures which are bound to a derived type (type-bound procedures)
820 including @code{PASS}, @code{PROCEDURE} and @code{GENERIC}, and
821 operators bound to a type.
823 @item Abstract interfaces and type extension with the possibility to
824 override type-bound procedures or to have deferred binding.
826 @item Polymorphic entities (``@code{CLASS}'') for derived types and unlimited
827 polymorphism (``@code{CLASS(*)}'') -- including @code{SAME_TYPE_AS},
828 @code{EXTENDS_TYPE_OF} and @code{SELECT TYPE} for scalars and arrays and
829 finalization.
831 @item Generic interface names, which have the same name as derived types,
832 are now supported. This allows one to write constructor functions.  Note
833 that Fortran does not support static constructor functions.  For static
834 variables, only default initialization or structure-constructor
835 initialization are available.
837 @item The @code{ASSOCIATE} construct.
839 @item Interoperability with C including enumerations, 
841 @item In structure constructors the components with default values may be
842 omitted.
844 @item Extensions to the @code{ALLOCATE} statement, allowing for a
845 type-specification with type parameter and for allocation and initialization
846 from a @code{SOURCE=} expression; @code{ALLOCATE} and @code{DEALLOCATE}
847 optionally return an error message string via @code{ERRMSG=}.
849 @item Reallocation on assignment: If an intrinsic assignment is
850 used, an allocatable variable on the left-hand side is automatically allocated
851 (if unallocated) or reallocated (if the shape is different). Currently, scalar
852 deferred character length left-hand sides are correctly handled but arrays
853 are not yet fully implemented.
855 @item Deferred-length character variables and scalar deferred-length character
856 components of derived types are supported. (Note that array-valued compoents
857 are not yet implemented.)
859 @item Transferring of allocations via @code{MOVE_ALLOC}.
861 @item The @code{PRIVATE} and @code{PUBLIC} attributes may be given individually
862 to derived-type components.
864 @item In pointer assignments, the lower bound may be specified and
865 the remapping of elements is supported.
867 @item For pointers an @code{INTENT} may be specified which affect the
868 association status not the value of the pointer target.
870 @item Intrinsics @code{command_argument_count}, @code{get_command},
871 @code{get_command_argument}, and @code{get_environment_variable}.
873 @item Support for Unicode characters (ISO 10646) and UTF-8, including
874 the @code{SELECTED_CHAR_KIND} and @code{NEW_LINE} intrinsic functions.
876 @item Support for binary, octal and hexadecimal (BOZ) constants in the
877 intrinsic functions @code{INT}, @code{REAL}, @code{CMPLX} and @code{DBLE}.
879 @item Support for namelist variables with allocatable and pointer
880 attribute and nonconstant length type parameter.
882 @item
883 @cindex array, constructors
884 @cindex @code{[...]}
885 Array constructors using square brackets.  That is, @code{[...]} rather
886 than @code{(/.../)}.  Type-specification for array constructors like
887 @code{(/ some-type :: ... /)}.
889 @item Extensions to the specification and initialization expressions,
890 including the support for intrinsics with real and complex arguments.
892 @item Support for the asynchronous input/output syntax; however, the
893 data transfer is currently always synchronously performed. 
895 @item
896 @cindex @code{FLUSH} statement
897 @cindex statement, @code{FLUSH}
898 @code{FLUSH} statement.
900 @item
901 @cindex @code{IOMSG=} specifier
902 @code{IOMSG=} specifier for I/O statements.
904 @item
905 @cindex @code{ENUM} statement
906 @cindex @code{ENUMERATOR} statement
907 @cindex statement, @code{ENUM}
908 @cindex statement, @code{ENUMERATOR}
909 @opindex @code{fshort-enums}
910 Support for the declaration of enumeration constants via the
911 @code{ENUM} and @code{ENUMERATOR} statements.  Interoperability with
912 @command{gcc} is guaranteed also for the case where the
913 @command{-fshort-enums} command line option is given.
915 @item
916 @cindex TR 15581
917 TR 15581:
918 @itemize
919 @item
920 @cindex @code{ALLOCATABLE} dummy arguments
921 @code{ALLOCATABLE} dummy arguments.
922 @item
923 @cindex @code{ALLOCATABLE} function results
924 @code{ALLOCATABLE} function results
925 @item
926 @cindex @code{ALLOCATABLE} components of derived types
927 @code{ALLOCATABLE} components of derived types
928 @end itemize
930 @item
931 @cindex @code{STREAM} I/O
932 @cindex @code{ACCESS='STREAM'} I/O
933 The @code{OPEN} statement supports the @code{ACCESS='STREAM'} specifier,
934 allowing I/O without any record structure.
936 @item
937 Namelist input/output for internal files.
939 @item Minor I/O features: Rounding during formatted output, using of
940 a decimal comma instead of a decimal point, setting whether a plus sign
941 should appear for positive numbers. On systems where @code{strtod} honours
942 the rounding mode, the rounding mode is also supported for input.
944 @item
945 @cindex @code{PROTECTED} statement
946 @cindex statement, @code{PROTECTED}
947 The @code{PROTECTED} statement and attribute.
949 @item
950 @cindex @code{VALUE} statement
951 @cindex statement, @code{VALUE}
952 The @code{VALUE} statement and attribute.
954 @item
955 @cindex @code{VOLATILE} statement
956 @cindex statement, @code{VOLATILE}
957 The @code{VOLATILE} statement and attribute.
959 @item
960 @cindex @code{IMPORT} statement
961 @cindex statement, @code{IMPORT}
962 The @code{IMPORT} statement, allowing to import
963 host-associated derived types.
965 @item The intrinsic modules @code{ISO_FORTRAN_ENVIRONMENT} is supported,
966 which contains parameters of the I/O units, storage sizes. Additionally,
967 procedures for C interoperability are available in the @code{ISO_C_BINDING}
968 module.
970 @item
971 @cindex @code{USE, INTRINSIC} statement
972 @cindex statement, @code{USE, INTRINSIC}
973 @cindex @code{ISO_FORTRAN_ENV} statement
974 @cindex statement, @code{ISO_FORTRAN_ENV}
975 @code{USE} statement with @code{INTRINSIC} and @code{NON_INTRINSIC}
976 attribute; supported intrinsic modules: @code{ISO_FORTRAN_ENV},
977 @code{ISO_C_BINDING}, @code{OMP_LIB} and @code{OMP_LIB_KINDS},
978 and @code{OPENACC}.
980 @item
981 Renaming of operators in the @code{USE} statement.
983 @end itemize
986 @node Fortran 2008 status
987 @section Fortran 2008 status
989 The latest version of the Fortran standard is ISO/IEC 1539-1:2010, informally
990 known as Fortran 2008.  The official version is available from International
991 Organization for Standardization (ISO) or its national member organizations.
992 The the final draft (FDIS) can be downloaded free of charge from
993 @url{http://www.nag.co.uk/@/sc22wg5/@/links.html}.  Fortran is developed by the
994 Working Group 5 of Sub-Committee 22 of the Joint Technical Committee 1 of the
995 International Organization for Standardization and the International
996 Electrotechnical Commission (IEC).  This group is known as
997 @uref{http://www.nag.co.uk/sc22wg5/, WG5}.
999 The GNU Fortran compiler supports several of the new features of Fortran 2008;
1000 the @uref{https://gcc.gnu.org/wiki/Fortran2008Status, wiki} has some information
1001 about the current Fortran 2008 implementation status.  In particular, the
1002 following is implemented.
1004 @itemize
1005 @item The @option{-std=f2008} option and support for the file extensions 
1006 @file{.f08} and @file{.F08}.
1008 @item The @code{OPEN} statement now supports the @code{NEWUNIT=} option,
1009 which returns a unique file unit, thus preventing inadvertent use of the
1010 same unit in different parts of the program.
1012 @item The @code{g0} format descriptor and unlimited format items.
1014 @item The mathematical intrinsics @code{ASINH}, @code{ACOSH}, @code{ATANH},
1015 @code{ERF}, @code{ERFC}, @code{GAMMA}, @code{LOG_GAMMA}, @code{BESSEL_J0},
1016 @code{BESSEL_J1}, @code{BESSEL_JN}, @code{BESSEL_Y0}, @code{BESSEL_Y1},
1017 @code{BESSEL_YN}, @code{HYPOT}, @code{NORM2}, and @code{ERFC_SCALED}.
1019 @item Using complex arguments with @code{TAN}, @code{SINH}, @code{COSH},
1020 @code{TANH}, @code{ASIN}, @code{ACOS}, and @code{ATAN} is now possible;
1021 @code{ATAN}(@var{Y},@var{X}) is now an alias for @code{ATAN2}(@var{Y},@var{X}).
1023 @item Support of the @code{PARITY} intrinsic functions.
1025 @item The following bit intrinsics: @code{LEADZ} and @code{TRAILZ} for
1026 counting the number of leading and trailing zero bits, @code{POPCNT} and
1027 @code{POPPAR} for counting the number of one bits and returning the parity;
1028 @code{BGE}, @code{BGT}, @code{BLE}, and @code{BLT} for bitwise comparisons;
1029 @code{DSHIFTL} and @code{DSHIFTR} for combined left and right shifts,
1030 @code{MASKL} and @code{MASKR} for simple left and right justified masks,
1031 @code{MERGE_BITS} for a bitwise merge using a mask, @code{SHIFTA},
1032 @code{SHIFTL} and @code{SHIFTR} for shift operations, and the
1033 transformational bit intrinsics @code{IALL}, @code{IANY} and @code{IPARITY}.
1035 @item Support of the @code{EXECUTE_COMMAND_LINE} intrinsic subroutine.
1037 @item Support for the @code{STORAGE_SIZE} intrinsic inquiry function.
1039 @item The @code{INT@{8,16,32@}} and @code{REAL@{32,64,128@}} kind type
1040 parameters and the array-valued named constants @code{INTEGER_KINDS},
1041 @code{LOGICAL_KINDS}, @code{REAL_KINDS} and @code{CHARACTER_KINDS} of
1042 the intrinsic module @code{ISO_FORTRAN_ENV}.
1044 @item The module procedures @code{C_SIZEOF} of the intrinsic module
1045 @code{ISO_C_BINDINGS} and @code{COMPILER_VERSION} and @code{COMPILER_OPTIONS}
1046 of @code{ISO_FORTRAN_ENV}.
1048 @item Coarray support for serial programs with @option{-fcoarray=single} flag
1049 and experimental support for multiple images with the @option{-fcoarray=lib}
1050 flag.
1052 @item Submodules are supported. It should noted that @code{MODULEs} do not
1053 produce the smod file needed by the descendent @code{SUBMODULEs} unless they
1054 contain at least one @code{MODULE PROCEDURE} interface. The reason for this is
1055 that @code{SUBMODULEs} are useless without @code{MODULE PROCEDUREs}. See
1056 http://j3-fortran.org/doc/meeting/207/15-209.txt for a discussion and a draft
1057 interpretation. Adopting this interpretation has the advantage that code that
1058 does not use submodules does not generate smod files.
1060 @item The @code{DO CONCURRENT} construct is supported.
1062 @item The @code{BLOCK} construct is supported.
1064 @item The @code{STOP} and the new @code{ERROR STOP} statements now
1065 support all constant expressions. Both show the signals which were signaling
1066 at termination.
1068 @item Support for the @code{CONTIGUOUS} attribute.
1070 @item Support for @code{ALLOCATE} with @code{MOLD}.
1072 @item Support for the @code{IMPURE} attribute for procedures, which
1073 allows for @code{ELEMENTAL} procedures without the restrictions of
1074 @code{PURE}.
1076 @item Null pointers (including @code{NULL()}) and not-allocated variables
1077 can be used as actual argument to optional non-pointer, non-allocatable
1078 dummy arguments, denoting an absent argument.
1080 @item Non-pointer variables with @code{TARGET} attribute can be used as
1081 actual argument to @code{POINTER} dummies with @code{INTENT(IN)}.
1083 @item Pointers including procedure pointers and those in a derived
1084 type (pointer components) can now be initialized by a target instead
1085 of only by @code{NULL}.
1087 @item The @code{EXIT} statement (with construct-name) can be now be
1088 used to leave not only the @code{DO} but also the @code{ASSOCIATE},
1089 @code{BLOCK}, @code{IF}, @code{SELECT CASE} and @code{SELECT TYPE}
1090 constructs.
1092 @item Internal procedures can now be used as actual argument.
1094 @item Minor features: obsolesce diagnostics for @code{ENTRY} with
1095 @option{-std=f2008}; a line may start with a semicolon; for internal
1096 and module procedures @code{END} can be used instead of
1097 @code{END SUBROUTINE} and @code{END FUNCTION}; @code{SELECTED_REAL_KIND}
1098 now also takes a @code{RADIX} argument; intrinsic types are supported
1099 for @code{TYPE}(@var{intrinsic-type-spec}); multiple type-bound procedures
1100 can be declared in a single @code{PROCEDURE} statement; implied-shape
1101 arrays are supported for named constants (@code{PARAMETER}).
1102 @end itemize
1106 @node TS 29113 status
1107 @section Technical Specification 29113 Status
1109 GNU Fortran supports some of the new features of the Technical
1110 Specification (TS) 29113 on Further Interoperability of Fortran with C.
1111 The @uref{https://gcc.gnu.org/wiki/TS29113Status, wiki} has some information
1112 about the current TS 29113 implementation status.  In particular, the
1113 following is implemented.
1115 See also @ref{Further Interoperability of Fortran with C}.
1117 @itemize
1118 @item The @option{-std=f2008ts} option.
1120 @item The @code{OPTIONAL} attribute is allowed for dummy arguments
1121 of @code{BIND(C) procedures.}
1123 @item The @code{RANK} intrinsic is supported.
1125 @item GNU Fortran's implementation for variables with @code{ASYNCHRONOUS}
1126 attribute is compatible with TS 29113.
1128 @item Assumed types (@code{TYPE(*)}).
1130 @item Assumed-rank (@code{DIMENSION(..)}). However, the array descriptor
1131 of the TS is not yet supported.
1132 @end itemize
1135 @node TS 18508 status
1136 @section Technical Specification 18508 Status
1138 GNU Fortran supports the following new features of the Technical
1139 Specification 18508 on Additional Parallel Features in Fortran:
1141 @itemize
1142 @item The new atomic ADD, CAS, FETCH and ADD/OR/XOR, OR and XOR intrinsics.
1144 @item The @code{CO_MIN} and @code{CO_MAX} and @code{SUM} reduction intrinsics.
1145 And the @code{CO_BROADCAST} and @code{CO_REDUCE} intrinsic, except that those
1146 do not support polymorphic types or types with allocatable, pointer or
1147 polymorphic components.
1149 @item Events (@code{EVENT POST}, @code{EVENT WAIT}, @code{EVENT_QUERY})
1151 @item Failed images (@code{FAIL IMAGE}, @code{IMAGE_STATUS},
1152 @code{FAILED_IMAGES}, @code{STOPPED_IMAGES})
1154 @end itemize
1157 @c ---------------------------------------------------------------------
1158 @c Compiler Characteristics
1159 @c ---------------------------------------------------------------------
1161 @node Compiler Characteristics
1162 @chapter Compiler Characteristics
1164 This chapter describes certain characteristics of the GNU Fortran
1165 compiler, that are not specified by the Fortran standard, but which
1166 might in some way or another become visible to the programmer.
1168 @menu
1169 * KIND Type Parameters::
1170 * Internal representation of LOGICAL variables::
1171 * Thread-safety of the runtime library::
1172 * Data consistency and durability::
1173 * Files opened without an explicit ACTION= specifier::
1174 * File operations on symbolic links::
1175 * File format of unformatted sequential files::
1176 @end menu
1179 @node KIND Type Parameters
1180 @section KIND Type Parameters
1181 @cindex kind
1183 The @code{KIND} type parameters supported by GNU Fortran for the primitive
1184 data types are:
1186 @table @code
1188 @item INTEGER
1189 1, 2, 4, 8*, 16*, default: 4**
1191 @item LOGICAL
1192 1, 2, 4, 8*, 16*, default: 4**
1194 @item REAL
1195 4, 8, 10*, 16*, default: 4***
1197 @item COMPLEX
1198 4, 8, 10*, 16*, default: 4***
1200 @item DOUBLE PRECISION
1201 4, 8, 10*, 16*, default: 8***
1203 @item CHARACTER
1204 1, 4, default: 1
1206 @end table
1208 @noindent
1209 * not available on all systems @*
1210 ** unless @option{-fdefault-integer-8} is used @*
1211 *** unless @option{-fdefault-real-8} is used (see @ref{Fortran Dialect Options})
1213 @noindent
1214 The @code{KIND} value matches the storage size in bytes, except for
1215 @code{COMPLEX} where the storage size is twice as much (or both real and
1216 imaginary part are a real value of the given size).  It is recommended to use
1217 the @ref{SELECTED_CHAR_KIND}, @ref{SELECTED_INT_KIND} and
1218 @ref{SELECTED_REAL_KIND} intrinsics or the @code{INT8}, @code{INT16},
1219 @code{INT32}, @code{INT64}, @code{REAL32}, @code{REAL64}, and @code{REAL128}
1220 parameters of the @code{ISO_FORTRAN_ENV} module instead of the concrete values.
1221 The available kind parameters can be found in the constant arrays
1222 @code{CHARACTER_KINDS}, @code{INTEGER_KINDS}, @code{LOGICAL_KINDS} and
1223 @code{REAL_KINDS} in the @ref{ISO_FORTRAN_ENV} module.  For C interoperability,
1224 the kind parameters of the @ref{ISO_C_BINDING} module should be used.
1227 @node Internal representation of LOGICAL variables
1228 @section Internal representation of LOGICAL variables
1229 @cindex logical, variable representation
1231 The Fortran standard does not specify how variables of @code{LOGICAL}
1232 type are represented, beyond requiring that @code{LOGICAL} variables
1233 of default kind have the same storage size as default @code{INTEGER}
1234 and @code{REAL} variables.  The GNU Fortran internal representation is
1235 as follows.
1237 A @code{LOGICAL(KIND=N)} variable is represented as an
1238 @code{INTEGER(KIND=N)} variable, however, with only two permissible
1239 values: @code{1} for @code{.TRUE.} and @code{0} for
1240 @code{.FALSE.}.  Any other integer value results in undefined behavior.
1242 See also @ref{Argument passing conventions} and @ref{Interoperability with C}.
1245 @node Thread-safety of the runtime library
1246 @section Thread-safety of the runtime library
1247 @cindex thread-safety, threads
1249 GNU Fortran can be used in programs with multiple threads, e.g.@: by
1250 using OpenMP, by calling OS thread handling functions via the
1251 @code{ISO_C_BINDING} facility, or by GNU Fortran compiled library code
1252 being called from a multi-threaded program.
1254 The GNU Fortran runtime library, (@code{libgfortran}), supports being
1255 called concurrently from multiple threads with the following
1256 exceptions. 
1258 During library initialization, the C @code{getenv} function is used,
1259 which need not be thread-safe.  Similarly, the @code{getenv}
1260 function is used to implement the @code{GET_ENVIRONMENT_VARIABLE} and
1261 @code{GETENV} intrinsics.  It is the responsibility of the user to
1262 ensure that the environment is not being updated concurrently when any
1263 of these actions are taking place.
1265 The @code{EXECUTE_COMMAND_LINE} and @code{SYSTEM} intrinsics are
1266 implemented with the @code{system} function, which need not be
1267 thread-safe.  It is the responsibility of the user to ensure that
1268 @code{system} is not called concurrently.
1270 For platforms not supporting thread-safe POSIX functions, further
1271 functionality might not be thread-safe.  For details, please consult
1272 the documentation for your operating system.
1274 The GNU Fortran runtime library uses various C library functions that
1275 depend on the locale, such as @code{strtod} and @code{snprintf}.  In
1276 order to work correctly in locale-aware programs that set the locale
1277 using @code{setlocale}, the locale is reset to the default ``C''
1278 locale while executing a formatted @code{READ} or @code{WRITE}
1279 statement.  On targets supporting the POSIX 2008 per-thread locale
1280 functions (e.g. @code{newlocale}, @code{uselocale},
1281 @code{freelocale}), these are used and thus the global locale set
1282 using @code{setlocale} or the per-thread locales in other threads are
1283 not affected.  However, on targets lacking this functionality, the
1284 global LC_NUMERIC locale is set to ``C'' during the formatted I/O.
1285 Thus, on such targets it's not safe to call @code{setlocale}
1286 concurrently from another thread while a Fortran formatted I/O
1287 operation is in progress.  Also, other threads doing something
1288 dependent on the LC_NUMERIC locale might not work correctly if a
1289 formatted I/O operation is in progress in another thread.
1291 @node Data consistency and durability
1292 @section Data consistency and durability
1293 @cindex consistency, durability
1295 This section contains a brief overview of data and metadata
1296 consistency and durability issues when doing I/O.
1298 With respect to durability, GNU Fortran makes no effort to ensure that
1299 data is committed to stable storage. If this is required, the GNU
1300 Fortran programmer can use the intrinsic @code{FNUM} to retrieve the
1301 low level file descriptor corresponding to an open Fortran unit. Then,
1302 using e.g. the @code{ISO_C_BINDING} feature, one can call the
1303 underlying system call to flush dirty data to stable storage, such as
1304 @code{fsync} on POSIX, @code{_commit} on MingW, or @code{fcntl(fd,
1305 F_FULLSYNC, 0)} on Mac OS X. The following example shows how to call
1306 fsync:
1308 @smallexample
1309   ! Declare the interface for POSIX fsync function
1310   interface
1311     function fsync (fd) bind(c,name="fsync")
1312     use iso_c_binding, only: c_int
1313       integer(c_int), value :: fd
1314       integer(c_int) :: fsync
1315     end function fsync
1316   end interface
1318   ! Variable declaration
1319   integer :: ret
1321   ! Opening unit 10
1322   open (10,file="foo")
1324   ! ...
1325   ! Perform I/O on unit 10
1326   ! ...
1328   ! Flush and sync
1329   flush(10)
1330   ret = fsync(fnum(10))
1332   ! Handle possible error
1333   if (ret /= 0) stop "Error calling FSYNC"
1334 @end smallexample
1336 With respect to consistency, for regular files GNU Fortran uses
1337 buffered I/O in order to improve performance. This buffer is flushed
1338 automatically when full and in some other situations, e.g. when
1339 closing a unit. It can also be explicitly flushed with the
1340 @code{FLUSH} statement. Also, the buffering can be turned off with the
1341 @code{GFORTRAN_UNBUFFERED_ALL} and
1342 @code{GFORTRAN_UNBUFFERED_PRECONNECTED} environment variables. Special
1343 files, such as terminals and pipes, are always unbuffered. Sometimes,
1344 however, further things may need to be done in order to allow other
1345 processes to see data that GNU Fortran has written, as follows.
1347 The Windows platform supports a relaxed metadata consistency model,
1348 where file metadata is written to the directory lazily. This means
1349 that, for instance, the @code{dir} command can show a stale size for a
1350 file. One can force a directory metadata update by closing the unit,
1351 or by calling @code{_commit} on the file descriptor. Note, though,
1352 that @code{_commit} will force all dirty data to stable storage, which
1353 is often a very slow operation.
1355 The Network File System (NFS) implements a relaxed consistency model
1356 called open-to-close consistency. Closing a file forces dirty data and
1357 metadata to be flushed to the server, and opening a file forces the
1358 client to contact the server in order to revalidate cached
1359 data. @code{fsync} will also force a flush of dirty data and metadata
1360 to the server. Similar to @code{open} and @code{close}, acquiring and
1361 releasing @code{fcntl} file locks, if the server supports them, will
1362 also force cache validation and flushing dirty data and metadata.
1365 @node Files opened without an explicit ACTION= specifier
1366 @section Files opened without an explicit ACTION= specifier
1367 @cindex open, action
1369 The Fortran standard says that if an @code{OPEN} statement is executed
1370 without an explicit @code{ACTION=} specifier, the default value is
1371 processor dependent.  GNU Fortran behaves as follows:
1373 @enumerate
1374 @item Attempt to open the file with @code{ACTION='READWRITE'}
1375 @item If that fails, try to open with @code{ACTION='READ'}
1376 @item If that fails, try to open with @code{ACTION='WRITE'}
1377 @item If that fails, generate an error
1378 @end enumerate
1381 @node File operations on symbolic links
1382 @section File operations on symbolic links
1383 @cindex file, symbolic link
1385 This section documents the behavior of GNU Fortran for file operations on
1386 symbolic links, on systems that support them. 
1388 @itemize
1390 @item Results of INQUIRE statements of the ``inquire by file'' form will
1391 relate to the target of the symbolic link. For example,
1392 @code{INQUIRE(FILE="foo",EXIST=ex)} will set @var{ex} to @var{.true.} if
1393 @var{foo} is a symbolic link pointing to an existing file, and @var{.false.}
1394 if @var{foo} points to an non-existing file (``dangling'' symbolic link).
1396 @item Using the @code{OPEN} statement with a @code{STATUS="NEW"} specifier
1397 on a symbolic link will result in an error condition, whether the symbolic
1398 link points to an existing target or is dangling.
1400 @item If a symbolic link was connected, using the @code{CLOSE} statement
1401 with a @code{STATUS="DELETE"} specifier will cause the symbolic link itself
1402 to be deleted, not its target.
1404 @end itemize
1406 @node File format of unformatted sequential files
1407 @section File format of unformatted sequential files
1408 @cindex file, unformatted sequential
1409 @cindex unformatted sequential
1410 @cindex sequential, unformatted
1411 @cindex record marker
1412 @cindex subrecord
1414 Unformatted sequential files are stored as logical records using
1415 record markers.  Each logical record consists of one of more
1416 subrecords.
1418 Each subrecord consists of a leading record marker, the data written
1419 by the user program, and a trailing record marker.  The record markers
1420 are four-byte integers by default, and eight-byte integers if the
1421 @option{-fmax-subrecord-length=8} option (which exists for backwards
1422 compability only) is in effect.
1424 The representation of the record markers is that of unformatted files
1425 given with the @option{-fconvert} option, the @xref{CONVERT specifier}
1426 on the open statement or the @xref{GFORTRAN_CONVERT_UNIT} environment
1427 variable.
1429 The maximum number of bytes of user data in a subrecord is 2147483639
1430 (2 GiB - 9) for a four-byte record marker.  This limit can be lowered
1431 with the @option{-fmax-subrecord-length} option, altough this is
1432 rarely useful. If the length of a logical record exceeds this limit,
1433 the data is distributed among several subrecords.
1435 The absolute of the number stored in the record markers is the number
1436 of bytes of user data in the corresponding subrecord.  If the leading
1437 record marker of a subrecord contains a negative number, another
1438 subrecord follows the current one.  If the trailing record marker
1439 contains a negative number, then there is a preceding subrecord.
1441 In the most simple case, with only one subrecord per logical record,
1442 both record markers contain the number of bytes of user data in the
1443 record,
1445 The format for unformatted sequential data can be duplicated using
1446 unformatted stream, as shown in the example program for an unformatted
1447 record containing a single subrecord:
1449 @smallexample
1450 program main
1451   use iso_fortran_env, only: int32
1452   implicit none
1453   integer(int32) :: i 
1454   real, dimension(10) :: a, b
1455   call random_number(a)
1456   open (10,file='test.dat',form='unformatted',access='stream')
1457   inquire (iolength=i) a
1458   write (10) i, a, i
1459   close (10)
1460   open (10,file='test.dat',form='unformatted')
1461   read (10) b
1462   if (all (a == b)) print *,'success!'
1463 end program main
1464 @end smallexample
1466 @c ---------------------------------------------------------------------
1467 @c Extensions
1468 @c ---------------------------------------------------------------------
1470 @c Maybe this chapter should be merged with the 'Standards' section,
1471 @c whenever that is written :-)
1473 @node Extensions
1474 @chapter Extensions
1475 @cindex extensions
1477 The two sections below detail the extensions to standard Fortran that are
1478 implemented in GNU Fortran, as well as some of the popular or
1479 historically important extensions that are not (or not yet) implemented.
1480 For the latter case, we explain the alternatives available to GNU Fortran
1481 users, including replacement by standard-conforming code or GNU
1482 extensions.
1484 @menu
1485 * Extensions implemented in GNU Fortran::
1486 * Extensions not implemented in GNU Fortran::
1487 @end menu
1490 @node Extensions implemented in GNU Fortran
1491 @section Extensions implemented in GNU Fortran
1492 @cindex extensions, implemented
1494 GNU Fortran implements a number of extensions over standard
1495 Fortran.  This chapter contains information on their syntax and
1496 meaning.  There are currently two categories of GNU Fortran
1497 extensions, those that provide functionality beyond that provided
1498 by any standard, and those that are supported by GNU Fortran
1499 purely for backward compatibility with legacy compilers.  By default,
1500 @option{-std=gnu} allows the compiler to accept both types of
1501 extensions, but to warn about the use of the latter.  Specifying
1502 either @option{-std=f95}, @option{-std=f2003} or @option{-std=f2008}
1503 disables both types of extensions, and @option{-std=legacy} allows both
1504 without warning.  The special compile flag @option{-fdec} enables additional
1505 compatibility extensions along with those enabled by @option{-std=legacy}.
1507 @menu
1508 * Old-style kind specifications::
1509 * Old-style variable initialization::
1510 * Extensions to namelist::
1511 * X format descriptor without count field::
1512 * Commas in FORMAT specifications::
1513 * Missing period in FORMAT specifications::
1514 * I/O item lists::
1515 * @code{Q} exponent-letter::
1516 * BOZ literal constants::
1517 * Real array indices::
1518 * Unary operators::
1519 * Implicitly convert LOGICAL and INTEGER values::
1520 * Hollerith constants support::
1521 * Cray pointers::
1522 * CONVERT specifier::
1523 * OpenMP::
1524 * OpenACC::
1525 * Argument list functions::
1526 * Read/Write after EOF marker::
1527 * STRUCTURE and RECORD::
1528 * UNION and MAP::
1529 * Type variants for integer intrinsics::
1530 * AUTOMATIC and STATIC attributes::
1531 * Extended math intrinsics::
1532 * Form feed as whitespace::
1533 * TYPE as an alias for PRINT::
1534 * %LOC as an rvalue::
1535 * .XOR. operator::
1536 * Bitwise logical operators::
1537 * Extended I/O specifiers::
1538 * Legacy PARAMETER statements::
1539 * Default exponents::
1540 @end menu
1542 @node Old-style kind specifications
1543 @subsection Old-style kind specifications
1544 @cindex kind, old-style
1546 GNU Fortran allows old-style kind specifications in declarations.  These
1547 look like:
1548 @smallexample
1549       TYPESPEC*size x,y,z
1550 @end smallexample
1551 @noindent
1552 where @code{TYPESPEC} is a basic type (@code{INTEGER}, @code{REAL},
1553 etc.), and where @code{size} is a byte count corresponding to the
1554 storage size of a valid kind for that type.  (For @code{COMPLEX}
1555 variables, @code{size} is the total size of the real and imaginary
1556 parts.)  The statement then declares @code{x}, @code{y} and @code{z} to
1557 be of type @code{TYPESPEC} with the appropriate kind.  This is
1558 equivalent to the standard-conforming declaration
1559 @smallexample
1560       TYPESPEC(k) x,y,z
1561 @end smallexample
1562 @noindent
1563 where @code{k} is the kind parameter suitable for the intended precision.  As
1564 kind parameters are implementation-dependent, use the @code{KIND},
1565 @code{SELECTED_INT_KIND} and @code{SELECTED_REAL_KIND} intrinsics to retrieve
1566 the correct value, for instance @code{REAL*8 x} can be replaced by:
1567 @smallexample
1568 INTEGER, PARAMETER :: dbl = KIND(1.0d0)
1569 REAL(KIND=dbl) :: x
1570 @end smallexample
1572 @node Old-style variable initialization
1573 @subsection Old-style variable initialization
1575 GNU Fortran allows old-style initialization of variables of the
1576 form:
1577 @smallexample
1578       INTEGER i/1/,j/2/
1579       REAL x(2,2) /3*0.,1./
1580 @end smallexample
1581 The syntax for the initializers is as for the @code{DATA} statement, but
1582 unlike in a @code{DATA} statement, an initializer only applies to the
1583 variable immediately preceding the initialization.  In other words,
1584 something like @code{INTEGER I,J/2,3/} is not valid.  This style of
1585 initialization is only allowed in declarations without double colons
1586 (@code{::}); the double colons were introduced in Fortran 90, which also
1587 introduced a standard syntax for initializing variables in type
1588 declarations.
1590 Examples of standard-conforming code equivalent to the above example
1591 are:
1592 @smallexample
1593 ! Fortran 90
1594       INTEGER :: i = 1, j = 2
1595       REAL :: x(2,2) = RESHAPE((/0.,0.,0.,1./),SHAPE(x))
1596 ! Fortran 77
1597       INTEGER i, j
1598       REAL x(2,2)
1599       DATA i/1/, j/2/, x/3*0.,1./
1600 @end smallexample
1602 Note that variables which are explicitly initialized in declarations
1603 or in @code{DATA} statements automatically acquire the @code{SAVE}
1604 attribute.
1606 @node Extensions to namelist
1607 @subsection Extensions to namelist
1608 @cindex Namelist
1610 GNU Fortran fully supports the Fortran 95 standard for namelist I/O
1611 including array qualifiers, substrings and fully qualified derived types.
1612 The output from a namelist write is compatible with namelist read.  The
1613 output has all names in upper case and indentation to column 1 after the
1614 namelist name.  Two extensions are permitted:
1616 Old-style use of @samp{$} instead of @samp{&}
1617 @smallexample
1618 $MYNML
1619  X(:)%Y(2) = 1.0 2.0 3.0
1620  CH(1:4) = "abcd"
1621 $END
1622 @end smallexample
1624 It should be noted that the default terminator is @samp{/} rather than
1625 @samp{&END}.
1627 Querying of the namelist when inputting from stdin.  After at least
1628 one space, entering @samp{?} sends to stdout the namelist name and the names of
1629 the variables in the namelist:
1630 @smallexample
1633 &mynml
1635  x%y
1636  ch
1637 &end
1638 @end smallexample
1640 Entering @samp{=?} outputs the namelist to stdout, as if
1641 @code{WRITE(*,NML = mynml)} had been called:
1642 @smallexample
1645 &MYNML
1646  X(1)%Y=  0.000000    ,  1.000000    ,  0.000000    ,
1647  X(2)%Y=  0.000000    ,  2.000000    ,  0.000000    ,
1648  X(3)%Y=  0.000000    ,  3.000000    ,  0.000000    ,
1649  CH=abcd,  /
1650 @end smallexample
1652 To aid this dialog, when input is from stdin, errors send their
1653 messages to stderr and execution continues, even if @code{IOSTAT} is set.
1655 @code{PRINT} namelist is permitted.  This causes an error if
1656 @option{-std=f95} is used.
1657 @smallexample
1658 PROGRAM test_print
1659   REAL, dimension (4)  ::  x = (/1.0, 2.0, 3.0, 4.0/)
1660   NAMELIST /mynml/ x
1661   PRINT mynml
1662 END PROGRAM test_print
1663 @end smallexample
1665 Expanded namelist reads are permitted.  This causes an error if 
1666 @option{-std=f95} is used.  In the following example, the first element
1667 of the array will be given the value 0.00 and the two succeeding
1668 elements will be given the values 1.00 and 2.00.
1669 @smallexample
1670 &MYNML
1671   X(1,1) = 0.00 , 1.00 , 2.00
1673 @end smallexample
1675 When writing a namelist, if no @code{DELIM=} is specified, by default a
1676 double quote is used to delimit character strings. If -std=F95, F2003,
1677 or F2008, etc, the delim status is set to 'none'.  Defaulting to
1678 quotes ensures that namelists with character strings can be subsequently
1679 read back in accurately.
1681 @node X format descriptor without count field
1682 @subsection @code{X} format descriptor without count field
1684 To support legacy codes, GNU Fortran permits the count field of the
1685 @code{X} edit descriptor in @code{FORMAT} statements to be omitted.
1686 When omitted, the count is implicitly assumed to be one.
1688 @smallexample
1689        PRINT 10, 2, 3
1690 10     FORMAT (I1, X, I1)
1691 @end smallexample
1693 @node Commas in FORMAT specifications
1694 @subsection Commas in @code{FORMAT} specifications
1696 To support legacy codes, GNU Fortran allows the comma separator
1697 to be omitted immediately before and after character string edit
1698 descriptors in @code{FORMAT} statements.
1700 @smallexample
1701        PRINT 10, 2, 3
1702 10     FORMAT ('FOO='I1' BAR='I2)
1703 @end smallexample
1706 @node Missing period in FORMAT specifications
1707 @subsection Missing period in @code{FORMAT} specifications
1709 To support legacy codes, GNU Fortran allows missing periods in format
1710 specifications if and only if @option{-std=legacy} is given on the
1711 command line.  This is considered non-conforming code and is
1712 discouraged.
1714 @smallexample
1715        REAL :: value
1716        READ(*,10) value
1717 10     FORMAT ('F4')
1718 @end smallexample
1720 @node I/O item lists
1721 @subsection I/O item lists
1722 @cindex I/O item lists
1724 To support legacy codes, GNU Fortran allows the input item list
1725 of the @code{READ} statement, and the output item lists of the
1726 @code{WRITE} and @code{PRINT} statements, to start with a comma.
1728 @node @code{Q} exponent-letter
1729 @subsection @code{Q} exponent-letter
1730 @cindex @code{Q} exponent-letter
1732 GNU Fortran accepts real literal constants with an exponent-letter
1733 of @code{Q}, for example, @code{1.23Q45}.  The constant is interpreted
1734 as a @code{REAL(16)} entity on targets that support this type.  If
1735 the target does not support @code{REAL(16)} but has a @code{REAL(10)}
1736 type, then the real-literal-constant will be interpreted as a
1737 @code{REAL(10)} entity.  In the absence of @code{REAL(16)} and
1738 @code{REAL(10)}, an error will occur.
1740 @node BOZ literal constants
1741 @subsection BOZ literal constants
1742 @cindex BOZ literal constants
1744 Besides decimal constants, Fortran also supports binary (@code{b}),
1745 octal (@code{o}) and hexadecimal (@code{z}) integer constants.  The
1746 syntax is: @samp{prefix quote digits quote}, were the prefix is
1747 either @code{b}, @code{o} or @code{z}, quote is either @code{'} or
1748 @code{"} and the digits are for binary @code{0} or @code{1}, for
1749 octal between @code{0} and @code{7}, and for hexadecimal between
1750 @code{0} and @code{F}.  (Example: @code{b'01011101'}.)
1752 Up to Fortran 95, BOZ literals were only allowed to initialize
1753 integer variables in DATA statements.  Since Fortran 2003 BOZ literals
1754 are also allowed as argument of @code{REAL}, @code{DBLE}, @code{INT}
1755 and @code{CMPLX}; the result is the same as if the integer BOZ
1756 literal had been converted by @code{TRANSFER} to, respectively,
1757 @code{real}, @code{double precision}, @code{integer} or @code{complex}.
1758 As GNU Fortran extension the intrinsic procedures @code{FLOAT},
1759 @code{DFLOAT}, @code{COMPLEX} and @code{DCMPLX} are treated alike.
1761 As an extension, GNU Fortran allows hexadecimal BOZ literal constants to
1762 be specified using the @code{X} prefix, in addition to the standard
1763 @code{Z} prefix.  The BOZ literal can also be specified by adding a
1764 suffix to the string, for example, @code{Z'ABC'} and @code{'ABC'Z} are
1765 equivalent.
1767 Furthermore, GNU Fortran allows using BOZ literal constants outside
1768 DATA statements and the four intrinsic functions allowed by Fortran 2003.
1769 In DATA statements, in direct assignments, where the right-hand side
1770 only contains a BOZ literal constant, and for old-style initializers of
1771 the form @code{integer i /o'0173'/}, the constant is transferred
1772 as if @code{TRANSFER} had been used; for @code{COMPLEX} numbers, only
1773 the real part is initialized unless @code{CMPLX} is used.  In all other
1774 cases, the BOZ literal constant is converted to an @code{INTEGER} value with
1775 the largest decimal representation.  This value is then converted
1776 numerically to the type and kind of the variable in question.
1777 (For instance, @code{real :: r = b'0000001' + 1} initializes @code{r}
1778 with @code{2.0}.) As different compilers implement the extension
1779 differently, one should be careful when doing bitwise initialization
1780 of non-integer variables.
1782 Note that initializing an @code{INTEGER} variable with a statement such
1783 as @code{DATA i/Z'FFFFFFFF'/} will give an integer overflow error rather
1784 than the desired result of @math{-1} when @code{i} is a 32-bit integer
1785 on a system that supports 64-bit integers.  The @samp{-fno-range-check}
1786 option can be used as a workaround for legacy code that initializes
1787 integers in this manner.
1789 @node Real array indices
1790 @subsection Real array indices
1791 @cindex array, indices of type real
1793 As an extension, GNU Fortran allows the use of @code{REAL} expressions
1794 or variables as array indices.
1796 @node Unary operators
1797 @subsection Unary operators
1798 @cindex operators, unary
1800 As an extension, GNU Fortran allows unary plus and unary minus operators
1801 to appear as the second operand of binary arithmetic operators without
1802 the need for parenthesis.
1804 @smallexample
1805        X = Y * -Z
1806 @end smallexample
1808 @node Implicitly convert LOGICAL and INTEGER values
1809 @subsection Implicitly convert @code{LOGICAL} and @code{INTEGER} values
1810 @cindex conversion, to integer
1811 @cindex conversion, to logical
1813 As an extension for backwards compatibility with other compilers, GNU
1814 Fortran allows the implicit conversion of @code{LOGICAL} values to
1815 @code{INTEGER} values and vice versa.  When converting from a
1816 @code{LOGICAL} to an @code{INTEGER}, @code{.FALSE.} is interpreted as
1817 zero, and @code{.TRUE.} is interpreted as one.  When converting from
1818 @code{INTEGER} to @code{LOGICAL}, the value zero is interpreted as
1819 @code{.FALSE.} and any nonzero value is interpreted as @code{.TRUE.}.
1821 @smallexample
1822         LOGICAL :: l
1823         l = 1
1824 @end smallexample
1825 @smallexample
1826         INTEGER :: i
1827         i = .TRUE.
1828 @end smallexample
1830 However, there is no implicit conversion of @code{INTEGER} values in
1831 @code{if}-statements, nor of @code{LOGICAL} or @code{INTEGER} values
1832 in I/O operations.
1834 @node Hollerith constants support
1835 @subsection Hollerith constants support
1836 @cindex Hollerith constants
1838 GNU Fortran supports Hollerith constants in assignments, function
1839 arguments, and @code{DATA} and @code{ASSIGN} statements.  A Hollerith
1840 constant is written as a string of characters preceded by an integer
1841 constant indicating the character count, and the letter @code{H} or
1842 @code{h}, and stored in bytewise fashion in a numeric (@code{INTEGER},
1843 @code{REAL}, or @code{complex}) or @code{LOGICAL} variable.  The
1844 constant will be padded or truncated to fit the size of the variable in
1845 which it is stored.
1847 Examples of valid uses of Hollerith constants:
1848 @smallexample
1849       complex*16 x(2)
1850       data x /16Habcdefghijklmnop, 16Hqrstuvwxyz012345/
1851       x(1) = 16HABCDEFGHIJKLMNOP
1852       call foo (4h abc)
1853 @end smallexample
1855 Invalid Hollerith constants examples:
1856 @smallexample
1857       integer*4 a
1858       a = 8H12345678 ! Valid, but the Hollerith constant will be truncated.
1859       a = 0H         ! At least one character is needed.
1860 @end smallexample
1862 In general, Hollerith constants were used to provide a rudimentary
1863 facility for handling character strings in early Fortran compilers,
1864 prior to the introduction of @code{CHARACTER} variables in Fortran 77;
1865 in those cases, the standard-compliant equivalent is to convert the
1866 program to use proper character strings.  On occasion, there may be a
1867 case where the intent is specifically to initialize a numeric variable
1868 with a given byte sequence.  In these cases, the same result can be
1869 obtained by using the @code{TRANSFER} statement, as in this example.
1870 @smallexample
1871       INTEGER(KIND=4) :: a
1872       a = TRANSFER ("abcd", a)     ! equivalent to: a = 4Habcd
1873 @end smallexample
1876 @node Cray pointers
1877 @subsection Cray pointers
1878 @cindex pointer, Cray
1880 Cray pointers are part of a non-standard extension that provides a
1881 C-like pointer in Fortran.  This is accomplished through a pair of
1882 variables: an integer "pointer" that holds a memory address, and a
1883 "pointee" that is used to dereference the pointer.
1885 Pointer/pointee pairs are declared in statements of the form:
1886 @smallexample
1887         pointer ( <pointer> , <pointee> )
1888 @end smallexample
1890 @smallexample
1891         pointer ( <pointer1> , <pointee1> ), ( <pointer2> , <pointee2> ), ...
1892 @end smallexample
1893 The pointer is an integer that is intended to hold a memory address.
1894 The pointee may be an array or scalar.  A pointee can be an assumed
1895 size array---that is, the last dimension may be left unspecified by
1896 using a @code{*} in place of a value---but a pointee cannot be an
1897 assumed shape array.  No space is allocated for the pointee.
1899 The pointee may have its type declared before or after the pointer
1900 statement, and its array specification (if any) may be declared
1901 before, during, or after the pointer statement.  The pointer may be
1902 declared as an integer prior to the pointer statement.  However, some
1903 machines have default integer sizes that are different than the size
1904 of a pointer, and so the following code is not portable:
1905 @smallexample
1906         integer ipt
1907         pointer (ipt, iarr)
1908 @end smallexample
1909 If a pointer is declared with a kind that is too small, the compiler
1910 will issue a warning; the resulting binary will probably not work
1911 correctly, because the memory addresses stored in the pointers may be
1912 truncated.  It is safer to omit the first line of the above example;
1913 if explicit declaration of ipt's type is omitted, then the compiler
1914 will ensure that ipt is an integer variable large enough to hold a
1915 pointer.
1917 Pointer arithmetic is valid with Cray pointers, but it is not the same
1918 as C pointer arithmetic.  Cray pointers are just ordinary integers, so
1919 the user is responsible for determining how many bytes to add to a
1920 pointer in order to increment it.  Consider the following example:
1921 @smallexample
1922         real target(10)
1923         real pointee(10)
1924         pointer (ipt, pointee)
1925         ipt = loc (target)
1926         ipt = ipt + 1       
1927 @end smallexample
1928 The last statement does not set @code{ipt} to the address of
1929 @code{target(1)}, as it would in C pointer arithmetic.  Adding @code{1}
1930 to @code{ipt} just adds one byte to the address stored in @code{ipt}.
1932 Any expression involving the pointee will be translated to use the
1933 value stored in the pointer as the base address.
1935 To get the address of elements, this extension provides an intrinsic
1936 function @code{LOC()}.  The @code{LOC()} function is equivalent to the
1937 @code{&} operator in C, except the address is cast to an integer type:
1938 @smallexample
1939         real ar(10)
1940         pointer(ipt, arpte(10))
1941         real arpte
1942         ipt = loc(ar)  ! Makes arpte is an alias for ar
1943         arpte(1) = 1.0 ! Sets ar(1) to 1.0
1944 @end smallexample
1945 The pointer can also be set by a call to the @code{MALLOC} intrinsic
1946 (see @ref{MALLOC}).
1948 Cray pointees often are used to alias an existing variable.  For
1949 example:
1950 @smallexample
1951         integer target(10)
1952         integer iarr(10)
1953         pointer (ipt, iarr)
1954         ipt = loc(target)
1955 @end smallexample
1956 As long as @code{ipt} remains unchanged, @code{iarr} is now an alias for
1957 @code{target}.  The optimizer, however, will not detect this aliasing, so
1958 it is unsafe to use @code{iarr} and @code{target} simultaneously.  Using
1959 a pointee in any way that violates the Fortran aliasing rules or
1960 assumptions is illegal.  It is the user's responsibility to avoid doing
1961 this; the compiler works under the assumption that no such aliasing
1962 occurs.
1964 Cray pointers will work correctly when there is no aliasing (i.e., when
1965 they are used to access a dynamically allocated block of memory), and
1966 also in any routine where a pointee is used, but any variable with which
1967 it shares storage is not used.  Code that violates these rules may not
1968 run as the user intends.  This is not a bug in the optimizer; any code
1969 that violates the aliasing rules is illegal.  (Note that this is not
1970 unique to GNU Fortran; any Fortran compiler that supports Cray pointers
1971 will ``incorrectly'' optimize code with illegal aliasing.)
1973 There are a number of restrictions on the attributes that can be applied
1974 to Cray pointers and pointees.  Pointees may not have the
1975 @code{ALLOCATABLE}, @code{INTENT}, @code{OPTIONAL}, @code{DUMMY},
1976 @code{TARGET}, @code{INTRINSIC}, or @code{POINTER} attributes.  Pointers
1977 may not have the @code{DIMENSION}, @code{POINTER}, @code{TARGET},
1978 @code{ALLOCATABLE}, @code{EXTERNAL}, or @code{INTRINSIC} attributes, nor
1979 may they be function results.  Pointees may not occur in more than one
1980 pointer statement.  A pointee cannot be a pointer.  Pointees cannot occur
1981 in equivalence, common, or data statements.
1983 A Cray pointer may also point to a function or a subroutine.  For
1984 example, the following excerpt is valid:
1985 @smallexample
1986   implicit none
1987   external sub
1988   pointer (subptr,subpte)
1989   external subpte
1990   subptr = loc(sub)
1991   call subpte()
1992   [...]
1993   subroutine sub
1994   [...]
1995   end subroutine sub
1996 @end smallexample
1998 A pointer may be modified during the course of a program, and this
1999 will change the location to which the pointee refers.  However, when
2000 pointees are passed as arguments, they are treated as ordinary
2001 variables in the invoked function.  Subsequent changes to the pointer
2002 will not change the base address of the array that was passed.
2004 @node CONVERT specifier
2005 @subsection @code{CONVERT} specifier
2006 @cindex @code{CONVERT} specifier
2008 GNU Fortran allows the conversion of unformatted data between little-
2009 and big-endian representation to facilitate moving of data
2010 between different systems.  The conversion can be indicated with
2011 the @code{CONVERT} specifier on the @code{OPEN} statement.
2012 @xref{GFORTRAN_CONVERT_UNIT}, for an alternative way of specifying
2013 the data format via an environment variable.
2015 Valid values for @code{CONVERT} are:
2016 @itemize @w{}
2017 @item @code{CONVERT='NATIVE'} Use the native format.  This is the default.
2018 @item @code{CONVERT='SWAP'} Swap between little- and big-endian.
2019 @item @code{CONVERT='LITTLE_ENDIAN'} Use the little-endian representation
2020 for unformatted files.
2021 @item @code{CONVERT='BIG_ENDIAN'} Use the big-endian representation for
2022 unformatted files.
2023 @end itemize
2025 Using the option could look like this:
2026 @smallexample
2027   open(file='big.dat',form='unformatted',access='sequential', &
2028        convert='big_endian')
2029 @end smallexample
2031 The value of the conversion can be queried by using
2032 @code{INQUIRE(CONVERT=ch)}.  The values returned are
2033 @code{'BIG_ENDIAN'} and @code{'LITTLE_ENDIAN'}.
2035 @code{CONVERT} works between big- and little-endian for
2036 @code{INTEGER} values of all supported kinds and for @code{REAL}
2037 on IEEE systems of kinds 4 and 8.  Conversion between different
2038 ``extended double'' types on different architectures such as
2039 m68k and x86_64, which GNU Fortran
2040 supports as @code{REAL(KIND=10)} and @code{REAL(KIND=16)}, will
2041 probably not work.
2043 @emph{Note that the values specified via the GFORTRAN_CONVERT_UNIT
2044 environment variable will override the CONVERT specifier in the
2045 open statement}.  This is to give control over data formats to
2046 users who do not have the source code of their program available.
2048 Using anything but the native representation for unformatted data
2049 carries a significant speed overhead.  If speed in this area matters
2050 to you, it is best if you use this only for data that needs to be
2051 portable.
2053 @node OpenMP
2054 @subsection OpenMP
2055 @cindex OpenMP
2057 OpenMP (Open Multi-Processing) is an application programming
2058 interface (API) that supports multi-platform shared memory 
2059 multiprocessing programming in C/C++ and Fortran on many 
2060 architectures, including Unix and Microsoft Windows platforms.
2061 It consists of a set of compiler directives, library routines,
2062 and environment variables that influence run-time behavior.
2064 GNU Fortran strives to be compatible to the 
2065 @uref{http://openmp.org/wp/openmp-specifications/,
2066 OpenMP Application Program Interface v4.5}.
2068 To enable the processing of the OpenMP directive @code{!$omp} in
2069 free-form source code; the @code{c$omp}, @code{*$omp} and @code{!$omp}
2070 directives in fixed form; the @code{!$} conditional compilation sentinels
2071 in free form; and the @code{c$}, @code{*$} and @code{!$} sentinels
2072 in fixed form, @command{gfortran} needs to be invoked with the
2073 @option{-fopenmp}.  This also arranges for automatic linking of the
2074 GNU Offloading and Multi Processing Runtime Library
2075 @ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
2076 Library}.
2078 The OpenMP Fortran runtime library routines are provided both in a
2079 form of a Fortran 90 module named @code{omp_lib} and in a form of
2080 a Fortran @code{include} file named @file{omp_lib.h}.
2082 An example of a parallelized loop taken from Appendix A.1 of
2083 the OpenMP Application Program Interface v2.5:
2084 @smallexample
2085 SUBROUTINE A1(N, A, B)
2086   INTEGER I, N
2087   REAL B(N), A(N)
2088 !$OMP PARALLEL DO !I is private by default
2089   DO I=2,N
2090     B(I) = (A(I) + A(I-1)) / 2.0
2091   ENDDO
2092 !$OMP END PARALLEL DO
2093 END SUBROUTINE A1
2094 @end smallexample
2096 Please note:
2097 @itemize
2098 @item
2099 @option{-fopenmp} implies @option{-frecursive}, i.e., all local arrays
2100 will be allocated on the stack.  When porting existing code to OpenMP,
2101 this may lead to surprising results, especially to segmentation faults
2102 if the stacksize is limited.
2104 @item
2105 On glibc-based systems, OpenMP enabled applications cannot be statically
2106 linked due to limitations of the underlying pthreads-implementation.  It
2107 might be possible to get a working solution if 
2108 @command{-Wl,--whole-archive -lpthread -Wl,--no-whole-archive} is added
2109 to the command line.  However, this is not supported by @command{gcc} and
2110 thus not recommended.
2111 @end itemize
2113 @node OpenACC
2114 @subsection OpenACC
2115 @cindex OpenACC
2117 OpenACC is an application programming interface (API) that supports
2118 offloading of code to accelerator devices.  It consists of a set of
2119 compiler directives, library routines, and environment variables that
2120 influence run-time behavior.
2122 GNU Fortran strives to be compatible to the
2123 @uref{http://www.openacc.org/, OpenACC Application Programming
2124 Interface v2.0}.
2126 To enable the processing of the OpenACC directive @code{!$acc} in
2127 free-form source code; the @code{c$acc}, @code{*$acc} and @code{!$acc}
2128 directives in fixed form; the @code{!$} conditional compilation
2129 sentinels in free form; and the @code{c$}, @code{*$} and @code{!$}
2130 sentinels in fixed form, @command{gfortran} needs to be invoked with
2131 the @option{-fopenacc}.  This also arranges for automatic linking of
2132 the GNU Offloading and Multi Processing Runtime Library
2133 @ref{Top,,libgomp,libgomp,GNU Offloading and Multi Processing Runtime
2134 Library}.
2136 The OpenACC Fortran runtime library routines are provided both in a
2137 form of a Fortran 90 module named @code{openacc} and in a form of a
2138 Fortran @code{include} file named @file{openacc_lib.h}.
2140 Note that this is an experimental feature, incomplete, and subject to
2141 change in future versions of GCC.  See
2142 @uref{https://gcc.gnu.org/wiki/OpenACC} for more information.
2144 @node Argument list functions
2145 @subsection Argument list functions @code{%VAL}, @code{%REF} and @code{%LOC}
2146 @cindex argument list functions
2147 @cindex @code{%VAL}
2148 @cindex @code{%REF}
2149 @cindex @code{%LOC}
2151 GNU Fortran supports argument list functions @code{%VAL}, @code{%REF} 
2152 and @code{%LOC} statements, for backward compatibility with g77. 
2153 It is recommended that these should be used only for code that is 
2154 accessing facilities outside of GNU Fortran, such as operating system 
2155 or windowing facilities.  It is best to constrain such uses to isolated 
2156 portions of a program--portions that deal specifically and exclusively 
2157 with low-level, system-dependent facilities.  Such portions might well 
2158 provide a portable interface for use by the program as a whole, but are 
2159 themselves not portable, and should be thoroughly tested each time they 
2160 are rebuilt using a new compiler or version of a compiler.
2162 @code{%VAL} passes a scalar argument by value, @code{%REF} passes it by 
2163 reference and @code{%LOC} passes its memory location.  Since gfortran 
2164 already passes scalar arguments by reference, @code{%REF} is in effect 
2165 a do-nothing.  @code{%LOC} has the same effect as a Fortran pointer.
2167 An example of passing an argument by value to a C subroutine foo.:
2168 @smallexample
2170 C prototype      void foo_ (float x);
2172       external foo
2173       real*4 x
2174       x = 3.14159
2175       call foo (%VAL (x))
2176       end
2177 @end smallexample
2179 For details refer to the g77 manual
2180 @uref{https://gcc.gnu.org/@/onlinedocs/@/gcc-3.4.6/@/g77/@/index.html#Top}.
2182 Also, @code{c_by_val.f} and its partner @code{c_by_val.c} of the
2183 GNU Fortran testsuite are worth a look.
2185 @node Read/Write after EOF marker
2186 @subsection Read/Write after EOF marker
2187 @cindex @code{EOF}
2188 @cindex @code{BACKSPACE}
2189 @cindex @code{REWIND}
2191 Some legacy codes rely on allowing @code{READ} or @code{WRITE} after the
2192 EOF file marker in order to find the end of a file. GNU Fortran normally
2193 rejects these codes with a run-time error message and suggests the user
2194 consider @code{BACKSPACE} or @code{REWIND} to properly position
2195 the file before the EOF marker.  As an extension, the run-time error may
2196 be disabled using -std=legacy.
2199 @node STRUCTURE and RECORD
2200 @subsection @code{STRUCTURE} and @code{RECORD}
2201 @cindex @code{STRUCTURE}
2202 @cindex @code{RECORD}
2204 Record structures are a pre-Fortran-90 vendor extension to create
2205 user-defined aggregate data types.  Support for record structures in GNU
2206 Fortran can be enabled with the @option{-fdec-structure} compile flag.
2207 If you have a choice, you should instead use Fortran 90's ``derived types'',
2208 which have a different syntax.
2210 In many cases, record structures can easily be converted to derived types.
2211 To convert, replace @code{STRUCTURE /}@var{structure-name}@code{/}
2212 by @code{TYPE} @var{type-name}.  Additionally, replace
2213 @code{RECORD /}@var{structure-name}@code{/} by
2214 @code{TYPE(}@var{type-name}@code{)}. Finally, in the component access,
2215 replace the period (@code{.}) by the percent sign (@code{%}).
2217 Here is an example of code using the non portable record structure syntax:
2219 @example
2220 ! Declaring a structure named ``item'' and containing three fields:
2221 ! an integer ID, an description string and a floating-point price.
2222 STRUCTURE /item/
2223   INTEGER id
2224   CHARACTER(LEN=200) description
2225   REAL price
2226 END STRUCTURE
2228 ! Define two variables, an single record of type ``item''
2229 ! named ``pear'', and an array of items named ``store_catalog''
2230 RECORD /item/ pear, store_catalog(100)
2232 ! We can directly access the fields of both variables
2233 pear.id = 92316
2234 pear.description = "juicy D'Anjou pear"
2235 pear.price = 0.15
2236 store_catalog(7).id = 7831
2237 store_catalog(7).description = "milk bottle"
2238 store_catalog(7).price = 1.2
2240 ! We can also manipulate the whole structure
2241 store_catalog(12) = pear
2242 print *, store_catalog(12)
2243 @end example
2245 @noindent
2246 This code can easily be rewritten in the Fortran 90 syntax as following:
2248 @example
2249 ! ``STRUCTURE /name/ ... END STRUCTURE'' becomes
2250 ! ``TYPE name ... END TYPE''
2251 TYPE item
2252   INTEGER id
2253   CHARACTER(LEN=200) description
2254   REAL price
2255 END TYPE
2257 ! ``RECORD /name/ variable'' becomes ``TYPE(name) variable''
2258 TYPE(item) pear, store_catalog(100)
2260 ! Instead of using a dot (.) to access fields of a record, the
2261 ! standard syntax uses a percent sign (%)
2262 pear%id = 92316
2263 pear%description = "juicy D'Anjou pear"
2264 pear%price = 0.15
2265 store_catalog(7)%id = 7831
2266 store_catalog(7)%description = "milk bottle"
2267 store_catalog(7)%price = 1.2
2269 ! Assignments of a whole variable do not change
2270 store_catalog(12) = pear
2271 print *, store_catalog(12)
2272 @end example
2274 @noindent
2275 GNU Fortran implements STRUCTURES like derived types with the following
2276 rules and exceptions:
2278 @itemize @bullet
2279 @item Structures act like derived types with the @code{SEQUENCE} attribute.
2280 Otherwise they may contain no specifiers.
2282 @item Structures may contain a special field with the name @code{%FILL}.
2283 This will create an anonymous component which cannot be accessed but occupies
2284 space just as if a component of the same type was declared in its place, useful
2285 for alignment purposes.  As an example, the following structure will consist
2286 of at least sixteen bytes:
2288 @smallexample
2289 structure /padded/
2290   character(4) start
2291   character(8) %FILL
2292   character(4) end
2293 end structure
2294 @end smallexample
2296 @item Structures may share names with other symbols. For example, the following
2297 is invalid for derived types, but valid for structures:
2299 @smallexample
2300 structure /header/
2301   ! ...
2302 end structure
2303 record /header/ header
2304 @end smallexample
2306 @item Structure types may be declared nested within another parent structure.
2307 The syntax is:
2308 @smallexample
2309 structure /type-name/
2310     ...
2311     structure [/<type-name>/] <field-list>
2313 @end smallexample
2315 The type name may be ommitted, in which case the structure type itself is
2316 anonymous, and other structures of the same type cannot be instantiated. The
2317 following shows some examples:
2319 @example
2320 structure /appointment/
2321   ! nested structure definition: app_time is an array of two 'time'
2322   structure /time/ app_time (2) 
2323     integer(1) hour, minute
2324   end structure
2325   character(10) memo
2326 end structure
2328 ! The 'time' structure is still usable
2329 record /time/ now
2330 now = time(5, 30)
2334 structure /appointment/
2335   ! anonymous nested structure definition
2336   structure start, end
2337     integer(1) hour, minute
2338   end structure
2339   character(10) memo
2340 end structure
2341 @end example
2343 @item Structures may contain @code{UNION} blocks. For more detail see the
2344 section on @ref{UNION and MAP}.
2346 @item Structures support old-style initialization of components, like
2347 those described in @ref{Old-style variable initialization}. For array
2348 initializers, an initializer may contain a repeat specification of the form
2349 @code{<literal-integer> * <constant-initializer>}. The value of the integer
2350 indicates the number of times to repeat the constant initializer when expanding
2351 the initializer list.
2352 @end itemize
2354 @node UNION and MAP
2355 @subsection @code{UNION} and @code{MAP}
2356 @cindex @code{UNION}
2357 @cindex @code{MAP}
2359 Unions are an old vendor extension which were commonly used with the
2360 non-standard @ref{STRUCTURE and RECORD} extensions. Use of @code{UNION} and
2361 @code{MAP} is automatically enabled with @option{-fdec-structure}.
2363 A @code{UNION} declaration occurs within a structure; within the definition of
2364 each union is a number of @code{MAP} blocks. Each @code{MAP} shares storage
2365 with its sibling maps (in the same union), and the size of the union is the
2366 size of the largest map within it, just as with unions in C. The major
2367 difference is that component references do not indicate which union or map the
2368 component is in (the compiler gets to figure that out).
2370 Here is a small example:
2371 @smallexample
2372 structure /myunion/
2373 union
2374   map
2375     character(2) w0, w1, w2
2376   end map
2377   map
2378     character(6) long
2379   end map
2380 end union
2381 end structure
2383 record /myunion/ rec
2384 ! After this assignment...
2385 rec.long = 'hello!'
2387 ! The following is true:
2388 ! rec.w0 === 'he'
2389 ! rec.w1 === 'll'
2390 ! rec.w2 === 'o!'
2391 @end smallexample
2393 The two maps share memory, and the size of the union is ultimately six bytes:
2395 @example
2396 0    1    2    3    4   5   6     Byte offset
2397 -------------------------------
2398 |    |    |    |    |    |    |
2399 -------------------------------
2401 ^    W0   ^    W1   ^    W2   ^
2402  \-------/ \-------/ \-------/
2404 ^             LONG            ^
2405  \---------------------------/
2406 @end example
2408 Following is an example mirroring the layout of an Intel x86_64 register:
2410 @example
2411 structure /reg/
2412   union ! U0                ! rax
2413     map
2414       character(16) rx
2415     end map
2416     map
2417       character(8) rh         ! rah
2418       union ! U1
2419         map
2420           character(8) rl     ! ral
2421         end map
2422         map
2423           character(8) ex     ! eax
2424         end map
2425         map
2426           character(4) eh     ! eah
2427           union ! U2
2428             map
2429               character(4) el ! eal
2430             end map
2431             map
2432               character(4) x  ! ax
2433             end map
2434             map
2435               character(2) h  ! ah
2436               character(2) l  ! al
2437             end map
2438           end union
2439         end map
2440       end union
2441     end map
2442   end union
2443 end structure
2444 record /reg/ a
2446 ! After this assignment...
2447 a.rx     =     'AAAAAAAA.BBB.C.D'
2449 ! The following is true:
2450 a.rx === 'AAAAAAAA.BBB.C.D'
2451 a.rh === 'AAAAAAAA'
2452 a.rl ===         '.BBB.C.D'
2453 a.ex ===         '.BBB.C.D'
2454 a.eh ===         '.BBB'
2455 a.el ===             '.C.D'
2456 a.x  ===             '.C.D'
2457 a.h  ===             '.C'
2458 a.l  ===               '.D'
2459 @end example
2461 @node Type variants for integer intrinsics
2462 @subsection Type variants for integer intrinsics
2463 @cindex intrinsics, integer
2465 Similar to the D/C prefixes to real functions to specify the input/output
2466 types, GNU Fortran offers B/I/J/K prefixes to integer functions for
2467 compatibility with DEC programs. The types implied by each are:
2469 @example
2470 @code{B} - @code{INTEGER(kind=1)}
2471 @code{I} - @code{INTEGER(kind=2)}
2472 @code{J} - @code{INTEGER(kind=4)}
2473 @code{K} - @code{INTEGER(kind=8)}
2474 @end example
2476 GNU Fortran supports these with the flag @option{-fdec-intrinsic-ints}.
2477 Intrinsics for which prefixed versions are available and in what form are noted
2478 in @ref{Intrinsic Procedures}. The complete list of supported intrinsics is
2479 here:
2481 @multitable @columnfractions .2 .2 .2 .2 .2
2483 @headitem Intrinsic @tab B @tab I @tab J @tab K
2485 @item @code{@ref{ABS}}
2486   @tab @code{BABS} @tab @code{IIABS} @tab @code{JIABS} @tab @code{KIABS}
2487 @item @code{@ref{BTEST}}
2488   @tab @code{BBTEST} @tab @code{BITEST} @tab @code{BJTEST} @tab @code{BKTEST}
2489 @item @code{@ref{IAND}}
2490   @tab @code{BIAND} @tab @code{IIAND} @tab @code{JIAND} @tab @code{KIAND}
2491 @item @code{@ref{IBCLR}}
2492   @tab @code{BBCLR} @tab @code{IIBCLR} @tab @code{JIBCLR} @tab @code{KIBCLR}
2493 @item @code{@ref{IBITS}}
2494   @tab @code{BBITS} @tab @code{IIBITS} @tab @code{JIBITS} @tab @code{KIBITS}
2495 @item @code{@ref{IBSET}}
2496   @tab @code{BBSET} @tab @code{IIBSET} @tab @code{JIBSET} @tab @code{KIBSET}
2497 @item @code{@ref{IEOR}}
2498   @tab @code{BIEOR} @tab @code{IIEOR} @tab @code{JIEOR} @tab @code{KIEOR}
2499 @item @code{@ref{IOR}}
2500   @tab @code{BIOR} @tab @code{IIOR} @tab @code{JIOR} @tab @code{KIOR}
2501 @item @code{@ref{ISHFT}}
2502   @tab @code{BSHFT} @tab @code{IISHFT} @tab @code{JISHFT} @tab @code{KISHFT}
2503 @item @code{@ref{ISHFTC}}
2504   @tab @code{BSHFTC} @tab @code{IISHFTC} @tab @code{JISHFTC} @tab @code{KISHFTC}
2505 @item @code{@ref{MOD}}
2506   @tab @code{BMOD} @tab @code{IMOD} @tab @code{JMOD} @tab @code{KMOD}
2507 @item @code{@ref{NOT}}
2508   @tab @code{BNOT} @tab @code{INOT} @tab @code{JNOT} @tab @code{KNOT}
2509 @item @code{@ref{REAL}}
2510   @tab @code{--} @tab @code{FLOATI} @tab @code{FLOATJ} @tab @code{FLOATK}
2511 @end multitable
2513 @node AUTOMATIC and STATIC attributes
2514 @subsection @code{AUTOMATIC} and @code{STATIC} attributes
2515 @cindex variable attributes
2516 @cindex @code{AUTOMATIC}
2517 @cindex @code{STATIC}
2519 With @option{-fdec-static} GNU Fortran supports the DEC extended attributes
2520 @code{STATIC} and @code{AUTOMATIC} to provide explicit specification of entity
2521 storage.  These follow the syntax of the Fortran standard @code{SAVE} attribute.
2523 @code{STATIC} is exactly equivalent to @code{SAVE}, and specifies that
2524 an entity should be allocated in static memory.  As an example, @code{STATIC}
2525 local variables will retain their values across multiple calls to a function.
2527 Entities marked @code{AUTOMATIC} will be stack automatic whenever possible.
2528 @code{AUTOMATIC} is the default for local variables smaller than
2529 @option{-fmax-stack-var-size}, unless @option{-fno-automatic} is given.  This
2530 attribute overrides @option{-fno-automatic}, @option{-fmax-stack-var-size}, and
2531 blanket @code{SAVE} statements.
2534 Examples:
2536 @example
2537 subroutine f
2538   integer, automatic :: i  ! automatic variable
2539   integer x, y             ! static variables
2540   save
2541   ...
2542 endsubroutine
2543 @end example
2544 @example
2545 subroutine f
2546   integer a, b, c, x, y, z
2547   static :: x
2548   save y
2549   automatic z, c
2550   ! a, b, c, and z are automatic
2551   ! x and y are static
2552 endsubroutine
2553 @end example
2554 @example
2555 ! Compiled with -fno-automatic
2556 subroutine f
2557   integer a, b, c, d
2558   automatic :: a
2559   ! a is automatic; b, c, and d are static
2560 endsubroutine
2561 @end example
2563 @node Extended math intrinsics
2564 @subsection Extended math intrinsics
2565 @cindex intrinsics, math
2566 @cindex intrinsics, trigonometric functions
2568 GNU Fortran supports an extended list of mathematical intrinsics with the
2569 compile flag @option{-fdec-math} for compatability with legacy code.
2570 These intrinsics are described fully in @ref{Intrinsic Procedures} where it is
2571 noted that they are extensions and should be avoided whenever possible.
2573 Specifically, @option{-fdec-math} enables the @ref{COTAN} intrinsic, and
2574 trigonometric intrinsics which accept or produce values in degrees instead of
2575 radians.  Here is a summary of the new intrinsics:
2577 @multitable @columnfractions .5 .5
2578 @headitem Radians @tab Degrees
2579 @item @code{@ref{ACOS}}   @tab @code{@ref{ACOSD}}*
2580 @item @code{@ref{ASIN}}   @tab @code{@ref{ASIND}}*
2581 @item @code{@ref{ATAN}}   @tab @code{@ref{ATAND}}*
2582 @item @code{@ref{ATAN2}}  @tab @code{@ref{ATAN2D}}*
2583 @item @code{@ref{COS}}    @tab @code{@ref{COSD}}*
2584 @item @code{@ref{COTAN}}* @tab @code{@ref{COTAND}}*
2585 @item @code{@ref{SIN}}    @tab @code{@ref{SIND}}*
2586 @item @code{@ref{TAN}}    @tab @code{@ref{TAND}}*
2587 @end multitable
2589 * Enabled with @option{-fdec-math}.
2591 For advanced users, it may be important to know the implementation of these
2592 functions. They are simply wrappers around the standard radian functions, which
2593 have more accurate builtin versions. These functions convert their arguments
2594 (or results) to degrees (or radians) by taking the value modulus 360 (or 2*pi)
2595 and then multiplying it by a constant radian-to-degree (or degree-to-radian)
2596 factor, as appropriate. The factor is computed at compile-time as 180/pi (or
2597 pi/180).
2599 @node Form feed as whitespace
2600 @subsection Form feed as whitespace
2601 @cindex form feed whitespace
2603 Historically, legacy compilers allowed insertion of form feed characters ('\f',
2604 ASCII 0xC) at the beginning of lines for formatted output to line printers,
2605 though the Fortran standard does not mention this. GNU Fortran supports the
2606 interpretation of form feed characters in source as whitespace for
2607 compatibility.
2609 @node TYPE as an alias for PRINT
2610 @subsection TYPE as an alias for PRINT
2611 @cindex type alias print
2612 For compatibility, GNU Fortran will interpret @code{TYPE} statements as
2613 @code{PRINT} statements with the flag @option{-fdec}.  With this flag asserted,
2614 the following two examples are equivalent:
2616 @smallexample
2617 TYPE *, 'hello world'
2618 @end smallexample
2620 @smallexample
2621 PRINT *, 'hello world'
2622 @end smallexample
2624 @node %LOC as an rvalue
2625 @subsection %LOC as an rvalue
2626 @cindex LOC
2627 Normally @code{%LOC} is allowed only in parameter lists.  However the intrinsic
2628 function @code{LOC} does the same thing, and is usable as the right-hand-side of
2629 assignments. For compatibility, GNU Fortran supports the use of @code{%LOC} as
2630 an alias for the builtin @code{LOC} with @option{-std=legacy}.  With this
2631 feature enabled the following two examples are equivalent:
2633 @smallexample
2634 integer :: i, l
2635 l = %loc(i)
2636 call sub(l)
2637 @end smallexample
2639 @smallexample
2640 integer :: i
2641 call sub(%loc(i))
2642 @end smallexample
2644 @node .XOR. operator
2645 @subsection .XOR. operator
2646 @cindex operators, xor
2648 GNU Fortran supports @code{.XOR.} as a logical operator with @code{-std=legacy}
2649 for compatibility with legacy code. @code{.XOR.} is equivalent to
2650 @code{.NEQV.}. That is, the output is true if and only if the inputs differ.
2652 @node Bitwise logical operators
2653 @subsection Bitwise logical operators
2654 @cindex logical, bitwise
2656 With @option{-fdec}, GNU Fortran relaxes the type constraints on
2657 logical operators to allow integer operands, and performs the corresponding
2658 bitwise operation instead.  This flag is for compatibility only, and should be
2659 avoided in new code.  Consider:
2661 @smallexample
2662   INTEGER :: i, j
2663   i = z'33'
2664   j = z'cc'
2665   print *, i .AND. j
2666 @end smallexample
2668 In this example, compiled with @option{-fdec}, GNU Fortran will
2669 replace the @code{.AND.} operation with a call to the intrinsic
2670 @code{@ref{IAND}} function, yielding the bitwise-and of @code{i} and @code{j}.
2672 Note that this conversion will occur if at least one operand is of integral
2673 type.  As a result, a logical operand will be converted to an integer when the
2674 other operand is an integer in a logical operation.  In this case,
2675 @code{.TRUE.} is converted to @code{1} and @code{.FALSE.} to @code{0}.
2677 Here is the mapping of logical operator to bitwise intrinsic used with
2678 @option{-fdec}:
2680 @multitable @columnfractions .25 .25 .5
2681 @headitem Operator @tab Intrinsic @tab Bitwise operation
2682 @item @code{.NOT.} @tab @code{@ref{NOT}} @tab complement
2683 @item @code{.AND.} @tab @code{@ref{IAND}} @tab intersection
2684 @item @code{.OR.} @tab @code{@ref{IOR}} @tab union
2685 @item @code{.NEQV.} @tab @code{@ref{IEOR}} @tab exclusive or
2686 @item @code{.EQV.} @tab @code{@ref{NOT}(@ref{IEOR})} @tab complement of exclusive or
2687 @end multitable
2689 @node Extended I/O specifiers
2690 @subsection Extended I/O specifiers
2691 @cindex @code{CARRIAGECONTROL}
2692 @cindex @code{READONLY}
2693 @cindex @code{SHARE}
2694 @cindex @code{SHARED}
2695 @cindex @code{NOSHARED}
2696 @cindex I/O specifiers
2698 GNU Fortran supports the additional legacy I/O specifiers
2699 @code{CARRIAGECONTROL}, @code{READONLY}, and @code{SHARE} with the
2700 compile flag @option{-fdec}, for compatibility.
2702 @table @code
2703 @item CARRIAGECONTROL
2704 The @code{CARRIAGECONTROL} specifier allows a user to control line
2705 termination settings between output records for an I/O unit. The specifier has
2706 no meaning for readonly files. When @code{CARRAIGECONTROL} is specified upon
2707 opening a unit for formatted writing, the exact @code{CARRIAGECONTROL} setting
2708 determines what characters to write between output records. The syntax is:
2710 @smallexample
2711 OPEN(..., CARRIAGECONTROL=cc)
2712 @end smallexample
2714 Where @emph{cc} is a character expression that evaluates to one of the
2715 following values:
2717 @multitable @columnfractions .2 .8
2718 @item @code{'LIST'} @tab One line feed between records (default)
2719 @item @code{'FORTRAN'} @tab Legacy interpretation of the first character (see below)
2720 @item @code{'NONE'} @tab No separator between records
2721 @end multitable
2723 With @code{CARRIAGECONTROL='FORTRAN'}, when a record is written, the first
2724 character of the input record is not written, and instead determines the output
2725 record separator as follows:
2727 @multitable @columnfractions .3 .3 .4
2728 @headitem Leading character @tab Meaning @tab Output separating character(s)
2729 @item @code{'+'} @tab Overprinting @tab Carriage return only
2730 @item @code{'-'} @tab New line @tab Line feed and carriage return
2731 @item @code{'0'} @tab Skip line @tab Two line feeds and carriage return
2732 @item @code{'1'} @tab New page @tab Form feed and carriage return
2733 @item @code{'$'} @tab Prompting @tab Line feed (no carriage return)
2734 @item @code{CHAR(0)} @tab Overprinting (no advance) @tab None
2735 @end multitable
2737 @item READONLY
2738 The @code{READONLY} specifier may be given upon opening a unit, and is
2739 equivalent to specifying @code{ACTION='READ'}, except that the file may not be
2740 deleted on close (i.e. @code{CLOSE} with @code{STATUS="DELETE"}). The syntax
2743 @smallexample
2744 @code{OPEN(..., READONLY)}
2745 @end smallexample
2747 @item SHARE
2748 The @code{SHARE} specifier allows system-level locking on a unit upon opening
2749 it for controlled access from multiple processes/threads. The @code{SHARE}
2750 specifier has several forms:
2752 @smallexample
2753 OPEN(..., SHARE=sh)
2754 OPEN(..., SHARED)
2755 OPEN(..., NOSHARED)
2756 @end smallexample
2758 Where @emph{sh} in the first form is a character expression that evaluates to
2759 a value as seen in the table below. The latter two forms are aliases
2760 for particular values of @emph{sh}:
2762 @multitable @columnfractions .3 .3 .4
2763 @headitem Explicit form @tab Short form @tab Meaning
2764 @item @code{SHARE='DENYRW'} @tab @code{NOSHARED} @tab Exclusive (write) lock
2765 @item @code{SHARE='DENYNONE'} @tab @code{SHARED} @tab Shared (read) lock
2766 @end multitable
2768 In general only one process may hold an exclusive (write) lock for a given file
2769 at a time, whereas many processes may hold shared (read) locks for the same
2770 file.
2772 The behavior of locking may vary with your operating system. On POSIX systems,
2773 locking is implemented with @code{fcntl}. Consult your corresponding operating
2774 system's manual pages for further details. Locking via @code{SHARE=} is not
2775 supported on other systems.
2777 @end table
2779 @node Legacy PARAMETER statements
2780 @subsection Legacy PARAMETER statements
2781 @cindex PARAMETER
2783 For compatibility, GNU Fortran supports legacy PARAMETER statements without
2784 parentheses with @option{-std=legacy}.  A warning is emitted if used with
2785 @option{-std=gnu}, and an error is acknowledged with a real Fortran standard
2786 flag (@option{-std=f95}, etc...).  These statements take the following form:
2788 @smallexample
2789 implicit real (E)
2790 parameter e = 2.718282
2791 real c
2792 parameter c = 3.0e8
2793 @end smallexample
2795 @node Default exponents
2796 @subsection Default exponents
2797 @cindex exponent
2799 For compatibility, GNU Fortran supports a default exponent of zero in real
2800 constants with @option{-fdec}.  For example, @code{9e} would be
2801 interpreted as @code{9e0}, rather than an error.
2804 @node Extensions not implemented in GNU Fortran
2805 @section Extensions not implemented in GNU Fortran
2806 @cindex extensions, not implemented
2808 The long history of the Fortran language, its wide use and broad
2809 userbase, the large number of different compiler vendors and the lack of
2810 some features crucial to users in the first standards have lead to the
2811 existence of a number of important extensions to the language.  While
2812 some of the most useful or popular extensions are supported by the GNU
2813 Fortran compiler, not all existing extensions are supported.  This section
2814 aims at listing these extensions and offering advice on how best make
2815 code that uses them running with the GNU Fortran compiler.
2817 @c More can be found here:
2818 @c   -- https://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/Missing-Features.html
2819 @c   -- the list of Fortran and libgfortran bugs closed as WONTFIX:
2820 @c      http://tinyurl.com/2u4h5y
2822 @menu
2823 * ENCODE and DECODE statements::
2824 * Variable FORMAT expressions::
2825 @c * Q edit descriptor::
2826 @c * TYPE and ACCEPT I/O Statements::
2827 @c * DEFAULTFILE, DISPOSE and RECORDTYPE I/O specifiers::
2828 @c * Omitted arguments in procedure call::
2829 * Alternate complex function syntax::
2830 * Volatile COMMON blocks::
2831 * OPEN( ... NAME=)::
2832 @end menu
2834 @node ENCODE and DECODE statements
2835 @subsection @code{ENCODE} and @code{DECODE} statements
2836 @cindex @code{ENCODE}
2837 @cindex @code{DECODE}
2839 GNU Fortran does not support the @code{ENCODE} and @code{DECODE}
2840 statements.  These statements are best replaced by @code{READ} and
2841 @code{WRITE} statements involving internal files (@code{CHARACTER}
2842 variables and arrays), which have been part of the Fortran standard since
2843 Fortran 77.  For example, replace a code fragment like
2845 @smallexample
2846       INTEGER*1 LINE(80)
2847       REAL A, B, C
2848 c     ... Code that sets LINE
2849       DECODE (80, 9000, LINE) A, B, C
2850  9000 FORMAT (1X, 3(F10.5))
2851 @end smallexample
2853 @noindent
2854 with the following:
2856 @smallexample
2857       CHARACTER(LEN=80) LINE
2858       REAL A, B, C
2859 c     ... Code that sets LINE
2860       READ (UNIT=LINE, FMT=9000) A, B, C
2861  9000 FORMAT (1X, 3(F10.5))
2862 @end smallexample
2864 Similarly, replace a code fragment like
2866 @smallexample
2867       INTEGER*1 LINE(80)
2868       REAL A, B, C
2869 c     ... Code that sets A, B and C
2870       ENCODE (80, 9000, LINE) A, B, C
2871  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2872 @end smallexample
2874 @noindent
2875 with the following:
2877 @smallexample
2878       CHARACTER(LEN=80) LINE
2879       REAL A, B, C
2880 c     ... Code that sets A, B and C
2881       WRITE (UNIT=LINE, FMT=9000) A, B, C
2882  9000 FORMAT (1X, 'OUTPUT IS ', 3(F10.5))
2883 @end smallexample
2886 @node Variable FORMAT expressions
2887 @subsection Variable @code{FORMAT} expressions
2888 @cindex @code{FORMAT}
2890 A variable @code{FORMAT} expression is format statement which includes
2891 angle brackets enclosing a Fortran expression: @code{FORMAT(I<N>)}.  GNU
2892 Fortran does not support this legacy extension.  The effect of variable
2893 format expressions can be reproduced by using the more powerful (and
2894 standard) combination of internal output and string formats.  For example,
2895 replace a code fragment like this:
2897 @smallexample
2898       WRITE(6,20) INT1
2899  20   FORMAT(I<N+1>)
2900 @end smallexample
2902 @noindent
2903 with the following:
2905 @smallexample
2906 c     Variable declaration
2907       CHARACTER(LEN=20) FMT
2908 c     
2909 c     Other code here...
2911       WRITE(FMT,'("(I", I0, ")")') N+1
2912       WRITE(6,FMT) INT1
2913 @end smallexample
2915 @noindent
2916 or with:
2918 @smallexample
2919 c     Variable declaration
2920       CHARACTER(LEN=20) FMT
2921 c     
2922 c     Other code here...
2924       WRITE(FMT,*) N+1
2925       WRITE(6,"(I" // ADJUSTL(FMT) // ")") INT1
2926 @end smallexample
2929 @node Alternate complex function syntax
2930 @subsection Alternate complex function syntax
2931 @cindex Complex function
2933 Some Fortran compilers, including @command{g77}, let the user declare
2934 complex functions with the syntax @code{COMPLEX FUNCTION name*16()}, as
2935 well as @code{COMPLEX*16 FUNCTION name()}.  Both are non-standard, legacy
2936 extensions.  @command{gfortran} accepts the latter form, which is more
2937 common, but not the former.
2940 @node Volatile COMMON blocks
2941 @subsection Volatile @code{COMMON} blocks
2942 @cindex @code{VOLATILE}
2943 @cindex @code{COMMON}
2945 Some Fortran compilers, including @command{g77}, let the user declare
2946 @code{COMMON} with the @code{VOLATILE} attribute. This is
2947 invalid standard Fortran syntax and is not supported by
2948 @command{gfortran}.  Note that @command{gfortran} accepts
2949 @code{VOLATILE} variables in @code{COMMON} blocks since revision 4.3.
2952 @node OPEN( ... NAME=)
2953 @subsection @code{OPEN( ... NAME=)}
2954 @cindex @code{NAM}
2956 Some Fortran compilers, including @command{g77}, let the user declare
2957 @code{OPEN( ... NAME=)}. This is
2958 invalid standard Fortran syntax and is not supported by
2959 @command{gfortran}.  @code{OPEN( ... NAME=)} should be replaced
2960 with @code{OPEN( ... FILE=)}.
2964 @c ---------------------------------------------------------------------
2965 @c ---------------------------------------------------------------------
2966 @c Mixed-Language Programming
2967 @c ---------------------------------------------------------------------
2969 @node Mixed-Language Programming
2970 @chapter Mixed-Language Programming
2971 @cindex Interoperability
2972 @cindex Mixed-language programming
2974 @menu
2975 * Interoperability with C::
2976 * GNU Fortran Compiler Directives::
2977 * Non-Fortran Main Program::
2978 * Naming and argument-passing conventions::
2979 @end menu
2981 This chapter is about mixed-language interoperability, but also applies
2982 if one links Fortran code compiled by different compilers.  In most cases,
2983 use of the C Binding features of the Fortran 2003 standard is sufficient,
2984 and their use is highly recommended.
2987 @node Interoperability with C
2988 @section Interoperability with C
2990 @menu
2991 * Intrinsic Types::
2992 * Derived Types and struct::
2993 * Interoperable Global Variables::
2994 * Interoperable Subroutines and Functions::
2995 * Working with Pointers::
2996 * Further Interoperability of Fortran with C::
2997 @end menu
2999 Since Fortran 2003 (ISO/IEC 1539-1:2004(E)) there is a
3000 standardized way to generate procedure and derived-type
3001 declarations and global variables which are interoperable with C
3002 (ISO/IEC 9899:1999).  The @code{bind(C)} attribute has been added
3003 to inform the compiler that a symbol shall be interoperable with C;
3004 also, some constraints are added.  Note, however, that not
3005 all C features have a Fortran equivalent or vice versa.  For instance,
3006 neither C's unsigned integers nor C's functions with variable number
3007 of arguments have an equivalent in Fortran.
3009 Note that array dimensions are reversely ordered in C and that arrays in
3010 C always start with index 0 while in Fortran they start by default with
3011 1.  Thus, an array declaration @code{A(n,m)} in Fortran matches
3012 @code{A[m][n]} in C and accessing the element @code{A(i,j)} matches
3013 @code{A[j-1][i-1]}.  The element following @code{A(i,j)} (C: @code{A[j-1][i-1]};
3014 assuming @math{i < n}) in memory is @code{A(i+1,j)} (C: @code{A[j-1][i]}).
3016 @node Intrinsic Types
3017 @subsection Intrinsic Types
3019 In order to ensure that exactly the same variable type and kind is used
3020 in C and Fortran, the named constants shall be used which are defined in the
3021 @code{ISO_C_BINDING} intrinsic module.  That module contains named constants
3022 for kind parameters and character named constants for the escape sequences
3023 in C.  For a list of the constants, see @ref{ISO_C_BINDING}.
3025 For logical types, please note that the Fortran standard only guarantees
3026 interoperability between C99's @code{_Bool} and Fortran's @code{C_Bool}-kind
3027 logicals and C99 defines that @code{true} has the value 1 and @code{false}
3028 the value 0.  Using any other integer value with GNU Fortran's @code{LOGICAL}
3029 (with any kind parameter) gives an undefined result.  (Passing other integer
3030 values than 0 and 1 to GCC's @code{_Bool} is also undefined, unless the
3031 integer is explicitly or implicitly casted to @code{_Bool}.)
3035 @node Derived Types and struct
3036 @subsection Derived Types and struct
3038 For compatibility of derived types with @code{struct}, one needs to use
3039 the @code{BIND(C)} attribute in the type declaration.  For instance, the
3040 following type declaration
3042 @smallexample
3043  USE ISO_C_BINDING
3044  TYPE, BIND(C) :: myType
3045    INTEGER(C_INT) :: i1, i2
3046    INTEGER(C_SIGNED_CHAR) :: i3
3047    REAL(C_DOUBLE) :: d1
3048    COMPLEX(C_FLOAT_COMPLEX) :: c1
3049    CHARACTER(KIND=C_CHAR) :: str(5)
3050  END TYPE
3051 @end smallexample
3053 matches the following @code{struct} declaration in C
3055 @smallexample
3056  struct @{
3057    int i1, i2;
3058    /* Note: "char" might be signed or unsigned.  */
3059    signed char i3;
3060    double d1;
3061    float _Complex c1;
3062    char str[5];
3063  @} myType;
3064 @end smallexample
3066 Derived types with the C binding attribute shall not have the @code{sequence}
3067 attribute, type parameters, the @code{extends} attribute, nor type-bound
3068 procedures.  Every component must be of interoperable type and kind and may not
3069 have the @code{pointer} or @code{allocatable} attribute.  The names of the
3070 components are irrelevant for interoperability.
3072 As there exist no direct Fortran equivalents, neither unions nor structs
3073 with bit field or variable-length array members are interoperable.
3075 @node Interoperable Global Variables
3076 @subsection Interoperable Global Variables
3078 Variables can be made accessible from C using the C binding attribute,
3079 optionally together with specifying a binding name.  Those variables
3080 have to be declared in the declaration part of a @code{MODULE},
3081 be of interoperable type, and have neither the @code{pointer} nor
3082 the @code{allocatable} attribute.
3084 @smallexample
3085   MODULE m
3086     USE myType_module
3087     USE ISO_C_BINDING
3088     integer(C_INT), bind(C, name="_MyProject_flags") :: global_flag
3089     type(myType), bind(C) :: tp
3090   END MODULE
3091 @end smallexample
3093 Here, @code{_MyProject_flags} is the case-sensitive name of the variable
3094 as seen from C programs while @code{global_flag} is the case-insensitive
3095 name as seen from Fortran.  If no binding name is specified, as for
3096 @var{tp}, the C binding name is the (lowercase) Fortran binding name.
3097 If a binding name is specified, only a single variable may be after the
3098 double colon.  Note of warning: You cannot use a global variable to
3099 access @var{errno} of the C library as the C standard allows it to be
3100 a macro.  Use the @code{IERRNO} intrinsic (GNU extension) instead.
3102 @node Interoperable Subroutines and Functions
3103 @subsection Interoperable Subroutines and Functions
3105 Subroutines and functions have to have the @code{BIND(C)} attribute to
3106 be compatible with C.  The dummy argument declaration is relatively
3107 straightforward.  However, one needs to be careful because C uses
3108 call-by-value by default while Fortran behaves usually similar to
3109 call-by-reference.  Furthermore, strings and pointers are handled
3110 differently.  Note that in Fortran 2003 and 2008 only explicit size
3111 and assumed-size arrays are supported but not assumed-shape or
3112 deferred-shape (i.e. allocatable or pointer) arrays.  However, those
3113 are allowed since the Technical Specification 29113, see
3114 @ref{Further Interoperability of Fortran with C}
3116 To pass a variable by value, use the @code{VALUE} attribute.
3117 Thus, the following C prototype
3119 @smallexample
3120 @code{int func(int i, int *j)}
3121 @end smallexample
3123 matches the Fortran declaration
3125 @smallexample
3126   integer(c_int) function func(i,j)
3127     use iso_c_binding, only: c_int
3128     integer(c_int), VALUE :: i
3129     integer(c_int) :: j
3130 @end smallexample
3132 Note that pointer arguments also frequently need the @code{VALUE} attribute,
3133 see @ref{Working with Pointers}.
3135 Strings are handled quite differently in C and Fortran.  In C a string
3136 is a @code{NUL}-terminated array of characters while in Fortran each string
3137 has a length associated with it and is thus not terminated (by e.g.
3138 @code{NUL}).  For example, if one wants to use the following C function,
3140 @smallexample
3141   #include <stdio.h>
3142   void print_C(char *string) /* equivalent: char string[]  */
3143   @{
3144      printf("%s\n", string);
3145   @}
3146 @end smallexample
3148 to print ``Hello World'' from Fortran, one can call it using
3150 @smallexample
3151   use iso_c_binding, only: C_CHAR, C_NULL_CHAR
3152   interface
3153     subroutine print_c(string) bind(C, name="print_C")
3154       use iso_c_binding, only: c_char
3155       character(kind=c_char) :: string(*)
3156     end subroutine print_c
3157   end interface
3158   call print_c(C_CHAR_"Hello World"//C_NULL_CHAR)
3159 @end smallexample
3161 As the example shows, one needs to ensure that the
3162 string is @code{NUL} terminated.  Additionally, the dummy argument
3163 @var{string} of @code{print_C} is a length-one assumed-size
3164 array; using @code{character(len=*)} is not allowed.  The example
3165 above uses @code{c_char_"Hello World"} to ensure the string
3166 literal has the right type; typically the default character
3167 kind and @code{c_char} are the same and thus @code{"Hello World"}
3168 is equivalent.  However, the standard does not guarantee this.
3170 The use of strings is now further illustrated using the C library
3171 function @code{strncpy}, whose prototype is
3173 @smallexample
3174   char *strncpy(char *restrict s1, const char *restrict s2, size_t n);
3175 @end smallexample
3177 The function @code{strncpy} copies at most @var{n} characters from
3178 string @var{s2} to @var{s1} and returns @var{s1}.  In the following
3179 example, we ignore the return value:
3181 @smallexample
3182   use iso_c_binding
3183   implicit none
3184   character(len=30) :: str,str2
3185   interface
3186     ! Ignore the return value of strncpy -> subroutine
3187     ! "restrict" is always assumed if we do not pass a pointer
3188     subroutine strncpy(dest, src, n) bind(C)
3189       import
3190       character(kind=c_char),  intent(out) :: dest(*)
3191       character(kind=c_char),  intent(in)  :: src(*)
3192       integer(c_size_t), value, intent(in) :: n
3193     end subroutine strncpy
3194   end interface
3195   str = repeat('X',30) ! Initialize whole string with 'X'
3196   call strncpy(str, c_char_"Hello World"//C_NULL_CHAR, &
3197                len(c_char_"Hello World",kind=c_size_t))
3198   print '(a)', str ! prints: "Hello WorldXXXXXXXXXXXXXXXXXXX"
3199   end
3200 @end smallexample
3202 The intrinsic procedures are described in @ref{Intrinsic Procedures}.
3204 @node Working with Pointers
3205 @subsection Working with Pointers
3207 C pointers are represented in Fortran via the special opaque derived type
3208 @code{type(c_ptr)} (with private components).  Thus one needs to
3209 use intrinsic conversion procedures to convert from or to C pointers.
3211 For some applications, using an assumed type (@code{TYPE(*)}) can be an
3212 alternative to a C pointer; see
3213 @ref{Further Interoperability of Fortran with C}.
3215 For example,
3217 @smallexample
3218   use iso_c_binding
3219   type(c_ptr) :: cptr1, cptr2
3220   integer, target :: array(7), scalar
3221   integer, pointer :: pa(:), ps
3222   cptr1 = c_loc(array(1)) ! The programmer needs to ensure that the
3223                           ! array is contiguous if required by the C
3224                           ! procedure
3225   cptr2 = c_loc(scalar)
3226   call c_f_pointer(cptr2, ps)
3227   call c_f_pointer(cptr2, pa, shape=[7])
3228 @end smallexample
3230 When converting C to Fortran arrays, the one-dimensional @code{SHAPE} argument
3231 has to be passed.
3233 If a pointer is a dummy-argument of an interoperable procedure, it usually
3234 has to be declared using the @code{VALUE} attribute.  @code{void*}
3235 matches @code{TYPE(C_PTR), VALUE}, while @code{TYPE(C_PTR)} alone
3236 matches @code{void**}.
3238 Procedure pointers are handled analogously to pointers; the C type is
3239 @code{TYPE(C_FUNPTR)} and the intrinsic conversion procedures are
3240 @code{C_F_PROCPOINTER} and @code{C_FUNLOC}.
3242 Let us consider two examples of actually passing a procedure pointer from
3243 C to Fortran and vice versa.  Note that these examples are also very
3244 similar to passing ordinary pointers between both languages. First,
3245 consider this code in C:
3247 @smallexample
3248 /* Procedure implemented in Fortran.  */
3249 void get_values (void (*)(double));
3251 /* Call-back routine we want called from Fortran.  */
3252 void
3253 print_it (double x)
3255   printf ("Number is %f.\n", x);
3258 /* Call Fortran routine and pass call-back to it.  */
3259 void
3260 foobar ()
3262   get_values (&print_it);
3264 @end smallexample
3266 A matching implementation for @code{get_values} in Fortran, that correctly
3267 receives the procedure pointer from C and is able to call it, is given
3268 in the following @code{MODULE}:
3270 @smallexample
3271 MODULE m
3272   IMPLICIT NONE
3274   ! Define interface of call-back routine.
3275   ABSTRACT INTERFACE
3276     SUBROUTINE callback (x)
3277       USE, INTRINSIC :: ISO_C_BINDING
3278       REAL(KIND=C_DOUBLE), INTENT(IN), VALUE :: x
3279     END SUBROUTINE callback
3280   END INTERFACE
3282 CONTAINS
3284   ! Define C-bound procedure.
3285   SUBROUTINE get_values (cproc) BIND(C)
3286     USE, INTRINSIC :: ISO_C_BINDING
3287     TYPE(C_FUNPTR), INTENT(IN), VALUE :: cproc
3289     PROCEDURE(callback), POINTER :: proc
3291     ! Convert C to Fortran procedure pointer.
3292     CALL C_F_PROCPOINTER (cproc, proc)
3294     ! Call it.
3295     CALL proc (1.0_C_DOUBLE)
3296     CALL proc (-42.0_C_DOUBLE)
3297     CALL proc (18.12_C_DOUBLE)
3298   END SUBROUTINE get_values
3300 END MODULE m
3301 @end smallexample
3303 Next, we want to call a C routine that expects a procedure pointer argument
3304 and pass it a Fortran procedure (which clearly must be interoperable!).
3305 Again, the C function may be:
3307 @smallexample
3309 call_it (int (*func)(int), int arg)
3311   return func (arg);
3313 @end smallexample
3315 It can be used as in the following Fortran code:
3317 @smallexample
3318 MODULE m
3319   USE, INTRINSIC :: ISO_C_BINDING
3320   IMPLICIT NONE
3322   ! Define interface of C function.
3323   INTERFACE
3324     INTEGER(KIND=C_INT) FUNCTION call_it (func, arg) BIND(C)
3325       USE, INTRINSIC :: ISO_C_BINDING
3326       TYPE(C_FUNPTR), INTENT(IN), VALUE :: func
3327       INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
3328     END FUNCTION call_it
3329   END INTERFACE
3331 CONTAINS
3333   ! Define procedure passed to C function.
3334   ! It must be interoperable!
3335   INTEGER(KIND=C_INT) FUNCTION double_it (arg) BIND(C)
3336     INTEGER(KIND=C_INT), INTENT(IN), VALUE :: arg
3337     double_it = arg + arg
3338   END FUNCTION double_it
3340   ! Call C function.
3341   SUBROUTINE foobar ()
3342     TYPE(C_FUNPTR) :: cproc
3343     INTEGER(KIND=C_INT) :: i
3345     ! Get C procedure pointer.
3346     cproc = C_FUNLOC (double_it)
3348     ! Use it.
3349     DO i = 1_C_INT, 10_C_INT
3350       PRINT *, call_it (cproc, i)
3351     END DO
3352   END SUBROUTINE foobar
3354 END MODULE m
3355 @end smallexample
3357 @node Further Interoperability of Fortran with C
3358 @subsection Further Interoperability of Fortran with C
3360 The Technical Specification ISO/IEC TS 29113:2012 on further
3361 interoperability of Fortran with C extends the interoperability support
3362 of Fortran 2003 and Fortran 2008. Besides removing some restrictions
3363 and constraints, it adds assumed-type (@code{TYPE(*)}) and assumed-rank
3364 (@code{dimension}) variables and allows for interoperability of
3365 assumed-shape, assumed-rank and deferred-shape arrays, including
3366 allocatables and pointers.
3368 Note: Currently, GNU Fortran does not support the array descriptor
3369 (dope vector) as specified in the Technical Specification, but uses
3370 an array descriptor with different fields. The Chasm Language
3371 Interoperability Tools, @url{http://chasm-interop.sourceforge.net/},
3372 provide an interface to GNU Fortran's array descriptor.
3374 The Technical Specification adds the following new features, which
3375 are supported by GNU Fortran:
3377 @itemize @bullet
3379 @item The @code{ASYNCHRONOUS} attribute has been clarified and
3380 extended to allow its use with asynchronous communication in
3381 user-provided libraries such as in implementations of the
3382 Message Passing Interface specification.
3384 @item Many constraints have been relaxed, in particular for
3385 the @code{C_LOC} and @code{C_F_POINTER} intrinsics.
3387 @item The @code{OPTIONAL} attribute is now allowed for dummy
3388 arguments; an absent argument matches a @code{NULL} pointer.
3390 @item Assumed types (@code{TYPE(*)}) have been added, which may
3391 only be used for dummy arguments.  They are unlimited polymorphic
3392 but contrary to @code{CLASS(*)} they do not contain any type
3393 information, similar to C's @code{void *} pointers.  Expressions
3394 of any type and kind can be passed; thus, it can be used as
3395 replacement for @code{TYPE(C_PTR)}, avoiding the use of
3396 @code{C_LOC} in the caller.
3398 Note, however, that @code{TYPE(*)} only accepts scalar arguments,
3399 unless the @code{DIMENSION} is explicitly specified.  As
3400 @code{DIMENSION(*)} only supports array (including array elements) but
3401 no scalars, it is not a full replacement for @code{C_LOC}.  On the
3402 other hand, assumed-type assumed-rank dummy arguments
3403 (@code{TYPE(*), DIMENSION(..)}) allow for both scalars and arrays, but
3404 require special code on the callee side to handle the array descriptor.
3406 @item Assumed-rank arrays (@code{DIMENSION(..)}) as dummy argument
3407 allow that scalars and arrays of any rank can be passed as actual
3408 argument. As the Technical Specification does not provide for direct
3409 means to operate with them, they have to be used either from the C side
3410 or be converted using @code{C_LOC} and @code{C_F_POINTER} to scalars
3411 or arrays of a specific rank. The rank can be determined using the
3412 @code{RANK} intrinisic.
3413 @end itemize
3416 Currently unimplemented:
3418 @itemize @bullet
3420 @item GNU Fortran always uses an array descriptor, which does not
3421 match the one of the Technical Specification. The
3422 @code{ISO_Fortran_binding.h} header file and the C functions it
3423 specifies are not available.
3425 @item Using assumed-shape, assumed-rank and deferred-shape arrays in
3426 @code{BIND(C)} procedures is not fully supported. In particular,
3427 C interoperable strings of other length than one are not supported
3428 as this requires the new array descriptor.
3429 @end itemize
3432 @node GNU Fortran Compiler Directives
3433 @section GNU Fortran Compiler Directives
3435 The Fortran standard describes how a conforming program shall
3436 behave; however, the exact implementation is not standardized.  In order
3437 to allow the user to choose specific implementation details, compiler
3438 directives can be used to set attributes of variables and procedures
3439 which are not part of the standard.  Whether a given attribute is
3440 supported and its exact effects depend on both the operating system and
3441 on the processor; see
3442 @ref{Top,,C Extensions,gcc,Using the GNU Compiler Collection (GCC)}
3443 for details.
3445 For procedures and procedure pointers, the following attributes can
3446 be used to change the calling convention:
3448 @itemize
3449 @item @code{CDECL} -- standard C calling convention
3450 @item @code{STDCALL} -- convention where the called procedure pops the stack
3451 @item @code{FASTCALL} -- part of the arguments are passed via registers
3452 instead using the stack
3453 @end itemize
3455 Besides changing the calling convention, the attributes also influence
3456 the decoration of the symbol name, e.g., by a leading underscore or by
3457 a trailing at-sign followed by the number of bytes on the stack.  When
3458 assigning a procedure to a procedure pointer, both should use the same
3459 calling convention.
3461 On some systems, procedures and global variables (module variables and
3462 @code{COMMON} blocks) need special handling to be accessible when they
3463 are in a shared library.  The following attributes are available:
3465 @itemize
3466 @item @code{DLLEXPORT} -- provide a global pointer to a pointer in the DLL
3467 @item @code{DLLIMPORT} -- reference the function or variable using a
3468 global pointer
3469 @end itemize
3471 For dummy arguments, the @code{NO_ARG_CHECK} attribute can be used; in
3472 other compilers, it is also known as @code{IGNORE_TKR}.  For dummy arguments
3473 with this attribute actual arguments of any type and kind (similar to
3474 @code{TYPE(*)}), scalars and arrays of any rank (no equivalent
3475 in Fortran standard) are accepted.  As with @code{TYPE(*)}, the argument
3476 is unlimited polymorphic and no type information is available.
3477 Additionally, the argument may only be passed to dummy arguments
3478 with the @code{NO_ARG_CHECK} attribute and as argument to the
3479 @code{PRESENT} intrinsic function and to @code{C_LOC} of the
3480 @code{ISO_C_BINDING} module.
3482 Variables with @code{NO_ARG_CHECK} attribute shall be of assumed-type
3483 (@code{TYPE(*)}; recommended) or of type @code{INTEGER}, @code{LOGICAL},
3484 @code{REAL} or @code{COMPLEX}. They shall not have the @code{ALLOCATE},
3485 @code{CODIMENSION}, @code{INTENT(OUT)}, @code{POINTER} or @code{VALUE}
3486 attribute; furthermore, they shall be either scalar or of assumed-size
3487 (@code{dimension(*)}). As @code{TYPE(*)}, the @code{NO_ARG_CHECK} attribute
3488 requires an explicit interface.
3490 @itemize
3491 @item @code{NO_ARG_CHECK} -- disable the type, kind and rank checking
3492 @end itemize
3495 The attributes are specified using the syntax
3497 @code{!GCC$ ATTRIBUTES} @var{attribute-list} @code{::} @var{variable-list}
3499 where in free-form source code only whitespace is allowed before @code{!GCC$}
3500 and in fixed-form source code @code{!GCC$}, @code{cGCC$} or @code{*GCC$} shall
3501 start in the first column.
3503 For procedures, the compiler directives shall be placed into the body
3504 of the procedure; for variables and procedure pointers, they shall be in
3505 the same declaration part as the variable or procedure pointer.
3509 @node Non-Fortran Main Program
3510 @section Non-Fortran Main Program
3512 @menu
3513 * _gfortran_set_args:: Save command-line arguments
3514 * _gfortran_set_options:: Set library option flags
3515 * _gfortran_set_convert:: Set endian conversion
3516 * _gfortran_set_record_marker:: Set length of record markers
3517 * _gfortran_set_fpe:: Set when a Floating Point Exception should be raised
3518 * _gfortran_set_max_subrecord_length:: Set subrecord length
3519 @end menu
3521 Even if you are doing mixed-language programming, it is very
3522 likely that you do not need to know or use the information in this
3523 section.  Since it is about the internal structure of GNU Fortran,
3524 it may also change in GCC minor releases.
3526 When you compile a @code{PROGRAM} with GNU Fortran, a function
3527 with the name @code{main} (in the symbol table of the object file)
3528 is generated, which initializes the libgfortran library and then
3529 calls the actual program which uses the name @code{MAIN__}, for
3530 historic reasons.  If you link GNU Fortran compiled procedures
3531 to, e.g., a C or C++ program or to a Fortran program compiled by
3532 a different compiler, the libgfortran library is not initialized
3533 and thus a few intrinsic procedures do not work properly, e.g.
3534 those for obtaining the command-line arguments.
3536 Therefore, if your @code{PROGRAM} is not compiled with
3537 GNU Fortran and the GNU Fortran compiled procedures require
3538 intrinsics relying on the library initialization, you need to
3539 initialize the library yourself.  Using the default options,
3540 gfortran calls @code{_gfortran_set_args} and
3541 @code{_gfortran_set_options}.  The initialization of the former
3542 is needed if the called procedures access the command line
3543 (and for backtracing); the latter sets some flags based on the
3544 standard chosen or to enable backtracing.  In typical programs,
3545 it is not necessary to call any initialization function.
3547 If your @code{PROGRAM} is compiled with GNU Fortran, you shall
3548 not call any of the following functions.  The libgfortran
3549 initialization functions are shown in C syntax but using C
3550 bindings they are also accessible from Fortran.
3553 @node _gfortran_set_args
3554 @subsection @code{_gfortran_set_args} --- Save command-line arguments
3555 @fnindex _gfortran_set_args
3556 @cindex libgfortran initialization, set_args
3558 @table @asis
3559 @item @emph{Description}:
3560 @code{_gfortran_set_args} saves the command-line arguments; this
3561 initialization is required if any of the command-line intrinsics
3562 is called.  Additionally, it shall be called if backtracing is
3563 enabled (see @code{_gfortran_set_options}).
3565 @item @emph{Syntax}:
3566 @code{void _gfortran_set_args (int argc, char *argv[])}
3568 @item @emph{Arguments}:
3569 @multitable @columnfractions .15 .70
3570 @item @var{argc} @tab number of command line argument strings
3571 @item @var{argv} @tab the command-line argument strings; argv[0]
3572 is the pathname of the executable itself.
3573 @end multitable
3575 @item @emph{Example}:
3576 @smallexample
3577 int main (int argc, char *argv[])
3579   /* Initialize libgfortran.  */
3580   _gfortran_set_args (argc, argv);
3581   return 0;
3583 @end smallexample
3584 @end table
3587 @node _gfortran_set_options
3588 @subsection @code{_gfortran_set_options} --- Set library option flags
3589 @fnindex _gfortran_set_options
3590 @cindex libgfortran initialization, set_options
3592 @table @asis
3593 @item @emph{Description}:
3594 @code{_gfortran_set_options} sets several flags related to the Fortran
3595 standard to be used, whether backtracing should be enabled
3596 and whether range checks should be performed.  The syntax allows for
3597 upward compatibility since the number of passed flags is specified; for
3598 non-passed flags, the default value is used.  See also
3599 @pxref{Code Gen Options}.  Please note that not all flags are actually
3600 used.
3602 @item @emph{Syntax}:
3603 @code{void _gfortran_set_options (int num, int options[])}
3605 @item @emph{Arguments}:
3606 @multitable @columnfractions .15 .70
3607 @item @var{num} @tab number of options passed
3608 @item @var{argv} @tab The list of flag values
3609 @end multitable
3611 @item @emph{option flag list}:
3612 @multitable @columnfractions .15 .70
3613 @item @var{option}[0] @tab Allowed standard; can give run-time errors
3614 if e.g. an input-output edit descriptor is invalid in a given standard.
3615 Possible values are (bitwise or-ed) @code{GFC_STD_F77} (1),
3616 @code{GFC_STD_F95_OBS} (2), @code{GFC_STD_F95_DEL} (4), @code{GFC_STD_F95}
3617 (8), @code{GFC_STD_F2003} (16), @code{GFC_STD_GNU} (32),
3618 @code{GFC_STD_LEGACY} (64), @code{GFC_STD_F2008} (128),
3619 @code{GFC_STD_F2008_OBS} (256) and GFC_STD_F2008_TS (512). Default:
3620 @code{GFC_STD_F95_OBS | GFC_STD_F95_DEL | GFC_STD_F95 | GFC_STD_F2003
3621 | GFC_STD_F2008 | GFC_STD_F2008_TS | GFC_STD_F2008_OBS | GFC_STD_F77
3622 | GFC_STD_GNU | GFC_STD_LEGACY}.
3623 @item @var{option}[1] @tab Standard-warning flag; prints a warning to
3624 standard error.  Default: @code{GFC_STD_F95_DEL | GFC_STD_LEGACY}.
3625 @item @var{option}[2] @tab If non zero, enable pedantic checking.
3626 Default: off.
3627 @item @var{option}[3] @tab Unused.
3628 @item @var{option}[4] @tab If non zero, enable backtracing on run-time
3629 errors.  Default: off. (Default in the compiler: on.)
3630 Note: Installs a signal handler and requires command-line
3631 initialization using @code{_gfortran_set_args}.
3632 @item @var{option}[5] @tab If non zero, supports signed zeros.
3633 Default: enabled.
3634 @item @var{option}[6] @tab Enables run-time checking.  Possible values
3635 are (bitwise or-ed): GFC_RTCHECK_BOUNDS (1), GFC_RTCHECK_ARRAY_TEMPS (2),
3636 GFC_RTCHECK_RECURSION (4), GFC_RTCHECK_DO (16), GFC_RTCHECK_POINTER (32).
3637 Default: disabled.
3638 @item @var{option}[7] @tab Unused.
3639 @item @var{option}[8] @tab Show a warning when invoking @code{STOP} and
3640 @code{ERROR STOP} if a floating-point exception occurred. Possible values
3641 are (bitwise or-ed) @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
3642 @code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
3643 @code{GFC_FPE_UNDERFLOW} (16), @code{GFC_FPE_INEXACT} (32). Default: None (0).
3644 (Default in the compiler: @code{GFC_FPE_INVALID | GFC_FPE_DENORMAL |
3645 GFC_FPE_ZERO | GFC_FPE_OVERFLOW | GFC_FPE_UNDERFLOW}.)
3646 @end multitable
3648 @item @emph{Example}:
3649 @smallexample
3650   /* Use gfortran 4.9 default options.  */
3651   static int options[] = @{68, 511, 0, 0, 1, 1, 0, 0, 31@};
3652   _gfortran_set_options (9, &options);
3653 @end smallexample
3654 @end table
3657 @node _gfortran_set_convert
3658 @subsection @code{_gfortran_set_convert} --- Set endian conversion
3659 @fnindex _gfortran_set_convert
3660 @cindex libgfortran initialization, set_convert
3662 @table @asis
3663 @item @emph{Description}:
3664 @code{_gfortran_set_convert} set the representation of data for
3665 unformatted files.
3667 @item @emph{Syntax}:
3668 @code{void _gfortran_set_convert (int conv)}
3670 @item @emph{Arguments}:
3671 @multitable @columnfractions .15 .70
3672 @item @var{conv} @tab Endian conversion, possible values:
3673 GFC_CONVERT_NATIVE (0, default), GFC_CONVERT_SWAP (1),
3674 GFC_CONVERT_BIG (2), GFC_CONVERT_LITTLE (3).
3675 @end multitable
3677 @item @emph{Example}:
3678 @smallexample
3679 int main (int argc, char *argv[])
3681   /* Initialize libgfortran.  */
3682   _gfortran_set_args (argc, argv);
3683   _gfortran_set_convert (1);
3684   return 0;
3686 @end smallexample
3687 @end table
3690 @node _gfortran_set_record_marker
3691 @subsection @code{_gfortran_set_record_marker} --- Set length of record markers
3692 @fnindex _gfortran_set_record_marker
3693 @cindex libgfortran initialization, set_record_marker
3695 @table @asis
3696 @item @emph{Description}:
3697 @code{_gfortran_set_record_marker} sets the length of record markers
3698 for unformatted files.
3700 @item @emph{Syntax}:
3701 @code{void _gfortran_set_record_marker (int val)}
3703 @item @emph{Arguments}:
3704 @multitable @columnfractions .15 .70
3705 @item @var{val} @tab Length of the record marker; valid values
3706 are 4 and 8.  Default is 4.
3707 @end multitable
3709 @item @emph{Example}:
3710 @smallexample
3711 int main (int argc, char *argv[])
3713   /* Initialize libgfortran.  */
3714   _gfortran_set_args (argc, argv);
3715   _gfortran_set_record_marker (8);
3716   return 0;
3718 @end smallexample
3719 @end table
3722 @node _gfortran_set_fpe
3723 @subsection @code{_gfortran_set_fpe} --- Enable floating point exception traps
3724 @fnindex _gfortran_set_fpe
3725 @cindex libgfortran initialization, set_fpe
3727 @table @asis
3728 @item @emph{Description}:
3729 @code{_gfortran_set_fpe} enables floating point exception traps for
3730 the specified exceptions.  On most systems, this will result in a
3731 SIGFPE signal being sent and the program being aborted.
3733 @item @emph{Syntax}:
3734 @code{void _gfortran_set_fpe (int val)}
3736 @item @emph{Arguments}:
3737 @multitable @columnfractions .15 .70
3738 @item @var{option}[0] @tab IEEE exceptions.  Possible values are
3739 (bitwise or-ed) zero (0, default) no trapping,
3740 @code{GFC_FPE_INVALID} (1), @code{GFC_FPE_DENORMAL} (2),
3741 @code{GFC_FPE_ZERO} (4), @code{GFC_FPE_OVERFLOW} (8),
3742 @code{GFC_FPE_UNDERFLOW} (16), and @code{GFC_FPE_INEXACT} (32).
3743 @end multitable
3745 @item @emph{Example}:
3746 @smallexample
3747 int main (int argc, char *argv[])
3749   /* Initialize libgfortran.  */
3750   _gfortran_set_args (argc, argv);
3751   /* FPE for invalid operations such as SQRT(-1.0).  */
3752   _gfortran_set_fpe (1);
3753   return 0;
3755 @end smallexample
3756 @end table
3759 @node _gfortran_set_max_subrecord_length
3760 @subsection @code{_gfortran_set_max_subrecord_length} --- Set subrecord length
3761 @fnindex _gfortran_set_max_subrecord_length
3762 @cindex libgfortran initialization, set_max_subrecord_length
3764 @table @asis
3765 @item @emph{Description}:
3766 @code{_gfortran_set_max_subrecord_length} set the maximum length
3767 for a subrecord.  This option only makes sense for testing and
3768 debugging of unformatted I/O.
3770 @item @emph{Syntax}:
3771 @code{void _gfortran_set_max_subrecord_length (int val)}
3773 @item @emph{Arguments}:
3774 @multitable @columnfractions .15 .70
3775 @item @var{val} @tab the maximum length for a subrecord;
3776 the maximum permitted value is 2147483639, which is also
3777 the default.
3778 @end multitable
3780 @item @emph{Example}:
3781 @smallexample
3782 int main (int argc, char *argv[])
3784   /* Initialize libgfortran.  */
3785   _gfortran_set_args (argc, argv);
3786   _gfortran_set_max_subrecord_length (8);
3787   return 0;
3789 @end smallexample
3790 @end table
3793 @node Naming and argument-passing conventions
3794 @section Naming and argument-passing conventions
3796 This section gives an overview about the naming convention of procedures
3797 and global variables and about the argument passing conventions used by
3798 GNU Fortran.  If a C binding has been specified, the naming convention
3799 and some of the argument-passing conventions change.  If possible,
3800 mixed-language and mixed-compiler projects should use the better defined
3801 C binding for interoperability.  See @pxref{Interoperability with C}.
3803 @menu
3804 * Naming conventions::
3805 * Argument passing conventions::
3806 @end menu
3809 @node Naming conventions
3810 @subsection Naming conventions
3812 According the Fortran standard, valid Fortran names consist of a letter
3813 between @code{A} to @code{Z}, @code{a} to @code{z}, digits @code{0},
3814 @code{1} to @code{9} and underscores (@code{_}) with the restriction
3815 that names may only start with a letter.  As vendor extension, the
3816 dollar sign (@code{$}) is additionally permitted with the option
3817 @option{-fdollar-ok}, but not as first character and only if the
3818 target system supports it.
3820 By default, the procedure name is the lower-cased Fortran name with an
3821 appended underscore (@code{_}); using @option{-fno-underscoring} no
3822 underscore is appended while @code{-fsecond-underscore} appends two
3823 underscores.  Depending on the target system and the calling convention,
3824 the procedure might be additionally dressed; for instance, on 32bit
3825 Windows with @code{stdcall}, an at-sign @code{@@} followed by an integer
3826 number is appended.  For the changing the calling convention, see
3827 @pxref{GNU Fortran Compiler Directives}.
3829 For common blocks, the same convention is used, i.e. by default an
3830 underscore is appended to the lower-cased Fortran name.  Blank commons
3831 have the name @code{__BLNK__}.
3833 For procedures and variables declared in the specification space of a
3834 module, the name is formed by @code{__}, followed by the lower-cased
3835 module name, @code{_MOD_}, and the lower-cased Fortran name.  Note that
3836 no underscore is appended.
3839 @node Argument passing conventions
3840 @subsection Argument passing conventions
3842 Subroutines do not return a value (matching C99's @code{void}) while
3843 functions either return a value as specified in the platform ABI or
3844 the result variable is passed as hidden argument to the function and
3845 no result is returned.  A hidden result variable is used when the
3846 result variable is an array or of type @code{CHARACTER}.
3848 Arguments are passed according to the platform ABI. In particular,
3849 complex arguments might not be compatible to a struct with two real
3850 components for the real and imaginary part. The argument passing
3851 matches the one of C99's @code{_Complex}.  Functions with scalar
3852 complex result variables return their value and do not use a
3853 by-reference argument.  Note that with the @option{-ff2c} option,
3854 the argument passing is modified and no longer completely matches
3855 the platform ABI.  Some other Fortran compilers use @code{f2c}
3856 semantic by default; this might cause problems with
3857 interoperablility.
3859 GNU Fortran passes most arguments by reference, i.e. by passing a
3860 pointer to the data.  Note that the compiler might use a temporary
3861 variable into which the actual argument has been copied, if required
3862 semantically (copy-in/copy-out).
3864 For arguments with @code{ALLOCATABLE} and @code{POINTER}
3865 attribute (including procedure pointers), a pointer to the pointer
3866 is passed such that the pointer address can be modified in the
3867 procedure.
3869 For dummy arguments with the @code{VALUE} attribute: Scalar arguments
3870 of the type @code{INTEGER}, @code{LOGICAL}, @code{REAL} and
3871 @code{COMPLEX} are passed by value according to the platform ABI.
3872 (As vendor extension and not recommended, using @code{%VAL()} in the
3873 call to a procedure has the same effect.) For @code{TYPE(C_PTR)} and
3874 procedure pointers, the pointer itself is passed such that it can be
3875 modified without affecting the caller.
3876 @c FIXME: Document how VALUE is handled for CHARACTER, TYPE,
3877 @c CLASS and arrays, i.e. whether the copy-in is done in the caller
3878 @c or in the callee.
3880 For Boolean (@code{LOGICAL}) arguments, please note that GCC expects
3881 only the integer value 0 and 1.  If a GNU Fortran @code{LOGICAL}
3882 variable contains another integer value, the result is undefined.
3883 As some other Fortran compilers use @math{-1} for @code{.TRUE.},
3884 extra care has to be taken -- such as passing the value as
3885 @code{INTEGER}.  (The same value restriction also applies to other
3886 front ends of GCC, e.g. to GCC's C99 compiler for @code{_Bool}
3887 or GCC's Ada compiler for @code{Boolean}.)
3889 For arguments of @code{CHARACTER} type, the character length is passed
3890 as hidden argument.  For deferred-length strings, the value is passed
3891 by reference, otherwise by value.  The character length has the type
3892 @code{INTEGER(kind=4)}.  Note with C binding, @code{CHARACTER(len=1)}
3893 result variables are returned according to the platform ABI and no
3894 hidden length argument is used for dummy arguments; with @code{VALUE},
3895 those variables are passed by value.
3897 For @code{OPTIONAL} dummy arguments, an absent argument is denoted
3898 by a NULL pointer, except for scalar dummy arguments of type
3899 @code{INTEGER}, @code{LOGICAL}, @code{REAL} and @code{COMPLEX}
3900 which have the @code{VALUE} attribute.  For those, a hidden Boolean
3901 argument (@code{logical(kind=C_bool),value}) is used to indicate
3902 whether the argument is present.
3904 Arguments which are assumed-shape, assumed-rank or deferred-rank
3905 arrays or, with @option{-fcoarray=lib}, allocatable scalar coarrays use
3906 an array descriptor.  All other arrays pass the address of the
3907 first element of the array.  With @option{-fcoarray=lib}, the token
3908 and the offset belonging to nonallocatable coarrays dummy arguments
3909 are passed as hidden argument along the character length hidden
3910 arguments.  The token is an oparque pointer identifying the coarray
3911 and the offset is a passed-by-value integer of kind @code{C_PTRDIFF_T},
3912 denoting the byte offset between the base address of the coarray and
3913 the passed scalar or first element of the passed array.
3915 The arguments are passed in the following order
3916 @itemize @bullet
3917 @item Result variable, when the function result is passed by reference
3918 @item Character length of the function result, if it is a of type
3919 @code{CHARACTER} and no C binding is used
3920 @item The arguments in the order in which they appear in the Fortran
3921 declaration
3922 @item The the present status for optional arguments with value attribute,
3923 which are internally passed by value
3924 @item The character length and/or coarray token and offset for the first
3925 argument which is a @code{CHARACTER} or a nonallocatable coarray dummy
3926 argument, followed by the hidden arguments of the next dummy argument
3927 of such a type
3928 @end itemize
3931 @c ---------------------------------------------------------------------
3932 @c Coarray Programming
3933 @c ---------------------------------------------------------------------
3935 @node Coarray Programming
3936 @chapter Coarray Programming
3937 @cindex Coarrays
3939 @menu
3940 * Type and enum ABI Documentation::
3941 * Function ABI Documentation::
3942 @end menu
3945 @node Type and enum ABI Documentation
3946 @section Type and enum ABI Documentation
3948 @menu
3949 * caf_token_t::
3950 * caf_register_t::
3951 * caf_deregister_t::
3952 * caf_reference_t::
3953 * caf_team_t::
3954 @end menu
3956 @node caf_token_t
3957 @subsection @code{caf_token_t}
3959 Typedef of type @code{void *} on the compiler side. Can be any data
3960 type on the library side.
3962 @node caf_register_t
3963 @subsection @code{caf_register_t}
3965 Indicates which kind of coarray variable should be registered.
3967 @verbatim
3968 typedef enum caf_register_t {
3969   CAF_REGTYPE_COARRAY_STATIC,
3970   CAF_REGTYPE_COARRAY_ALLOC,
3971   CAF_REGTYPE_LOCK_STATIC,
3972   CAF_REGTYPE_LOCK_ALLOC,
3973   CAF_REGTYPE_CRITICAL,
3974   CAF_REGTYPE_EVENT_STATIC,
3975   CAF_REGTYPE_EVENT_ALLOC,
3976   CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY,
3977   CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY
3979 caf_register_t;
3980 @end verbatim
3982 The values @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} and
3983 @code{CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY} are for allocatable components
3984 in derived type coarrays only.  The first one sets up the token without
3985 allocating memory for allocatable component.  The latter one only allocates the
3986 memory for an allocatable component in a derived type coarray.  The token
3987 needs to be setup previously by the REGISTER_ONLY.  This allows to have
3988 allocatable components un-allocated on some images.  The status whether an
3989 allocatable component is allocated on a remote image can be queried by
3990 @code{_caf_is_present} which used internally by the @code{ALLOCATED}
3991 intrinsic.
3993 @node caf_deregister_t
3994 @subsection @code{caf_deregister_t}
3996 @verbatim
3997 typedef enum caf_deregister_t {
3998   CAF_DEREGTYPE_COARRAY_DEREGISTER,
3999   CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY
4001 caf_deregister_t;
4002 @end verbatim
4004 Allows to specifiy the type of deregistration of a coarray object.  The
4005 @code{CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY} flag is only allowed for
4006 allocatable components in derived type coarrays.
4008 @node caf_reference_t
4009 @subsection @code{caf_reference_t}
4011 The structure used for implementing arbitrary reference chains.
4012 A @code{CAF_REFERENCE_T} allows to specify a component reference or any kind
4013 of array reference of any rank supported by gfortran.  For array references all
4014 kinds as known by the compiler/Fortran standard are supported indicated by
4015 a @code{MODE}.
4017 @verbatim
4018 typedef enum caf_ref_type_t {
4019   /* Reference a component of a derived type, either regular one or an
4020      allocatable or pointer type.  For regular ones idx in caf_reference_t is
4021      set to -1.  */
4022   CAF_REF_COMPONENT,
4023   /* Reference an allocatable array.  */
4024   CAF_REF_ARRAY,
4025   /* Reference a non-allocatable/non-pointer array.  I.e., the coarray object
4026      has no array descriptor associated and the addressing is done
4027      completely using the ref.  */
4028   CAF_REF_STATIC_ARRAY
4029 } caf_ref_type_t;
4030 @end verbatim
4032 @verbatim
4033 typedef enum caf_array_ref_t {
4034   /* No array ref.  This terminates the array ref.  */
4035   CAF_ARR_REF_NONE = 0,
4036   /* Reference array elements given by a vector.  Only for this mode
4037      caf_reference_t.u.a.dim[i].v is valid.  */
4038   CAF_ARR_REF_VECTOR,
4039   /* A full array ref (:).  */
4040   CAF_ARR_REF_FULL,
4041   /* Reference a range on elements given by start, end and stride.  */
4042   CAF_ARR_REF_RANGE,
4043   /* Only a single item is referenced given in the start member.  */
4044   CAF_ARR_REF_SINGLE,
4045   /* An array ref of the kind (i:), where i is an arbitrary valid index in the
4046      array.  The index i is given in the start member.  */
4047   CAF_ARR_REF_OPEN_END,
4048   /* An array ref of the kind (:i), where the lower bound of the array ref
4049      is given by the remote side.  The index i is given in the end member.  */
4050   CAF_ARR_REF_OPEN_START
4051 } caf_array_ref_t;
4052 @end verbatim
4054 @verbatim
4055 /* References to remote components of a derived type.  */
4056 typedef struct caf_reference_t {
4057   /* A pointer to the next ref or NULL.  */
4058   struct caf_reference_t *next;
4059   /* The type of the reference.  */
4060   /* caf_ref_type_t, replaced by int to allow specification in fortran FE.  */
4061   int type;
4062   /* The size of an item referenced in bytes.  I.e. in an array ref this is
4063      the factor to advance the array pointer with to get to the next item.
4064      For component refs this gives just the size of the element referenced.  */
4065   size_t item_size;
4066   union {
4067     struct {
4068       /* The offset (in bytes) of the component in the derived type.
4069          Unused for allocatable or pointer components.  */
4070       ptrdiff_t offset;
4071       /* The offset (in bytes) to the caf_token associated with this
4072          component.  NULL, when not allocatable/pointer ref.  */
4073       ptrdiff_t caf_token_offset;
4074     } c;
4075     struct {
4076       /* The mode of the array ref.  See CAF_ARR_REF_*.  */
4077       /* caf_array_ref_t, replaced by unsigend char to allow specification in
4078          fortran FE.  */
4079      unsigned char mode[GFC_MAX_DIMENSIONS];
4080       /* The type of a static array.  Unset for array's with descriptors.  */
4081       int static_array_type;
4082       /* Subscript refs (s) or vector refs (v).  */
4083       union {
4084         struct {
4085           /* The start and end boundary of the ref and the stride.  */
4086           index_type start, end, stride;
4087         } s;
4088         struct {
4089           /* nvec entries of kind giving the elements to reference.  */
4090           void *vector;
4091           /* The number of entries in vector.  */
4092           size_t nvec;
4093           /* The integer kind used for the elements in vector.  */
4094           int kind;
4095         } v;
4096       } dim[GFC_MAX_DIMENSIONS];
4097     } a;
4098   } u;
4099 } caf_reference_t;
4100 @end verbatim
4102 The references make up a single linked list of reference operations.  The
4103 @code{NEXT} member links to the next reference or NULL to indicate the end of
4104 the chain.  Component and array refs can be arbitrarly mixed as long as they
4105 comply to the Fortran standard.
4107 @emph{NOTES}
4108 The member @code{STATIC_ARRAY_TYPE} is used only when the @code{TYPE} is
4109 @code{CAF_REF_STATIC_ARRAY}.  The member gives the type of the data referenced.
4110 Because no array descriptor is available for a descriptor-less array and
4111 type conversion still needs to take place the type is transported here.
4113 At the moment @code{CAF_ARR_REF_VECTOR} is not implemented in the front end for
4114 descriptor-less arrays.  The library caf_single has untested support for it.
4116 @node caf_team_t
4117 @subsection @code{caf_team_t}
4119 Opaque pointer to represent a team-handle.  This type is a stand-in for the
4120 future implementation of teams.  It is about to change without further notice.
4122 @node Function ABI Documentation
4123 @section Function ABI Documentation
4125 @menu
4126 * _gfortran_caf_init:: Initialiation function
4127 * _gfortran_caf_finish:: Finalization function
4128 * _gfortran_caf_this_image:: Querying the image number
4129 * _gfortran_caf_num_images:: Querying the maximal number of images
4130 * _gfortran_caf_image_status :: Query the status of an image
4131 * _gfortran_caf_failed_images :: Get an array of the indexes of the failed images
4132 * _gfortran_caf_stopped_images :: Get an array of the indexes of the stopped images
4133 * _gfortran_caf_register:: Registering coarrays
4134 * _gfortran_caf_deregister:: Deregistering coarrays
4135 * _gfortran_caf_is_present:: Query whether an allocatable or pointer component in a derived type coarray is allocated
4136 * _gfortran_caf_send:: Sending data from a local image to a remote image
4137 * _gfortran_caf_get:: Getting data from a remote image
4138 * _gfortran_caf_sendget:: Sending data between remote images
4139 * _gfortran_caf_send_by_ref:: Sending data from a local image to a remote image using enhanced references
4140 * _gfortran_caf_get_by_ref:: Getting data from a remote image using enhanced references
4141 * _gfortran_caf_sendget_by_ref:: Sending data between remote images using enhanced references
4142 * _gfortran_caf_lock:: Locking a lock variable
4143 * _gfortran_caf_unlock:: Unlocking a lock variable
4144 * _gfortran_caf_event_post:: Post an event
4145 * _gfortran_caf_event_wait:: Wait that an event occurred
4146 * _gfortran_caf_event_query:: Query event count
4147 * _gfortran_caf_sync_all:: All-image barrier
4148 * _gfortran_caf_sync_images:: Barrier for selected images
4149 * _gfortran_caf_sync_memory:: Wait for completion of segment-memory operations
4150 * _gfortran_caf_error_stop:: Error termination with exit code
4151 * _gfortran_caf_error_stop_str:: Error termination with string
4152 * _gfortran_caf_fail_image :: Mark the image failed and end its execution
4153 * _gfortran_caf_atomic_define:: Atomic variable assignment
4154 * _gfortran_caf_atomic_ref:: Atomic variable reference
4155 * _gfortran_caf_atomic_cas:: Atomic compare and swap
4156 * _gfortran_caf_atomic_op:: Atomic operation
4157 * _gfortran_caf_co_broadcast:: Sending data to all images
4158 * _gfortran_caf_co_max:: Collective maximum reduction
4159 * _gfortran_caf_co_min:: Collective minimum reduction
4160 * _gfortran_caf_co_sum:: Collective summing reduction
4161 * _gfortran_caf_co_reduce:: Generic collective reduction
4162 @end menu
4165 @node _gfortran_caf_init
4166 @subsection @code{_gfortran_caf_init} --- Initialiation function
4167 @cindex Coarray, _gfortran_caf_init
4169 @table @asis
4170 @item @emph{Description}:
4171 This function is called at startup of the program before the Fortran main
4172 program, if the latter has been compiled with @option{-fcoarray=lib}.
4173 It takes as arguments the command-line arguments of the program.  It is
4174 permitted to pass two @code{NULL} pointers as argument; if non-@code{NULL},
4175 the library is permitted to modify the arguments.
4177 @item @emph{Syntax}:
4178 @code{void _gfortran_caf_init (int *argc, char ***argv)}
4180 @item @emph{Arguments}:
4181 @multitable @columnfractions .15 .70
4182 @item @var{argc} @tab intent(inout) An integer pointer with the number of
4183 arguments passed to the program or @code{NULL}.
4184 @item @var{argv} @tab intent(inout) A pointer to an array of strings with the
4185 command-line arguments or @code{NULL}.
4186 @end multitable
4188 @item @emph{NOTES}
4189 The function is modelled after the initialization function of the Message
4190 Passing Interface (MPI) specification.  Due to the way coarray registration
4191 works, it might not be the first call to the library.  If the main program is
4192 not written in Fortran and only a library uses coarrays, it can happen that
4193 this function is never called.  Therefore, it is recommended that the library
4194 does not rely on the passed arguments and whether the call has been done.
4195 @end table
4198 @node _gfortran_caf_finish
4199 @subsection @code{_gfortran_caf_finish} --- Finalization function
4200 @cindex Coarray, _gfortran_caf_finish
4202 @table @asis
4203 @item @emph{Description}:
4204 This function is called at the end of the Fortran main program, if it has
4205 been compiled with the @option{-fcoarray=lib} option.
4207 @item @emph{Syntax}:
4208 @code{void _gfortran_caf_finish (void)}
4210 @item @emph{NOTES}
4211 For non-Fortran programs, it is recommended to call the function at the end
4212 of the main program.  To ensure that the shutdown is also performed for
4213 programs where this function is not explicitly invoked, for instance
4214 non-Fortran programs or calls to the system's exit() function, the library
4215 can use a destructor function.  Note that programs can also be terminated
4216 using the STOP and ERROR STOP statements; those use different library calls.
4217 @end table
4220 @node _gfortran_caf_this_image
4221 @subsection @code{_gfortran_caf_this_image} --- Querying the image number
4222 @cindex Coarray, _gfortran_caf_this_image
4224 @table @asis
4225 @item @emph{Description}:
4226 This function returns the current image number, which is a positive number.
4228 @item @emph{Syntax}:
4229 @code{int _gfortran_caf_this_image (int distance)}
4231 @item @emph{Arguments}:
4232 @multitable @columnfractions .15 .70
4233 @item @var{distance} @tab As specified for the @code{this_image} intrinsic
4234 in TS18508.  Shall be a non-negative number.
4235 @end multitable
4237 @item @emph{NOTES}
4238 If the Fortran intrinsic @code{this_image} is invoked without an argument, which
4239 is the only permitted form in Fortran 2008, GCC passes @code{0} as
4240 first argument.
4241 @end table
4244 @node _gfortran_caf_num_images
4245 @subsection @code{_gfortran_caf_num_images} --- Querying the maximal number of images
4246 @cindex Coarray, _gfortran_caf_num_images
4248 @table @asis
4249 @item @emph{Description}:
4250 This function returns the number of images in the current team, if
4251 @var{distance} is 0 or the number of images in the parent team at the specified
4252 distance. If failed is -1, the function returns the number of all images at
4253 the specified distance; if it is 0, the function returns the number of
4254 nonfailed images, and if it is 1, it returns the number of failed images.
4256 @item @emph{Syntax}:
4257 @code{int _gfortran_caf_num_images(int distance, int failed)}
4259 @item @emph{Arguments}:
4260 @multitable @columnfractions .15 .70
4261 @item @var{distance} @tab the distance from this image to the ancestor.
4262 Shall be positive.
4263 @item @var{failed} @tab shall be -1, 0, or 1
4264 @end multitable
4266 @item @emph{NOTES}
4267 This function follows TS18508. If the num_image intrinsic has no arguments,
4268 then the compiler passes @code{distance=0} and @code{failed=-1} to the function.
4269 @end table
4272 @node _gfortran_caf_image_status
4273 @subsection @code{_gfortran_caf_image_status} --- Query the status of an image
4274 @cindex Coarray, _gfortran_caf_image_status
4276 @table @asis
4277 @item @emph{Description}:
4278 Get the status of the image given by the id @var{image} of the team given by
4279 @var{team}.  Valid results are zero, for image is ok, @code{STAT_STOPPED_IMAGE}
4280 from the ISO_FORTRAN_ENV module to indicate that the image has been stopped and
4281 @code{STAT_FAILED_IMAGE} also from ISO_FORTRAN_ENV to indicate that the image
4282 has executed a @code{FAIL IMAGE} statement.
4284 @item @emph{Syntax}:
4285 @code{int _gfortran_caf_image_status (int image, caf_team_t * team)}
4287 @item @emph{Arguments}:
4288 @multitable @columnfractions .15 .70
4289 @item @var{image} @tab the positive scalar id of the image in the current TEAM.
4290 @item @var{team} @tab optional; team on the which the inquiry is to be
4291 performed.
4292 @end multitable
4294 @item @emph{NOTES}
4295 This function follows TS18508.  Because team-functionality is not yet
4296 implemented a null-pointer is passed for the @var{team} argument at the moment.
4297 @end table
4300 @node _gfortran_caf_failed_images
4301 @subsection @code{_gfortran_caf_failed_images} --- Get an array of the indexes of the failed images
4302 @cindex Coarray, _gfortran_caf_failed_images
4304 @table @asis
4305 @item @emph{Description}:
4306 Get an array of image indexes in the current @var{team} that have failed.  The
4307 array is sorted ascendingly.  When @var{team} is not provided the current team
4308 is to be used.  When @var{kind} is provided then the resulting array is of that
4309 integer kind else it is of default integer kind.  The returns an unallocated
4310 size zero array when no images have failed.
4312 @item @emph{Syntax}:
4313 @code{int _gfortran_caf_failed_images (caf_team_t * team, int * kind)}
4315 @item @emph{Arguments}:
4316 @multitable @columnfractions .15 .70
4317 @item @var{team} @tab optional; team on the which the inquiry is to be
4318 performed.
4319 @item @var{image} @tab optional; the kind of the resulting integer array.
4320 @end multitable
4322 @item @emph{NOTES}
4323 This function follows TS18508.  Because team-functionality is not yet
4324 implemented a null-pointer is passed for the @var{team} argument at the moment.
4325 @end table
4328 @node _gfortran_caf_stopped_images
4329 @subsection @code{_gfortran_caf_stopped_images} --- Get an array of the indexes of the stopped images
4330 @cindex Coarray, _gfortran_caf_stopped_images
4332 @table @asis
4333 @item @emph{Description}:
4334 Get an array of image indexes in the current @var{team} that have stopped.  The
4335 array is sorted ascendingly.  When @var{team} is not provided the current team
4336 is to be used.  When @var{kind} is provided then the resulting array is of that
4337 integer kind else it is of default integer kind.  The returns an unallocated
4338 size zero array when no images have failed.
4340 @item @emph{Syntax}:
4341 @code{int _gfortran_caf_stopped_images (caf_team_t * team, int * kind)}
4343 @item @emph{Arguments}:
4344 @multitable @columnfractions .15 .70
4345 @item @var{team} @tab optional; team on the which the inquiry is to be
4346 performed.
4347 @item @var{image} @tab optional; the kind of the resulting integer array.
4348 @end multitable
4350 @item @emph{NOTES}
4351 This function follows TS18508.  Because team-functionality is not yet
4352 implemented a null-pointer is passed for the @var{team} argument at the moment.
4353 @end table
4356 @node _gfortran_caf_register
4357 @subsection @code{_gfortran_caf_register} --- Registering coarrays
4358 @cindex Coarray, _gfortran_caf_register
4360 @table @asis
4361 @item @emph{Description}:
4362 Registers memory for a coarray and creates a token to identify the coarray.  The
4363 routine is called for both coarrays with @code{SAVE} attribute and using an
4364 explicit @code{ALLOCATE} statement.  If an error occurs and @var{STAT} is a
4365 @code{NULL} pointer, the function shall abort with printing an error message
4366 and starting the error termination.  If no error occurs and @var{STAT} is
4367 present, it shall be set to zero.  Otherwise, it shall be set to a positive
4368 value and, if not-@code{NULL}, @var{ERRMSG} shall be set to a string describing
4369 the failure.  The routine shall register the memory provided in the
4370 @code{DATA}-component of the array descriptor @var{DESC}, when that component
4371 is non-@code{NULL}, else it shall allocate sufficient memory and provide a
4372 pointer to it in the @code{DATA}-component of @var{DESC}.  The array descriptor
4373 has rank zero, when a scalar object is to be registered and the array
4374 descriptor may be invalid after the call to @code{_gfortran_caf_register}.
4375 When an array is to be allocated the descriptor persists.
4377 For @code{CAF_REGTYPE_COARRAY_STATIC} and @code{CAF_REGTYPE_COARRAY_ALLOC},
4378 the passed size is the byte size requested.  For @code{CAF_REGTYPE_LOCK_STATIC},
4379 @code{CAF_REGTYPE_LOCK_ALLOC} and @code{CAF_REGTYPE_CRITICAL} it is the array
4380 size or one for a scalar.
4382 When @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} is used, then only a token
4383 for an allocatable or pointer component is created.  The @code{SIZE} parameter
4384 is not used then.  On the contrary when
4385 @code{CAF_REGTYPE_COARRAY_ALLOC_ALLOCATE_ONLY} is specified, then the
4386 @var{token} needs to be registered by a previous call with regtype
4387 @code{CAF_REGTYPE_COARRAY_ALLOC_REGISTER_ONLY} and either the memory specified
4388 in the @var{desc}'s data-ptr is registered or allocate when the data-ptr is
4389 NULL.
4391 @item @emph{Syntax}:
4392 @code{void caf_register (size_t size, caf_register_t type, caf_token_t *token,
4393 gfc_descriptor_t *desc, int *stat, char *errmsg, int errmsg_len)}
4395 @item @emph{Arguments}:
4396 @multitable @columnfractions .15 .70
4397 @item @var{size} @tab For normal coarrays, the byte size of the coarray to be
4398 allocated; for lock types and event types, the number of elements.
4399 @item @var{type} @tab one of the caf_register_t types.
4400 @item @var{token} @tab intent(out) An opaque pointer identifying the coarray.
4401 @item @var{desc} @tab intent(inout) The (pseudo) array descriptor.
4402 @item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
4403 may be NULL
4404 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4405 an error message; may be NULL
4406 @item @var{errmsg_len} @tab the buffer size of errmsg.
4407 @end multitable
4409 @item @emph{NOTES}
4410 Nonalloatable coarrays have to be registered prior use from remote images.
4411 In order to guarantee this, they have to be registered before the main
4412 program. This can be achieved by creating constructor functions. That is what
4413 GCC does such that also nonallocatable coarrays the memory is allocated and no
4414 static memory is used.  The token permits to identify the coarray; to the
4415 processor, the token is a nonaliasing pointer. The library can, for instance,
4416 store the base address of the coarray in the token, some handle or a more
4417 complicated struct.  The library may also store the array descriptor
4418 @var{DESC} when its rank is non-zero.
4420 For lock types, the value shall only used for checking the allocation
4421 status. Note that for critical blocks, the locking is only required on one
4422 image; in the locking statement, the processor shall always pass an
4423 image index of one for critical-block lock variables
4424 (@code{CAF_REGTYPE_CRITICAL}). For lock types and critical-block variables,
4425 the initial value shall be unlocked (or, respecitively, not in critical
4426 section) such as the value false; for event types, the initial state should
4427 be no event, e.g. zero.
4428 @end table
4431 @node _gfortran_caf_deregister
4432 @subsection @code{_gfortran_caf_deregister} --- Deregistering coarrays
4433 @cindex Coarray, _gfortran_caf_deregister
4435 @table @asis
4436 @item @emph{Description}:
4437 Called to free or deregister the memory of a coarray; the processor calls this
4438 function for automatic and explicit deallocation.  In case of an error, this
4439 function shall fail with an error message, unless the @var{STAT} variable is
4440 not null.  The library is only expected to free memory it allocated itself
4441 during a call to @code{_gfortran_caf_register}.
4443 @item @emph{Syntax}:
4444 @code{void caf_deregister (caf_token_t *token, caf_deregister_t type,
4445 int *stat, char *errmsg, int errmsg_len)}
4447 @item @emph{Arguments}:
4448 @multitable @columnfractions .15 .70
4449 @item @var{token} @tab the token to free.
4450 @item @var{type} @tab the type of action to take for the coarray.  A
4451 @code{CAF_DEREGTYPE_COARRAY_DEALLOCATE_ONLY} is allowed only for allocatable or
4452 pointer components of derived type coarrays.  The action only deallocates the
4453 local memory without deleting the token.
4454 @item @var{stat} @tab intent(out) Stores the STAT=; may be NULL
4455 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set
4456 to an error message; may be NULL
4457 @item @var{errmsg_len} @tab the buffer size of errmsg.
4458 @end multitable
4460 @item @emph{NOTES}
4461 For nonalloatable coarrays this function is never called.  If a cleanup is
4462 required, it has to be handled via the finish, stop and error stop functions,
4463 and via destructors.
4464 @end table
4467 @node _gfortran_caf_is_present
4468 @subsection @code{_gfortran_caf_is_present} --- Query whether an allocatable or pointer component in a derived type coarray is allocated
4469 @cindex Coarray, _gfortran_caf_is_present
4471 @table @asis
4472 @item @emph{Description}:
4473 Used to query the coarray library whether an allocatable component in a derived
4474 type coarray is allocated on a remote image.
4476 @item @emph{Syntax}:
4477 @code{void _gfortran_caf_is_present (caf_token_t token, int image_index,
4478 gfc_reference_t *ref)}
4480 @item @emph{Arguments}:
4481 @multitable @columnfractions .15 .70
4482 @item @var{token} @tab An opaque pointer identifying the coarray.
4483 @item @var{image_index} @tab The ID of the remote image; must be a positive
4484 number.
4485 @item @var{ref} @tab A chain of references to address the allocatable or
4486 pointer component in the derived type coarray.  The object reference needs to be
4487 a scalar or a full array reference, respectively.
4488 @end multitable
4490 @end table
4492 @node _gfortran_caf_send
4493 @subsection @code{_gfortran_caf_send} --- Sending data from a local image to a remote image
4494 @cindex Coarray, _gfortran_caf_send
4496 @table @asis
4497 @item @emph{Description}:
4498 Called to send a scalar, an array section or a whole array from a local
4499 to a remote image identified by the image_index.
4501 @item @emph{Syntax}:
4502 @code{void _gfortran_caf_send (caf_token_t token, size_t offset,
4503 int image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
4504 gfc_descriptor_t *src, int dst_kind, int src_kind, bool may_require_tmp,
4505 int *stat)}
4507 @item @emph{Arguments}:
4508 @multitable @columnfractions .15 .70
4509 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4510 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
4511 shifted compared to the base address of the coarray.
4512 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4513 positive number.
4514 @item @var{dest} @tab intent(in)  Array descriptor for the remote image for the
4515 bounds and the size.  The @code{base_addr} shall not be accessed.
4516 @item @var{dst_vector} @tab intent(in)  If not NULL, it contains the vector
4517 subscript of the destination array; the values are relative to the dimension
4518 triplet of the dest argument.
4519 @item @var{src} @tab intent(in)  Array descriptor of the local array to be
4520 transferred to the remote image
4521 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4522 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4523 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4524 it is known at compile time that the @var{dest} and @var{src} either cannot
4525 overlap or overlap (fully or partially) such that walking @var{src} and
4526 @var{dest} in element wise element order (honoring the stride value) will not
4527 lead to wrong results.  Otherwise, the value is @code{true}.
4528 @item @var{stat} @tab intent(out) when non-NULL give the result of the
4529 operation, i.e., zero on success and non-zero on error.  When NULL and an error
4530 occurs, then an error message is printed and the program is terminated.
4531 @end multitable
4533 @item @emph{NOTES}
4534 It is permitted to have @var{image_index} equal the current image; the memory
4535 of the send-to and the send-from might (partially) overlap in that case.  The
4536 implementation has to take care that it handles this case, e.g. using
4537 @code{memmove} which handles (partially) overlapping memory. If
4538 @var{may_require_tmp} is true, the library might additionally create a
4539 temporary variable, unless additional checks show that this is not required
4540 (e.g. because walking backward is possible or because both arrays are
4541 contiguous and @code{memmove} takes care of overlap issues).
4543 Note that the assignment of a scalar to an array is permitted. In addition,
4544 the library has to handle numeric-type conversion and for strings, padding
4545 and different character kinds.
4546 @end table
4549 @node _gfortran_caf_get
4550 @subsection @code{_gfortran_caf_get} --- Getting data from a remote image
4551 @cindex Coarray, _gfortran_caf_get
4553 @table @asis
4554 @item @emph{Description}:
4555 Called to get an array section or a whole array from a remote,
4556 image identified by the image_index.
4558 @item @emph{Syntax}:
4559 @code{void _gfortran_caf_get (caf_token_t token, size_t offset,
4560 int image_index, gfc_descriptor_t *src, caf_vector_t *src_vector,
4561 gfc_descriptor_t *dest, int src_kind, int dst_kind, bool may_require_tmp,
4562 int *stat)}
4564 @item @emph{Arguments}:
4565 @multitable @columnfractions .15 .70
4566 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4567 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
4568 shifted compared to the base address of the coarray.
4569 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4570 positive number.
4571 @item @var{dest} @tab intent(out) Array descriptor of the local array to store
4572 the data retrieved from the remote image
4573 @item @var{src} @tab intent(in) Array descriptor for the remote image for the
4574 bounds and the size.  The @code{base_addr} shall not be accessed.
4575 @item @var{src_vector} @tab intent(in)  If not NULL, it contains the vector
4576 subscript of the source array; the values are relative to the dimension
4577 triplet of the @var{src} argument.
4578 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4579 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4580 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4581 it is known at compile time that the @var{dest} and @var{src} either cannot
4582 overlap or overlap (fully or partially) such that walking @var{src} and
4583 @var{dest} in element wise element order (honoring the stride value) will not
4584 lead to wrong results.  Otherwise, the value is @code{true}.
4585 @item @var{stat} @tab intent(out) When non-NULL give the result of the
4586 operation, i.e., zero on success and non-zero on error.  When NULL and an error
4587 occurs, then an error message is printed and the program is terminated.
4588 @end multitable
4590 @item @emph{NOTES}
4591 It is permitted to have @var{image_index} equal the current image; the memory of
4592 the send-to and the send-from might (partially) overlap in that case.  The
4593 implementation has to take care that it handles this case, e.g. using
4594 @code{memmove} which handles (partially) overlapping memory. If
4595 @var{may_require_tmp} is true, the library might additionally create a
4596 temporary variable, unless additional checks show that this is not required
4597 (e.g. because walking backward is possible or because both arrays are
4598 contiguous and @code{memmove} takes care of overlap issues).
4600 Note that the library has to handle numeric-type conversion and for strings,
4601 padding and different character kinds.
4602 @end table
4605 @node _gfortran_caf_sendget
4606 @subsection @code{_gfortran_caf_sendget} --- Sending data between remote images
4607 @cindex Coarray, _gfortran_caf_sendget
4609 @table @asis
4610 @item @emph{Description}:
4611 Called to send a scalar, an array section or a whole array from a remote image
4612 identified by the @var{src_image_index} to a remote image identified by the
4613 @var{dst_image_index}.
4615 @item @emph{Syntax}:
4616 @code{void _gfortran_caf_sendget (caf_token_t dst_token, size_t dst_offset,
4617 int dst_image_index, gfc_descriptor_t *dest, caf_vector_t *dst_vector,
4618 caf_token_t src_token, size_t src_offset, int src_image_index,
4619 gfc_descriptor_t *src, caf_vector_t *src_vector, int dst_kind, int src_kind,
4620 bool may_require_tmp, int *stat)}
4622 @item @emph{Arguments}:
4623 @multitable @columnfractions .15 .70
4624 @item @var{dst_token} @tab intent(in)  An opaque pointer identifying the
4625 destination coarray.
4626 @item @var{dst_offset} @tab intent(in)  By which amount of bytes the actual data
4627 is shifted compared to the base address of the destination coarray.
4628 @item @var{dst_image_index} @tab intent(in)  The ID of the destination remote
4629 image; must be a positive number.
4630 @item @var{dest} @tab intent(in) Array descriptor for the destination
4631 remote image for the bounds and the size.  The @code{base_addr} shall not be
4632 accessed.
4633 @item @var{dst_vector} @tab intent(int)  If not NULL, it contains the vector
4634 subscript of the destination array; the values are relative to the dimension
4635 triplet of the @var{dest} argument.
4636 @item @var{src_token} @tab intent(in)  An opaque pointer identifying the source
4637 coarray.
4638 @item @var{src_offset} @tab intent(in)  By which amount of bytes the actual data
4639 is shifted compared to the base address of the source coarray.
4640 @item @var{src_image_index} @tab intent(in)  The ID of the source remote image;
4641 must be a positive number.
4642 @item @var{src} @tab intent(in) Array descriptor of the local array to be
4643 transferred to the remote image.
4644 @item @var{src_vector} @tab intent(in) Array descriptor of the local array to
4645 be transferred to the remote image
4646 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4647 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4648 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4649 it is known at compile time that the @var{dest} and @var{src} either cannot
4650 overlap or overlap (fully or partially) such that walking @var{src} and
4651 @var{dest} in element wise element order (honoring the stride value) will not
4652 lead to wrong results.  Otherwise, the value is @code{true}.
4653 @item @var{stat} @tab intent(out) when non-NULL give the result of the
4654 operation, i.e., zero on success and non-zero on error.  When NULL and an error
4655 occurs, then an error message is printed and the program is terminated.
4656 @end multitable
4658 @item @emph{NOTES}
4659 It is permitted to have the same image index for both @var{src_image_index} and
4660 @var{dst_image_index}; the memory of the send-to and the send-from might
4661 (partially) overlap in that case.  The implementation has to take care that it
4662 handles this case, e.g. using @code{memmove} which handles (partially)
4663 overlapping memory.  If @var{may_require_tmp} is true, the library
4664 might additionally create a temporary variable, unless additional checks show
4665 that this is not required (e.g. because walking backward is possible or because
4666 both arrays are contiguous and @code{memmove} takes care of overlap issues).
4668 Note that the assignment of a scalar to an array is permitted. In addition,
4669 the library has to handle numeric-type conversion and for strings, padding and
4670 different character kinds.
4671 @end table
4673 @node _gfortran_caf_send_by_ref
4674 @subsection @code{_gfortran_caf_send_by_ref} --- Sending data from a local image to a remote image with enhanced referencing options
4675 @cindex Coarray, _gfortran_caf_send_by_ref
4677 @table @asis
4678 @item @emph{Description}:
4679 Called to send a scalar, an array section or a whole array from a local to a
4680 remote image identified by the @var{image_index}.
4682 @item @emph{Syntax}:
4683 @code{void _gfortran_caf_send_by_ref (caf_token_t token, int image_index,
4684 gfc_descriptor_t *src, caf_reference_t *refs, int dst_kind, int src_kind,
4685 bool may_require_tmp, bool dst_reallocatable, int *stat)}
4687 @item @emph{Arguments}:
4688 @multitable @columnfractions .15 .70
4689 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4690 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4691 positive number.
4692 @item @var{src} @tab intent(in) Array descriptor of the local array to be
4693 transferred to the remote image
4694 @item @var{refs} @tab intent(in) The references on the remote array to store
4695 the data given by src.  Guaranteed to have at least one entry.
4696 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4697 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4698 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4699 it is known at compile time that the @var{dest} and @var{src} either cannot
4700 overlap or overlap (fully or partially) such that walking @var{src} and
4701 @var{dest} in element wise element order (honoring the stride value) will not
4702 lead to wrong results.  Otherwise, the value is @code{true}.
4703 @item @var{dst_reallocatable} @tab intent(in)  Set when the destination is of
4704 allocatable or pointer type and the refs will allow reallocation, i.e., the ref
4705 is a full array or component ref.
4706 @item @var{stat} @tab intent(out) When non-@code{NULL} give the result of the
4707 operation, i.e., zero on success and non-zero on error.  When @code{NULL} and
4708 an error occurs, then an error message is printed and the program is terminated.
4709 @end multitable
4711 @item @emph{NOTES}
4712 It is permitted to have @var{image_index} equal the current image; the memory of
4713 the send-to and the send-from might (partially) overlap in that case.  The
4714 implementation has to take care that it handles this case, e.g. using
4715 @code{memmove} which handles (partially) overlapping memory.  If
4716 @var{may_require_tmp} is true, the library might additionally create a
4717 temporary variable, unless additional checks show that this is not required
4718 (e.g. because walking backward is possible or because both arrays are
4719 contiguous and @code{memmove} takes care of overlap issues).
4721 Note that the assignment of a scalar to an array is permitted.  In addition,
4722 the library has to handle numeric-type conversion and for strings, padding
4723 and different character kinds.
4725 Because of the more complicated references possible some operations may be
4726 unsupported by certain libraries.  The library is expected to issue a precise
4727 error message why the operation is not permitted.
4728 @end table
4731 @node _gfortran_caf_get_by_ref
4732 @subsection @code{_gfortran_caf_get_by_ref} --- Getting data from a remote image using enhanced references
4733 @cindex Coarray, _gfortran_caf_get_by_ref
4735 @table @asis
4736 @item @emph{Description}:
4737 Called to get a scalar, an array section or a whole array from a remote image
4738 identified by the @var{image_index}.
4740 @item @emph{Syntax}:
4741 @code{void _gfortran_caf_get_by_ref (caf_token_t token, int image_index,
4742 caf_reference_t *refs, gfc_descriptor_t *dst, int dst_kind, int src_kind,
4743 bool may_require_tmp, bool dst_reallocatable, int *stat)}
4745 @item @emph{Arguments}:
4746 @multitable @columnfractions .15 .70
4747 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4748 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4749 positive number.
4750 @item @var{refs} @tab intent(in) The references to apply to the remote structure
4751 to get the data.
4752 @item @var{dst} @tab intent(in) Array descriptor of the local array to store
4753 the data transferred from the remote image.  May be reallocated where needed
4754 and when @var{DST_REALLOCATABLE} allows it.
4755 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4756 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4757 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4758 it is known at compile time that the @var{dest} and @var{src} either cannot
4759 overlap or overlap (fully or partially) such that walking @var{src} and
4760 @var{dest} in element wise element order (honoring the stride value) will not
4761 lead to wrong results.  Otherwise, the value is @code{true}.
4762 @item @var{dst_reallocatable} @tab intent(in)  Set when @var{DST} is of
4763 allocatable or pointer type and its refs allow reallocation, i.e., the full
4764 array or a component is referenced.
4765 @item @var{stat} @tab intent(out) When non-@code{NULL} give the result of the
4766 operation, i.e., zero on success and non-zero on error.  When @code{NULL} and an
4767 error occurs, then an error message is printed and the program is terminated.
4768 @end multitable
4770 @item @emph{NOTES}
4771 It is permitted to have @code{image_index} equal the current image; the memory
4772 of the send-to and the send-from might (partially) overlap in that case.  The
4773 implementation has to take care that it handles this case, e.g. using
4774 @code{memmove} which handles (partially) overlapping memory.  If
4775 @var{may_require_tmp} is true, the library might additionally create a
4776 temporary variable, unless additional checks show that this is not required
4777 (e.g. because walking backward is possible or because both arrays are
4778 contiguous and @code{memmove} takes care of overlap issues).
4780 Note that the library has to handle numeric-type conversion and for strings,
4781 padding and different character kinds.
4783 Because of the more complicated references possible some operations may be
4784 unsupported by certain libraries.  The library is expected to issue a precise
4785 error message why the operation is not permitted.
4786 @end table
4789 @node _gfortran_caf_sendget_by_ref
4790 @subsection @code{_gfortran_caf_sendget_by_ref} --- Sending data between remote images using enhanced references on both sides
4791 @cindex Coarray, _gfortran_caf_sendget_by_ref
4793 @table @asis
4794 @item @emph{Description}:
4795 Called to send a scalar, an array section or a whole array from a remote image
4796 identified by the @var{src_image_index} to a remote image identified by the
4797 @var{dst_image_index}.
4799 @item @emph{Syntax}:
4800 @code{void _gfortran_caf_sendget_by_ref (caf_token_t dst_token,
4801 int dst_image_index, caf_reference_t *dst_refs,
4802 caf_token_t src_token, int src_image_index, caf_reference_t *src_refs,
4803 int dst_kind, int src_kind, bool may_require_tmp, int *dst_stat, int *src_stat)}
4805 @item @emph{Arguments}:
4806 @multitable @columnfractions .15 .70
4807 @item @var{dst_token} @tab intent(in)  An opaque pointer identifying the
4808 destination coarray.
4809 @item @var{dst_image_index} @tab intent(in)  The ID of the destination remote
4810 image; must be a positive number.
4811 @item @var{dst_refs} @tab intent(in) The references on the remote array to store
4812 the data given by the source.  Guaranteed to have at least one entry.
4813 @item @var{src_token} @tab intent(in)  An opaque pointer identifying the source
4814 coarray.
4815 @item @var{src_image_index} @tab intent(in)  The ID of the source remote image;
4816 must be a positive number.
4817 @item @var{src_refs} @tab intent(in) The references to apply to the remote
4818 structure to get the data.
4819 @item @var{dst_kind} @tab intent(in)  Kind of the destination argument
4820 @item @var{src_kind} @tab intent(in)  Kind of the source argument
4821 @item @var{may_require_tmp} @tab intent(in)  The variable is @code{false} when
4822 it is known at compile time that the @var{dest} and @var{src} either cannot
4823 overlap or overlap (fully or partially) such that walking @var{src} and
4824 @var{dest} in element wise element order (honoring the stride value) will not
4825 lead to wrong results.  Otherwise, the value is @code{true}.
4826 @item @var{dst_stat} @tab intent(out) when non-@code{NULL} give the result of
4827 the send-operation, i.e., zero on success and non-zero on error.  When
4828 @code{NULL} and an error occurs, then an error message is printed and the
4829 program is terminated.
4830 @item @var{src_stat} @tab intent(out) When non-@code{NULL} give the result of
4831 the get-operation, i.e., zero on success and non-zero on error.  When
4832 @code{NULL} and an error occurs, then an error message is printed and the
4833 program is terminated.
4834 @end multitable
4836 @item @emph{NOTES}
4837 It is permitted to have the same image index for both @var{src_image_index} and
4838 @var{dst_image_index}; the memory of the send-to and the send-from might
4839 (partially) overlap in that case.  The implementation has to take care that it
4840 handles this case, e.g. using @code{memmove} which handles (partially)
4841 overlapping memory.  If @var{may_require_tmp} is true, the library
4842 might additionally create a temporary variable, unless additional checks show
4843 that this is not required (e.g. because walking backward is possible or because
4844 both arrays are contiguous and @code{memmove} takes care of overlap issues).
4846 Note that the assignment of a scalar to an array is permitted.  In addition,
4847 the library has to handle numeric-type conversion and for strings, padding and
4848 different character kinds.
4850 Because of the more complicated references possible some operations may be
4851 unsupported by certain libraries.  The library is expected to issue a precise
4852 error message why the operation is not permitted.
4853 @end table
4856 @node _gfortran_caf_lock
4857 @subsection @code{_gfortran_caf_lock} --- Locking a lock variable
4858 @cindex Coarray, _gfortran_caf_lock
4860 @table @asis
4861 @item @emph{Description}:
4862 Acquire a lock on the given image on a scalar locking variable or for the
4863 given array element for an array-valued variable.  If the @var{aquired_lock}
4864 is @code{NULL}, the function returns after having obtained the lock.  If it is
4865 non-@code{NULL}, then @var{acquired_lock} is assigned the value true (one) when
4866 the lock could be obtained and false (zero) otherwise.  Locking a lock variable
4867 which has already been locked by the same image is an error.
4869 @item @emph{Syntax}:
4870 @code{void _gfortran_caf_lock (caf_token_t token, size_t index, int image_index,
4871 int *aquired_lock, int *stat, char *errmsg, int errmsg_len)}
4873 @item @emph{Arguments}:
4874 @multitable @columnfractions .15 .70
4875 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4876 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
4877 scalars, it is always 0.
4878 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4879 positive number.
4880 @item @var{aquired_lock} @tab intent(out) If not NULL, it returns whether lock
4881 could be obtained.
4882 @item @var{stat} @tab intent(out) Stores the STAT=; may be NULL.
4883 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4884 an error message; may be NULL.
4885 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
4886 @end multitable
4888 @item @emph{NOTES}
4889 This function is also called for critical blocks; for those, the array index
4890 is always zero and the image index is one.  Libraries are permitted to use other
4891 images for critical-block locking variables.
4892 @end table
4894 @node _gfortran_caf_unlock
4895 @subsection @code{_gfortran_caf_lock} --- Unlocking a lock variable
4896 @cindex Coarray, _gfortran_caf_unlock
4898 @table @asis
4899 @item @emph{Description}:
4900 Release a lock on the given image on a scalar locking variable or for the
4901 given array element for an array-valued variable. Unlocking a lock variable
4902 which is unlocked or has been locked by a different image is an error.
4904 @item @emph{Syntax}:
4905 @code{void _gfortran_caf_unlock (caf_token_t token, size_t index, int image_index,
4906 int *stat, char *errmsg, int errmsg_len)}
4908 @item @emph{Arguments}:
4909 @multitable @columnfractions .15 .70
4910 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4911 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
4912 scalars, it is always 0.
4913 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4914 positive number.
4915 @item @var{stat} @tab intent(out) For allocatable coarrays, stores the STAT=;
4916 may be NULL.
4917 @item @var{errmsg} @tab intent(out) When an error occurs, this will be set to
4918 an error message; may be NULL.
4919 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
4920 @end multitable
4922 @item @emph{NOTES}
4923 This function is also called for critical block; for those, the array index
4924 is always zero and the image index is one.  Libraries are permitted to use other
4925 images for critical-block locking variables.
4926 @end table
4928 @node _gfortran_caf_event_post
4929 @subsection @code{_gfortran_caf_event_post} --- Post an event
4930 @cindex Coarray, _gfortran_caf_event_post
4932 @table @asis
4933 @item @emph{Description}:
4934 Increment the event count of the specified event variable.
4936 @item @emph{Syntax}:
4937 @code{void _gfortran_caf_event_post (caf_token_t token, size_t index,
4938 int image_index, int *stat, char *errmsg, int errmsg_len)}
4940 @item @emph{Arguments}:
4941 @multitable @columnfractions .15 .70
4942 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4943 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
4944 scalars, it is always 0.
4945 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
4946 positive number; zero indicates the current image, when accessed noncoindexed.
4947 @item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
4948 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
4949 an error message; may be NULL.
4950 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
4951 @end multitable
4953 @item @emph{NOTES}
4954 This acts like an atomic add of one to the remote image's event variable.
4955 The statement is an image-control statement but does not imply sync memory.
4956 Still, all preceeding push communications of this image to the specified
4957 remote image have to be completed before @code{event_wait} on the remote
4958 image returns.
4959 @end table
4963 @node _gfortran_caf_event_wait
4964 @subsection @code{_gfortran_caf_event_wait} --- Wait that an event occurred
4965 @cindex Coarray, _gfortran_caf_event_wait
4967 @table @asis
4968 @item @emph{Description}:
4969 Wait until the event count has reached at least the specified
4970 @var{until_count}; if so, atomically decrement the event variable by this
4971 amount and return.
4973 @item @emph{Syntax}:
4974 @code{void _gfortran_caf_event_wait (caf_token_t token, size_t index,
4975 int until_count, int *stat, char *errmsg, int errmsg_len)}
4977 @item @emph{Arguments}:
4978 @multitable @columnfractions .15 .70
4979 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
4980 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
4981 scalars, it is always 0.
4982 @item @var{until_count} @tab intent(in)  The number of events which have to be
4983 available before the function returns.
4984 @item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
4985 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
4986 an error message; may be NULL.
4987 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
4988 @end multitable
4990 @item @emph{NOTES}
4991 This function only operates on a local coarray. It acts like a loop checking
4992 atomically the value of the event variable, breaking if the value is greater
4993 or equal the requested number of counts. Before the function returns, the
4994 event variable has to be decremented by the requested @var{until_count} value.
4995 A possible implementation would be a busy loop for a certain number of spins
4996 (possibly depending on the number of threads relative to the number of available
4997 cores) followed by another waiting strategy such as a sleeping wait (possibly
4998 with an increasing number of sleep time) or, if possible, a futex wait.
5000 The statement is an image-control statement but does not imply sync memory.
5001 Still, all preceeding push communications of this image to the specified
5002 remote image have to be completed before @code{event_wait} on the remote
5003 image returns.
5004 @end table
5008 @node _gfortran_caf_event_query
5009 @subsection @code{_gfortran_caf_event_query} --- Query event count
5010 @cindex Coarray, _gfortran_caf_event_query
5012 @table @asis
5013 @item @emph{Description}:
5014 Return the event count of the specified event variable.
5016 @item @emph{Syntax}:
5017 @code{void _gfortran_caf_event_query (caf_token_t token, size_t index,
5018 int image_index, int *count, int *stat)}
5020 @item @emph{Arguments}:
5021 @multitable @columnfractions .15 .70
5022 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5023 @item @var{index} @tab intent(in)  Array index; first array index is 0.  For
5024 scalars, it is always 0.
5025 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5026 positive number; zero indicates the current image when accessed noncoindexed.
5027 @item @var{count} @tab intent(out)  The number of events currently posted to
5028 the event variable.
5029 @item @var{stat} @tab intent(out)  Stores the STAT=; may be NULL.
5030 @end multitable
5032 @item @emph{NOTES}
5033 The typical use is to check the local event variable to only call
5034 @code{event_wait} when the data is available. However, a coindexed variable
5035 is permitted; there is no ordering or synchronization implied.  It acts like
5036 an atomic fetch of the value of the event variable.
5037 @end table
5041 @node _gfortran_caf_sync_all
5042 @subsection @code{_gfortran_caf_sync_all} --- All-image barrier
5043 @cindex Coarray, _gfortran_caf_sync_all
5045 @table @asis
5046 @item @emph{Description}:
5047 Synchronization of all images in the current team; the program only continues
5048 on a given image after this function has been called on all images of the
5049 current team.  Additionally, it ensures that all pending data transfers of
5050 previous segment have completed.
5052 @item @emph{Syntax}:
5053 @code{void _gfortran_caf_sync_all (int *stat, char *errmsg, int errmsg_len)}
5055 @item @emph{Arguments}:
5056 @multitable @columnfractions .15 .70
5057 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5058 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5059 an error message; may be NULL.
5060 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5061 @end multitable
5062 @end table
5066 @node _gfortran_caf_sync_images
5067 @subsection @code{_gfortran_caf_sync_images} --- Barrier for selected images
5068 @cindex Coarray, _gfortran_caf_sync_images
5070 @table @asis
5071 @item @emph{Description}:
5072 Synchronization between the specified images; the program only continues on a
5073 given image after this function has been called on all images specified for
5074 that image. Note that one image can wait for all other images in the current
5075 team (e.g. via @code{sync images(*)}) while those only wait for that specific
5076 image.  Additionally, @code{sync images} ensures that all pending data
5077 transfers of previous segments have completed.
5079 @item @emph{Syntax}:
5080 @code{void _gfortran_caf_sync_images (int count, int images[], int *stat,
5081 char *errmsg, int errmsg_len)}
5083 @item @emph{Arguments}:
5084 @multitable @columnfractions .15 .70
5085 @item @var{count} @tab intent(in)  The number of images which are provided in
5086 the next argument.  For a zero-sized array, the value is zero.  For
5087 @code{sync images (*)}, the value is @math{-1}.
5088 @item @var{images} @tab intent(in)  An array with the images provided by the
5089 user.  If @var{count} is zero, a NULL pointer is passed.
5090 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5091 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5092 an error message; may be NULL.
5093 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5094 @end multitable
5095 @end table
5099 @node _gfortran_caf_sync_memory
5100 @subsection @code{_gfortran_caf_sync_memory} --- Wait for completion of segment-memory operations
5101 @cindex Coarray, _gfortran_caf_sync_memory
5103 @table @asis
5104 @item @emph{Description}:
5105 Acts as optimization barrier between different segments. It also ensures that
5106 all pending memory operations of this image have been completed.
5108 @item @emph{Syntax}:
5109 @code{void _gfortran_caf_sync_memory (int *stat, char *errmsg, int errmsg_len)}
5111 @item @emph{Arguments}:
5112 @multitable @columnfractions .15 .70
5113 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5114 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5115 an error message; may be NULL.
5116 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5117 @end multitable
5119 @item @emph{NOTE} A simple implementation could be
5120 @code{__asm__ __volatile__ ("":::"memory")} to prevent code movements.
5121 @end table
5125 @node _gfortran_caf_error_stop
5126 @subsection @code{_gfortran_caf_error_stop} --- Error termination with exit code
5127 @cindex Coarray, _gfortran_caf_error_stop
5129 @table @asis
5130 @item @emph{Description}:
5131 Invoked for an @code{ERROR STOP} statement which has an integer argument.  The
5132 function should terminate the program with the specified exit code.
5135 @item @emph{Syntax}:
5136 @code{void _gfortran_caf_error_stop (int32_t error)}
5138 @item @emph{Arguments}:
5139 @multitable @columnfractions .15 .70
5140 @item @var{error} @tab intent(in)  The exit status to be used.
5141 @end multitable
5142 @end table
5146 @node _gfortran_caf_error_stop_str
5147 @subsection @code{_gfortran_caf_error_stop_str} --- Error termination with string
5148 @cindex Coarray, _gfortran_caf_error_stop_str
5150 @table @asis
5151 @item @emph{Description}:
5152 Invoked for an @code{ERROR STOP} statement which has a string as argument.  The
5153 function should terminate the program with a nonzero-exit code.
5155 @item @emph{Syntax}:
5156 @code{void _gfortran_caf_error_stop (const char *string, int32_t len)}
5158 @item @emph{Arguments}:
5159 @multitable @columnfractions .15 .70
5160 @item @var{string} @tab intent(in)  the error message (not zero terminated)
5161 @item @var{len} @tab intent(in)  the length of the string
5162 @end multitable
5163 @end table
5167 @node _gfortran_caf_fail_image
5168 @subsection @code{_gfortran_caf_fail_image} --- Mark the image failed and end its execution
5169 @cindex Coarray, _gfortran_caf_fail_image
5171 @table @asis
5172 @item @emph{Description}:
5173 Invoked for an @code{FAIL IMAGE} statement.  The function should terminate the
5174 current image.
5176 @item @emph{Syntax}:
5177 @code{void _gfortran_caf_fail_image ()}
5179 @item @emph{NOTES}
5180 This function follows TS18508.
5181 @end table
5185 @node _gfortran_caf_atomic_define
5186 @subsection @code{_gfortran_caf_atomic_define} --- Atomic variable assignment
5187 @cindex Coarray, _gfortran_caf_atomic_define
5189 @table @asis
5190 @item @emph{Description}:
5191 Assign atomically a value to an integer or logical variable.
5193 @item @emph{Syntax}:
5194 @code{void _gfortran_caf_atomic_define (caf_token_t token, size_t offset,
5195 int image_index, void *value, int *stat, int type, int kind)}
5197 @item @emph{Arguments}:
5198 @multitable @columnfractions .15 .70
5199 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5200 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5201 shifted compared to the base address of the coarray.
5202 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5203 positive number; zero indicates the current image when used noncoindexed.
5204 @item @var{value} @tab intent(in)  the value to be assigned, passed by reference
5205 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5206 @item @var{type} @tab intent(in)  The data type, i.e. @code{BT_INTEGER} (1) or
5207 @code{BT_LOGICAL} (2).
5208 @item @var{kind} @tab intent(in)  The kind value (only 4; always @code{int})
5209 @end multitable
5210 @end table
5214 @node _gfortran_caf_atomic_ref
5215 @subsection @code{_gfortran_caf_atomic_ref} --- Atomic variable reference
5216 @cindex Coarray, _gfortran_caf_atomic_ref
5218 @table @asis
5219 @item @emph{Description}:
5220 Reference atomically a value of a kind-4 integer or logical variable.
5222 @item @emph{Syntax}:
5223 @code{void _gfortran_caf_atomic_ref (caf_token_t token, size_t offset,
5224 int image_index, void *value, int *stat, int type, int kind)}
5226 @item @emph{Arguments}:
5227 @multitable @columnfractions .15 .70
5228 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5229 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5230 shifted compared to the base address of the coarray.
5231 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5232 positive number; zero indicates the current image when used noncoindexed.
5233 @item @var{value} @tab intent(out)  The variable assigned the atomically
5234 referenced variable.
5235 @item @var{stat} @tab intent(out) Stores the status STAT= and may be NULL.
5236 @item @var{type} @tab the data type, i.e. @code{BT_INTEGER} (1) or
5237 @code{BT_LOGICAL} (2).
5238 @item @var{kind} @tab The kind value (only 4; always @code{int})
5239 @end multitable
5240 @end table
5244 @node _gfortran_caf_atomic_cas
5245 @subsection @code{_gfortran_caf_atomic_cas} --- Atomic compare and swap
5246 @cindex Coarray, _gfortran_caf_atomic_cas
5248 @table @asis
5249 @item @emph{Description}:
5250 Atomic compare and swap of a kind-4 integer or logical variable. Assigns
5251 atomically the specified value to the atomic variable, if the latter has
5252 the value specified by the passed condition value.
5254 @item @emph{Syntax}:
5255 @code{void _gfortran_caf_atomic_cas (caf_token_t token, size_t offset,
5256 int image_index, void *old, void *compare, void *new_val, int *stat,
5257 int type, int kind)}
5259 @item @emph{Arguments}:
5260 @multitable @columnfractions .15 .70
5261 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5262 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5263 shifted compared to the base address of the coarray.
5264 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5265 positive number; zero indicates the current image when used noncoindexed.
5266 @item @var{old} @tab intent(out)  The value which the atomic variable had
5267 just before the cas operation.
5268 @item @var{compare} @tab intent(in)  The value used for comparision.
5269 @item @var{new_val} @tab intent(in)  The new value for the atomic variable,
5270 assigned to the atomic variable, if @code{compare} equals the value of the
5271 atomic variable.
5272 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5273 @item @var{type} @tab intent(in)  the data type, i.e. @code{BT_INTEGER} (1) or
5274 @code{BT_LOGICAL} (2).
5275 @item @var{kind} @tab intent(in)  The kind value (only 4; always @code{int})
5276 @end multitable
5277 @end table
5281 @node _gfortran_caf_atomic_op
5282 @subsection @code{_gfortran_caf_atomic_op} --- Atomic operation
5283 @cindex Coarray, _gfortran_caf_atomic_op
5285 @table @asis
5286 @item @emph{Description}:
5287 Apply an operation atomically to an atomic integer or logical variable.
5288 After the operation, @var{old} contains the value just before the operation,
5289 which, respectively, adds (GFC_CAF_ATOMIC_ADD) atomically the @code{value} to
5290 the atomic integer variable or does a bitwise AND, OR or exclusive OR
5291 between the atomic variable and @var{value}; the result is then stored in the
5292 atomic variable.
5294 @item @emph{Syntax}:
5295 @code{void _gfortran_caf_atomic_op (int op, caf_token_t token, size_t offset,
5296 int image_index, void *value, void *old, int *stat, int type, int kind)}
5298 @item @emph{Arguments}:
5299 @multitable @columnfractions .15 .70
5300 @item @var{op} @tab intent(in)  the operation to be performed; possible values
5301 @code{GFC_CAF_ATOMIC_ADD} (1), @code{GFC_CAF_ATOMIC_AND} (2),
5302 @code{GFC_CAF_ATOMIC_OR} (3), @code{GFC_CAF_ATOMIC_XOR} (4).
5303 @item @var{token} @tab intent(in)  An opaque pointer identifying the coarray.
5304 @item @var{offset} @tab intent(in)  By which amount of bytes the actual data is
5305 shifted compared to the base address of the coarray.
5306 @item @var{image_index} @tab intent(in)  The ID of the remote image; must be a
5307 positive number; zero indicates the current image when used noncoindexed.
5308 @item @var{old} @tab intent(out)  The value which the atomic variable had
5309 just before the atomic operation.
5310 @item @var{val} @tab intent(in)  The new value for the atomic variable,
5311 assigned to the atomic variable, if @code{compare} equals the value of the
5312 atomic variable.
5313 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5314 @item @var{type} @tab intent(in)  the data type, i.e. @code{BT_INTEGER} (1) or
5315 @code{BT_LOGICAL} (2)
5316 @item @var{kind} @tab intent(in)  the kind value (only 4; always @code{int})
5317 @end multitable
5318 @end table
5323 @node _gfortran_caf_co_broadcast
5324 @subsection @code{_gfortran_caf_co_broadcast} --- Sending data to all images
5325 @cindex Coarray, _gfortran_caf_co_broadcast
5327 @table @asis
5328 @item @emph{Description}:
5329 Distribute a value from a given image to all other images in the team. Has to
5330 be called collectively.
5332 @item @emph{Syntax}:
5333 @code{void _gfortran_caf_co_broadcast (gfc_descriptor_t *a,
5334 int source_image, int *stat, char *errmsg, int errmsg_len)}
5336 @item @emph{Arguments}:
5337 @multitable @columnfractions .15 .70
5338 @item @var{a} @tab intent(inout)  An array descriptor with the data to be
5339 broadcasted (on @var{source_image}) or to be received (other images).
5340 @item @var{source_image} @tab intent(in)  The ID of the image from which the
5341 data should be broadcasted.
5342 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5343 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5344 an error message; may be NULL.
5345 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg.
5346 @end multitable
5347 @end table
5351 @node _gfortran_caf_co_max
5352 @subsection @code{_gfortran_caf_co_max} --- Collective maximum reduction
5353 @cindex Coarray, _gfortran_caf_co_max
5355 @table @asis
5356 @item @emph{Description}:
5357 Calculates for each array element of the variable @var{a} the maximum
5358 value for that element in the current team; if @var{result_image} has the
5359 value 0, the result shall be stored on all images, otherwise, only on the
5360 specified image. This function operates on numeric values and character
5361 strings.
5363 @item @emph{Syntax}:
5364 @code{void _gfortran_caf_co_max (gfc_descriptor_t *a, int result_image,
5365 int *stat, char *errmsg, int a_len, int errmsg_len)}
5367 @item @emph{Arguments}:
5368 @multitable @columnfractions .15 .70
5369 @item @var{a} @tab intent(inout)  An array descriptor for the data to be
5370 processed.  On the destination image(s) the result overwrites the old content.
5371 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5372 reduced value should be copied to; if zero, it has to be copied to all images.
5373 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5374 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5375 an error message; may be NULL.
5376 @item @var{a_len} @tab intent(in)  the string length of argument @var{a}
5377 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5378 @end multitable
5380 @item @emph{NOTES}
5381 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5382 all images except of the specified one become undefined; hence, the library may
5383 make use of this.
5384 @end table
5388 @node _gfortran_caf_co_min
5389 @subsection @code{_gfortran_caf_co_min} --- Collective minimum reduction
5390 @cindex Coarray, _gfortran_caf_co_min
5392 @table @asis
5393 @item @emph{Description}:
5394 Calculates for each array element of the variable @var{a} the minimum
5395 value for that element in the current team; if @var{result_image} has the
5396 value 0, the result shall be stored on all images, otherwise, only on the
5397 specified image. This function operates on numeric values and character
5398 strings.
5400 @item @emph{Syntax}:
5401 @code{void _gfortran_caf_co_min (gfc_descriptor_t *a, int result_image,
5402 int *stat, char *errmsg, int a_len, int errmsg_len)}
5404 @item @emph{Arguments}:
5405 @multitable @columnfractions .15 .70
5406 @item @var{a} @tab intent(inout)  An array descriptor for the data to be
5407 processed.  On the destination image(s) the result overwrites the old content.
5408 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5409 reduced value should be copied to; if zero, it has to be copied to all images.
5410 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5411 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5412 an error message; may be NULL.
5413 @item @var{a_len} @tab intent(in)  the string length of argument @var{a}
5414 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5415 @end multitable
5417 @item @emph{NOTES}
5418 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5419 all images except of the specified one become undefined; hence, the library may
5420 make use of this.
5421 @end table
5425 @node _gfortran_caf_co_sum
5426 @subsection @code{_gfortran_caf_co_sum} --- Collective summing reduction
5427 @cindex Coarray, _gfortran_caf_co_sum
5429 @table @asis
5430 @item @emph{Description}:
5431 Calculates for each array element of the variable @var{a} the sum of all
5432 values for that element in the current team; if @var{result_image} has the
5433 value 0, the result shall be stored on all images, otherwise, only on the
5434 specified image.  This function operates on numeric values only.
5436 @item @emph{Syntax}:
5437 @code{void _gfortran_caf_co_sum (gfc_descriptor_t *a, int result_image,
5438 int *stat, char *errmsg, int errmsg_len)}
5440 @item @emph{Arguments}:
5441 @multitable @columnfractions .15 .70
5442 @item @var{a} @tab intent(inout)  An array descriptor with the data to be
5443 processed.  On the destination image(s) the result overwrites the old content.
5444 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5445 reduced value should be copied to; if zero, it has to be copied to all images.
5446 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5447 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5448 an error message; may be NULL.
5449 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5450 @end multitable
5452 @item @emph{NOTES}
5453 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5454 all images except of the specified one become undefined; hence, the library may
5455 make use of this.
5456 @end table
5460 @node _gfortran_caf_co_reduce
5461 @subsection @code{_gfortran_caf_co_reduce} --- Generic collective reduction
5462 @cindex Coarray, _gfortran_caf_co_reduce
5464 @table @asis
5465 @item @emph{Description}:
5466 Calculates for each array element of the variable @var{a} the reduction
5467 value for that element in the current team; if @var{result_image} has the
5468 value 0, the result shall be stored on all images, otherwise, only on the
5469 specified image.  The @var{opr} is a pure function doing a mathematically
5470 commutative and associative operation.
5472 The @var{opr_flags} denote the following; the values are bitwise ored.
5473 @code{GFC_CAF_BYREF} (1) if the result should be returned
5474 by reference; @code{GFC_CAF_HIDDENLEN} (2) whether the result and argument
5475 string lengths shall be specified as hidden arguments;
5476 @code{GFC_CAF_ARG_VALUE} (4) whether the arguments shall be passed by value,
5477 @code{GFC_CAF_ARG_DESC} (8) whether the arguments shall be passed by descriptor.
5480 @item @emph{Syntax}:
5481 @code{void _gfortran_caf_co_reduce (gfc_descriptor_t *a,
5482 void * (*opr) (void *, void *), int opr_flags, int result_image,
5483 int *stat, char *errmsg, int a_len, int errmsg_len)}
5485 @item @emph{Arguments}:
5486 @multitable @columnfractions .15 .70
5487 @item @var{a} @tab intent(inout)  An array descriptor with the data to be
5488 processed.  On the destination image(s) the result overwrites the old content.
5489 @item @var{opr} @tab intent(in)  Function pointer to the reduction function
5490 @item @var{opr_flags} @tab intent(in)  Flags regarding the reduction function
5491 @item @var{result_image} @tab intent(in)  The ID of the image to which the
5492 reduced value should be copied to; if zero, it has to be copied to all images.
5493 @item @var{stat} @tab intent(out)  Stores the status STAT= and may be NULL.
5494 @item @var{errmsg} @tab intent(out)  When an error occurs, this will be set to
5495 an error message; may be NULL.
5496 @item @var{a_len} @tab intent(in)  the string length of argument @var{a}
5497 @item @var{errmsg_len} @tab intent(in)  the buffer size of errmsg
5498 @end multitable
5500 @item @emph{NOTES}
5501 If @var{result_image} is nonzero, the data in the array descriptor @var{a} on
5502 all images except of the specified one become undefined; hence, the library may
5503 make use of this.
5505 For character arguments, the result is passed as first argument, followed
5506 by the result string length, next come the two string arguments, followed
5507 by the two hidden string length arguments.  With C binding, there are no hidden
5508 arguments and by-reference passing and either only a single character is passed
5509 or an array descriptor.
5510 @end table
5513 @c Intrinsic Procedures
5514 @c ---------------------------------------------------------------------
5516 @include intrinsic.texi
5519 @tex
5520 \blankpart
5521 @end tex
5523 @c ---------------------------------------------------------------------
5524 @c Contributing
5525 @c ---------------------------------------------------------------------
5527 @node Contributing
5528 @unnumbered Contributing
5529 @cindex Contributing
5531 Free software is only possible if people contribute to efforts
5532 to create it.
5533 We're always in need of more people helping out with ideas
5534 and comments, writing documentation and contributing code.
5536 If you want to contribute to GNU Fortran,
5537 have a look at the long lists of projects you can take on.
5538 Some of these projects are small,
5539 some of them are large;
5540 some are completely orthogonal to the rest of what is
5541 happening on GNU Fortran,
5542 but others are ``mainstream'' projects in need of enthusiastic hackers.
5543 All of these projects are important!
5544 We will eventually get around to the things here,
5545 but they are also things doable by someone who is willing and able.
5547 @menu
5548 * Contributors::
5549 * Projects::
5550 * Proposed Extensions::
5551 @end menu
5554 @node Contributors
5555 @section Contributors to GNU Fortran
5556 @cindex Contributors
5557 @cindex Credits
5558 @cindex Authors
5560 Most of the parser was hand-crafted by @emph{Andy Vaught}, who is
5561 also the initiator of the whole project.  Thanks Andy!
5562 Most of the interface with GCC was written by @emph{Paul Brook}.
5564 The following individuals have contributed code and/or
5565 ideas and significant help to the GNU Fortran project
5566 (in alphabetical order):
5568 @itemize @minus
5569 @item Janne Blomqvist
5570 @item Steven Bosscher
5571 @item Paul Brook
5572 @item Tobias Burnus
5573 @item Fran@,{c}ois-Xavier Coudert
5574 @item Bud Davis
5575 @item Jerry DeLisle
5576 @item Erik Edelmann
5577 @item Bernhard Fischer
5578 @item Daniel Franke
5579 @item Richard Guenther
5580 @item Richard Henderson
5581 @item Katherine Holcomb
5582 @item Jakub Jelinek
5583 @item Niels Kristian Bech Jensen
5584 @item Steven Johnson
5585 @item Steven G. Kargl
5586 @item Thomas Koenig
5587 @item Asher Langton
5588 @item H. J. Lu
5589 @item Toon Moene
5590 @item Brooks Moses
5591 @item Andrew Pinski
5592 @item Tim Prince
5593 @item Christopher D. Rickett
5594 @item Richard Sandiford
5595 @item Tobias Schl@"uter
5596 @item Roger Sayle
5597 @item Paul Thomas
5598 @item Andy Vaught
5599 @item Feng Wang
5600 @item Janus Weil
5601 @item Daniel Kraft
5602 @end itemize
5604 The following people have contributed bug reports,
5605 smaller or larger patches,
5606 and much needed feedback and encouragement for the
5607 GNU Fortran project: 
5609 @itemize @minus
5610 @item Bill Clodius
5611 @item Dominique d'Humi@`eres
5612 @item Kate Hedstrom
5613 @item Erik Schnetter
5614 @item Joost VandeVondele
5615 @end itemize
5617 Many other individuals have helped debug,
5618 test and improve the GNU Fortran compiler over the past few years,
5619 and we welcome you to do the same!
5620 If you already have done so,
5621 and you would like to see your name listed in the
5622 list above, please contact us.
5625 @node Projects
5626 @section Projects
5628 @table @emph
5630 @item Help build the test suite
5631 Solicit more code for donation to the test suite: the more extensive the
5632 testsuite, the smaller the risk of breaking things in the future! We can
5633 keep code private on request.
5635 @item Bug hunting/squishing
5636 Find bugs and write more test cases! Test cases are especially very
5637 welcome, because it allows us to concentrate on fixing bugs instead of
5638 isolating them.  Going through the bugzilla database at
5639 @url{https://gcc.gnu.org/@/bugzilla/} to reduce testcases posted there and
5640 add more information (for example, for which version does the testcase
5641 work, for which versions does it fail?) is also very helpful.
5643 @end table
5646 @node Proposed Extensions
5647 @section Proposed Extensions
5649 Here's a list of proposed extensions for the GNU Fortran compiler, in no particular
5650 order.  Most of these are necessary to be fully compatible with
5651 existing Fortran compilers, but they are not part of the official
5652 J3 Fortran 95 standard.
5654 @subsection Compiler extensions:
5655 @itemize @bullet
5656 @item
5657 User-specified alignment rules for structures.
5659 @item
5660 Automatically extend single precision constants to double.
5662 @item
5663 Compile code that conserves memory by dynamically allocating common and
5664 module storage either on stack or heap.
5666 @item
5667 Compile flag to generate code for array conformance checking (suggest -CC).
5669 @item
5670 User control of symbol names (underscores, etc).
5672 @item
5673 Compile setting for maximum size of stack frame size before spilling
5674 parts to static or heap.
5676 @item
5677 Flag to force local variables into static space.
5679 @item
5680 Flag to force local variables onto stack.
5681 @end itemize
5684 @subsection Environment Options
5685 @itemize @bullet
5686 @item
5687 Pluggable library modules for random numbers, linear algebra.
5688 LA should use BLAS calling conventions.
5690 @item
5691 Environment variables controlling actions on arithmetic exceptions like
5692 overflow, underflow, precision loss---Generate NaN, abort, default.
5693 action.
5695 @item
5696 Set precision for fp units that support it (i387).
5698 @item
5699 Variable for setting fp rounding mode.
5701 @item
5702 Variable to fill uninitialized variables with a user-defined bit
5703 pattern.
5705 @item
5706 Environment variable controlling filename that is opened for that unit
5707 number.
5709 @item
5710 Environment variable to clear/trash memory being freed.
5712 @item
5713 Environment variable to control tracing of allocations and frees.
5715 @item
5716 Environment variable to display allocated memory at normal program end.
5718 @item
5719 Environment variable for filename for * IO-unit.
5721 @item
5722 Environment variable for temporary file directory.
5724 @item
5725 Environment variable forcing standard output to be line buffered (Unix).
5727 @end itemize
5730 @c ---------------------------------------------------------------------
5731 @c GNU General Public License
5732 @c ---------------------------------------------------------------------
5734 @include gpl_v3.texi
5738 @c ---------------------------------------------------------------------
5739 @c GNU Free Documentation License
5740 @c ---------------------------------------------------------------------
5742 @include fdl.texi
5746 @c ---------------------------------------------------------------------
5747 @c Funding Free Software
5748 @c ---------------------------------------------------------------------
5750 @include funding.texi
5752 @c ---------------------------------------------------------------------
5753 @c Indices
5754 @c ---------------------------------------------------------------------
5756 @node Option Index
5757 @unnumbered Option Index
5758 @command{gfortran}'s command line options are indexed here without any
5759 initial @samp{-} or @samp{--}.  Where an option has both positive and
5760 negative forms (such as -foption and -fno-option), relevant entries in
5761 the manual are indexed under the most appropriate form; it may sometimes
5762 be useful to look up both forms.
5763 @printindex op
5765 @node Keyword Index
5766 @unnumbered Keyword Index
5767 @printindex cp
5769 @bye