1<!--===- docs/Extensions.md
2
3   Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4   See https://llvm.org/LICENSE.txt for license information.
5   SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
7-->
8
9# Fortran Extensions supported by Flang
10
11```eval_rst
12.. contents::
13   :local:
14```
15
16As a general principle, this compiler will accept by default and
17without complaint many legacy features, extensions to the standard
18language, and features that have been deleted from the standard,
19so long as the recognition of those features would not cause a
20standard-conforming program to be rejected or misinterpreted.
21
22Other non-standard features, which do conflict with the current
23standard specification of the Fortran programming language, are
24accepted if enabled by command-line options.
25
26## Intentional violations of the standard
27
28* Scalar `INTEGER` actual argument expressions (not variables!)
29  are converted to the kinds of scalar `INTEGER` dummy arguments
30  when the interface is explicit and the kinds differ.
31  This conversion allows the results of the intrinsics like
32  `SIZE` that (as mentioned below) may return non-default
33  `INTEGER` results by default to be passed.  A warning is
34  emitted when truncation is possible.  These conversions
35  are not applied in calls to non-intrinsic generic procedures.
36* We are not strict on the contents of `BLOCK DATA` subprograms
37  so long as they contain no executable code, no internal subprograms,
38  and allocate no storage outside a named `COMMON` block.  (C1415)
39* Delimited list-directed (and NAMELIST) character output is required
40  to emit contiguous doubled instances of the delimiter character
41  when it appears in the output value.  When fixed-size records
42  are being emitted, as is the case with internal output, this
43  is not possible when the problematic character falls on the last
44  position of a record.  No two other Fortran compilers do the same
45  thing in this situation so there is no good precedent to follow.
46  Because it seems least wrong, we emit one copy of the delimiter as
47  the last character of the current record and another as the first
48  character of the next record.  (The second-least-wrong alternative
49  might be to flag a runtime error, but that seems harsh since it's
50  not an explicit error in the standard, and the output may not have
51  to be usable later as input anyway.)
52  Consequently, the output is not suitable for use as list-directed or
53  NAMELIST input.  If a later standard were to clarify this case, this
54  behavior will change as needed to conform.
55```
56character(11) :: buffer(3)
57character(10) :: quotes = '""""""""""'
58write(buffer,*,delim="QUOTE") quotes
59print "('>',a10,'<')", buffer
60end
61```
62* The name of the control variable in an implied DO loop in an array
63  constructor or DATA statement has a scope over the value-list only,
64  not the bounds of the implied DO loop.  It is not advisable to use
65  an object of the same name as the index variable in a bounds
66  expression, but it will work, instead of being needlessly undefined.
67* If both the `COUNT=` and the `COUNT_MAX=` optional arguments are
68  present on the same call to the intrinsic subroutine `SYSTEM_CLOCK`,
69  we require that their types have the same integer kind, since the
70  kind of these arguments is used to select the clock rate.
71  In common with some other compilers, the clock is in milliseconds
72  for kinds <= 4 and nanoseconds otherwise where the target system
73  supports these rates.
74
75## Extensions, deletions, and legacy features supported by default
76
77* Tabs in source
78* `<>` as synonym for `.NE.` and `/=`
79* `$` and `@` as legal characters in names
80* Initialization in type declaration statements using `/values/`
81* Kind specification with `*`, e.g. `REAL*4`
82* `DOUBLE COMPLEX`
83* Signed complex literal constants
84* DEC `STRUCTURE`, `RECORD`, `UNION`, and `MAP`
85* Structure field access with `.field`
86* `BYTE` as synonym for `INTEGER(KIND=1)`
87* Quad precision REAL literals with `Q`
88* `X` prefix/suffix as synonym for `Z` on hexadecimal literals
89* `B`, `O`, `Z`, and `X` accepted as suffixes as well as prefixes
90* Triplets allowed in array constructors
91* `%LOC`, `%VAL`, and `%REF`
92* Leading comma allowed before I/O item list
93* Empty parentheses allowed in `PROGRAM P()`
94* Missing parentheses allowed in `FUNCTION F`
95* Cray based `POINTER(p,x)` and `LOC()` intrinsic (with `%LOC()` as
96  an alias)
97* Arithmetic `IF`.  (Which branch should NaN take? Fall through?)
98* `ASSIGN` statement, assigned `GO TO`, and assigned format
99* `PAUSE` statement
100* Hollerith literals and edit descriptors
101* `NAMELIST` allowed in the execution part
102* Omitted colons on type declaration statements with attributes
103* COMPLEX constructor expression, e.g. `(x+y,z)`
104* `+` and `-` before all primary expressions, e.g. `x*-y`
105* `.NOT. .NOT.` accepted
106* `NAME=` as synonym for `FILE=`
107* Data edit descriptors without width or other details
108* `D` lines in fixed form as comments or debug code
109* `CARRIAGECONTROL=` on the OPEN and INQUIRE statements
110* `CONVERT=` on the OPEN and INQUIRE statements
111* `DISPOSE=` on the OPEN and INQUIRE statements
112* Leading semicolons are ignored before any statement that
113  could have a label
114* The character `&` in column 1 in fixed form source is a variant form
115  of continuation line.
116* Character literals as elements of an array constructor without an explicit
117  type specifier need not have the same length; the longest literal determines
118  the length parameter of the implicit type, not the first.
119* Outside a character literal, a comment after a continuation marker (&)
120  need not begin with a comment marker (!).
121* Classic C-style /*comments*/ are skipped, so multi-language header
122  files are easier to write and use.
123* $ and \ edit descriptors are supported in FORMAT to suppress newline
124  output on user prompts.
125* Tabs in format strings (not `FORMAT` statements) are allowed on output.
126* REAL and DOUBLE PRECISION variable and bounds in DO loops
127* Integer literals without explicit kind specifiers that are out of range
128  for the default kind of INTEGER are assumed to have the least larger kind
129  that can hold them, if one exists.
130* BOZ literals can be used as INTEGER values in contexts where the type is
131  unambiguous: the right hand sides of assigments and initializations
132  of INTEGER entities, and as actual arguments to a few intrinsic functions
133  (ACHAR, BTEST, CHAR).  BOZ literals are interpreted as default INTEGER
134  when they appear as the first items of array constructors with no
135  explicit type.  Otherwise, they generally cannot be used if the type would
136  not be known (e.g., `IAND(X'1',X'2')`).
137* BOZ literals can also be used as REAL values in some contexts where the
138  type is unambiguous, such as initializations of REAL parameters.
139* EQUIVALENCE of numeric and character sequences (a ubiquitous extension)
140* Values for whole anonymous parent components in structure constructors
141  (e.g., `EXTENDEDTYPE(PARENTTYPE(1,2,3))` rather than `EXTENDEDTYPE(1,2,3)`
142   or `EXTENDEDTYPE(PARENTTYPE=PARENTTYPE(1,2,3))`).
143* Some intrinsic functions are specified in the standard as requiring the
144  same type and kind for their arguments (viz., ATAN with two arguments,
145  ATAN2, DIM, HYPOT, MAX, MIN, MOD, and MODULO);
146  we allow distinct types to be used, promoting
147  the arguments as if they were operands to an intrinsic `+` operator,
148  and defining the result type accordingly.
149* DOUBLE COMPLEX intrinsics DREAL, DCMPLX, DCONJG, and DIMAG.
150* The DFLOAT intrinsic function.
151* INT_PTR_KIND intrinsic returns the kind of c_intptr_t.
152* Restricted specific conversion intrinsics FLOAT, SNGL, IDINT, IFIX, DREAL,
153  and DCMPLX accept arguments of any kind instead of only the default kind or
154  double precision kind. Their result kinds remain as specified.
155* Specific intrinsics AMAX0, AMAX1, AMIN0, AMIN1, DMAX1, DMIN1, MAX0, MAX1,
156  MIN0, and MIN1 accept more argument types than specified. They are replaced by
157  the related generics followed by conversions to the specified result types.
158* When a scalar CHARACTER actual argument of the same kind is known to
159  have a length shorter than the associated dummy argument, it is extended
160  on the right with blanks, similar to assignment.
161* When a dummy argument is `POINTER` or `ALLOCATABLE` and is `INTENT(IN)`, we
162  relax enforcement of some requirements on actual arguments that must otherwise
163  hold true for definable arguments.
164* Assignment of `LOGICAL` to `INTEGER` and vice versa (but not other types) is
165  allowed.  The values are normalized.
166* An effectively empty source file (no program unit) is accepted and
167  produces an empty relocatable output file.
168* A `RETURN` statement may appear in a main program.
169* DATA statement initialization is allowed for procedure pointers outside
170  structure constructors.
171* Nonstandard intrinsic functions: ISNAN, SIZEOF
172* A forward reference to a default INTEGER scalar dummy argument is
173  permitted to appear in a specification expression, such as an array
174  bound, in a scope with IMPLICIT NONE(TYPE) if the name
175  of the dummy argument would have caused it to be implicitly typed
176  as default INTEGER if IMPLICIT NONE(TYPE) were absent.
177* OPEN(ACCESS='APPEND') is interpreted as OPEN(POSITION='APPEND')
178  to ease porting from Sun Fortran.
179* Intrinsic subroutines EXIT([status]) and ABORT()
180* The definition of simple contiguity in 9.5.4 applies only to arrays;
181  we also treat scalars as being trivially contiguous, so that they
182  can be used in contexts like data targets in pointer assignments
183  with bounds remapping.
184* We support some combinations of specific procedures in generic
185  interfaces that a strict reading of the standard would preclude
186  when their calls must nonetheless be distinguishable.
187  Specifically, `ALLOCATABLE` dummy arguments are distinguishing
188  if an actual argument acceptable to one could not be passed to
189  the other & vice versa because exactly one is polymorphic or
190  exactly one is unlimited polymorphic).
191* External unit 0 is predefined and connected to the standard error output,
192  and defined as `ERROR_UNIT` in the intrinsic `ISO_FORTRAN_ENV` module.
193
194### Extensions supported when enabled by options
195
196* C-style backslash escape sequences in quoted CHARACTER literals
197  (but not Hollerith) [-fbackslash]
198* Logical abbreviations `.T.`, `.F.`, `.N.`, `.A.`, `.O.`, and `.X.`
199  [-flogical-abbreviations]
200* `.XOR.` as a synonym for `.NEQV.` [-fxor-operator]
201* The default `INTEGER` type is required by the standard to occupy
202  the same amount of storage as the default `REAL` type.  Default
203  `REAL` is of course 32-bit IEEE-754 floating-point today.  This legacy
204  rule imposes an artificially small constraint in some cases
205  where Fortran mandates that something have the default `INTEGER`
206  type: specifically, the results of references to the intrinsic functions
207  `SIZE`, `STORAGE_SIZE`,`LBOUND`, `UBOUND`, `SHAPE`, and the location reductions
208  `FINDLOC`, `MAXLOC`, and `MINLOC` in the absence of an explicit
209  `KIND=` actual argument.  We return `INTEGER(KIND=8)` by default in
210  these cases when the `-flarge-sizes` option is enabled.
211  `SIZEOF` and `C_SIZEOF` always return `INTEGER(KIND=8)`.
212* Treat each specification-part like is has `IMPLICIT NONE`
213  [-fimplicit-none-type-always]
214* Ignore occurrences of `IMPLICIT NONE` and `IMPLICIT NONE(TYPE)`
215  [-fimplicit-none-type-never]
216* Old-style `PARAMETER pi=3.14` statement without parentheses
217  [-falternative-parameter-statement]
218
219### Extensions and legacy features deliberately not supported
220
221* `.LG.` as synonym for `.NE.`
222* `REDIMENSION`
223* Allocatable `COMMON`
224* Expressions in formats
225* `ACCEPT` as synonym for `READ *`
226* `TYPE` as synonym for `PRINT`
227* `ARRAY` as synonym for `DIMENSION`
228* `VIRTUAL` as synonym for `DIMENSION`
229* `ENCODE` and `DECODE` as synonyms for internal I/O
230* `IMPLICIT AUTOMATIC`, `IMPLICIT STATIC`
231* Default exponent of zero, e.g. `3.14159E`
232* Characters in defined operators that are neither letters nor digits
233* `B` suffix on unquoted octal constants
234* `Z` prefix on unquoted hexadecimal constants (dangerous)
235* `T` and `F` as abbreviations for `.TRUE.` and `.FALSE.` in DATA (PGI/XLF)
236* Use of host FORMAT labels in internal subprograms (PGI-only feature)
237* ALLOCATE(TYPE(derived)::...) as variant of correct ALLOCATE(derived::...) (PGI only)
238* Defining an explicit interface for a subprogram within itself (PGI only)
239* USE association of a procedure interface within that same procedure's definition
240* NULL() as a structure constructor expression for an ALLOCATABLE component (PGI).
241* Conversion of LOGICAL to INTEGER in expressions.
242* IF (integer expression) THEN ... END IF  (PGI/Intel)
243* Comparsion of LOGICAL with ==/.EQ. rather than .EQV. (also .NEQV.) (PGI/Intel)
244* Procedure pointers in COMMON blocks (PGI/Intel)
245* Underindexing multi-dimensional arrays (e.g., A(1) rather than A(1,1)) (PGI only)
246* Legacy PGI `NCHARACTER` type and `NC` Kanji character literals
247* Using non-integer expressions for array bounds (e.g., REAL A(3.14159)) (PGI/Intel)
248* Mixing INTEGER types as operands to bit intrinsics (e.g., IAND); only two
249  compilers support it, and they disagree on sign extension.
250* Module & program names that conflict with an object inside the unit (PGI only).
251* When the same name is brought into scope via USE association from
252  multiple modules, the name must refer to a generic interface; PGI
253  allows a name to be a procedure from one module and a generic interface
254  from another.
255* Type parameter declarations must come first in a derived type definition;
256  some compilers allow them to follow `PRIVATE`, or be intermixed with the
257  component declarations.
258* Wrong argument types in calls to specific intrinsics that have different names than the
259  related generics. Some accepted exceptions are listed above in the allowed extensions.
260  PGI, Intel, and XLF support this in ways that are not numerically equivalent.
261  PGI converts the arguments while Intel and XLF replace the specific by the related generic.
262
263## Preprocessing behavior
264
265* The preprocessor is always run, whatever the filename extension may be.
266* We respect Fortran comments in macro actual arguments (like GNU, Intel, NAG;
267  unlike PGI and XLF) on the principle that macro calls should be treated
268  like function references.  Fortran's line continuation methods also work.
269
270## Standard features not silently accepted
271
272* Fortran explicitly ignores type declaration statements when they
273  attempt to type the name of a generic intrinsic function (8.2 p3).
274  One can declare `CHARACTER::COS` and still get a real result
275  from `COS(3.14159)`, for example.  f18 will complain when a
276  generic intrinsic function's inferred result type does not
277  match an explicit declaration.  This message is a warning.
278
279## Standard features that might as well not be
280
281* f18 supports designators with constant expressions, properly
282  constrained, as initial data targets for data pointers in
283  initializers of variable and component declarations and in
284  `DATA` statements; e.g., `REAL, POINTER :: P => T(1:10:2)`.
285  This Fortran 2008 feature might as well be viewed like an
286  extension; no other compiler that we've tested can handle
287  it yet.
288
289## Behavior in cases where the standard is ambiguous or indefinite
290
291* When an inner procedure of a subprogram uses the value or an attribute
292  of an undeclared name in a specification expression and that name does
293  not appear in the host, it is not clear in the standard whether that
294  name is an implicitly typed local variable of the inner procedure or a
295  host association with an implicitly typed local variable of the host.
296  For example:
297```
298module module
299 contains
300  subroutine host(j)
301    ! Although "m" never appears in the specification or executable
302    ! parts of this subroutine, both of its contained subroutines
303    ! might be accessing it via host association.
304    integer, intent(in out) :: j
305    call inner1(j)
306    call inner2(j)
307   contains
308    subroutine inner1(n)
309      integer(kind(m)), intent(in) :: n
310      m = n + 1
311    end subroutine
312    subroutine inner2(n)
313      integer(kind(m)), intent(out) :: n
314      n = m + 2
315    end subroutine
316  end subroutine
317end module
318
319program demo
320  use module
321  integer :: k
322  k = 0
323  call host(k)
324  print *, k, " should be 3"
325end
326
327```
328
329  Other Fortran compilers disagree in their interpretations of this example;
330  some seem to treat the references to `m` as if they were host associations
331  to an implicitly typed variable (and print `3`), while others seem to
332  treat them as references to implicitly typed local variabless, and
333  load uninitialized values.
334
335  In f18, we chose to emit an error message for this case since the standard
336  is unclear, the usage is not portable, and the issue can be easily resolved
337  by adding a declaration.
338
339* In subclause 7.5.6.2 of Fortran 2018 the standard defines a partial ordering
340  of the final subroutine calls for finalizable objects, their non-parent
341  components, and then their parent components.
342  (The object is finalized, then the non-parent components of each element,
343  and then the parent component.)
344  Some have argued that the standard permits an implementation
345  to finalize the parent component before finalizing an allocatable component in
346  the context of deallocation, and the next revision of the language may codify
347  this option.
348  In the interest of avoiding needless confusion, this compiler implements what
349  we believe to be the least surprising order of finalization.
350  Specifically: all non-parent components are finalized before
351  the parent, allocatable or not;
352  all finalization takes place before any deallocation;
353  and no object or subobject will be finalized more than once.
354
355* When `RECL=` is set via the `OPEN` statement for a sequential formatted input
356  file, it functions as an effective maximum record length.
357  Longer records, if any, will appear as if they had been truncated to
358  the value of `RECL=`.
359  (Other compilers ignore `RECL=`, signal an error, or apply effective truncation
360  to some forms of input in this situation.)
361  For sequential formatted output, RECL= serves as a limit on record lengths
362  that raises an error when it is exceeded.
363