Commit Graph

4464 Commits

Author SHA1 Message Date
Peixin-Qiao c207e36025 [flang] Enforce a program not including more than one main program
As Fortran 2018 5.2.2 states, a program shall consist of exactly one
main program. Add this semantic check.

Reviewed By: klausler

Differential Revision: https://reviews.llvm.org/D125186
2022-05-09 10:48:06 +08:00
Eric Schweitz 1bffc75383 Upstream support for POINTER assignment in FORALL.
Reviewed By: vdonaldson, PeteSteinfeld

Differential Revision: https://reviews.llvm.org/D125140
2022-05-06 19:52:47 -07:00
River Riddle a8308020ac [mlir] Remove special case parsing/printing of `func` operations
This was leftover from when the standard dialect was destroyed, and
when FuncOp moved to the func dialect. Now that these transitions
have settled a bit we can drop these.

Most updates were handled using a simple regex: replace `^( *)func` with `$1func.func`

Differential Revision: https://reviews.llvm.org/D124146
2022-05-06 13:36:15 -07:00
Daniil Dudkin 2c27d5b36a [flang] Fix internal error with DATA-statement style initializers
The code below causes flang to crash with an exception.
After fixing the crash flang with an internal error "no symbol found for 'bar'"
This change fixes all the issues.

  program name
    implicit none
    integer, parameter :: bar = 1
    integer foo(bar) /bar*2/
  end program name

Reviewed By: kiranchandramohan, klausler

Differential Revision: https://reviews.llvm.org/D124914
2022-05-06 18:21:34 +03:00
PeixinQiao 2472b6869a [flang] Add one semantic check for masked array assignment
As Fortran 2018 states, in each where-assignment-stmt, the mask-expr and
the variable being defined shall be arrays of the same shape. The
previous check does not consider checking if it is an array.

Reviewed By: klausler

Differential Revision: https://reviews.llvm.org/D125022
2022-05-06 22:19:20 +08:00
PeixinQiao ffc7f9d542 [flang] Support external procedure passed as actual argument with implicit character type
As Fortran 2018 15.5.2.9 point 2, the actual argument and dummy argument
have the same type and type parameters and an external function with
assumed character length may be associated with a dummy argument with
explicit character length. As Fortran 2018 15.5.2.9 point 7, if an
external procedure is used as an actual argument, it can be explicitly
declared to have the EXTERNAL attribute. This supports the external
procedure passed as actual argument with implicit character type, either
explicit character length or assumed character length.

Reviewed By: Jean Perier, klausler

Differential Revision: https://reviews.llvm.org/D124345
2022-05-06 22:14:51 +08:00
PeixinQiao ac0f4c8f36 [flang] Fix AllocaOp/AllocMemOp type conversion
For arrays without a constant interior or arrays of character with
dynamic length arrays, the data types are converted to a pointer to the
element type, so the scale size of the constant extents needs to be
counted. The previous AllocaOp conversion does not consider the arrays
of character with dynamic length arrays, and the previous AllocMemOp
conversion does not consider arrays without a constant interior. This
fixes them and refactors the code so that it can be shared. Also add
the test cases.

Reviewed By: Jean Perier

Differential Revision: https://reviews.llvm.org/D124766
2022-05-06 22:10:13 +08:00
Kiran Chandramohan b85c39dd00 [Flang][OpenMP] Initial lowering of the OpenMP worksharing loop
The OpenMP worksharing loop operation in the dialect is a proper loop
operation and not a container of a loop. So we have to lower the
parse-tree OpenMP loop construct and the do-loop inside the construct
to a omp.wsloop operation and there should not be a fir.do_loop inside
it. This is achieved by skipping fir.do_loop creation and calling genFIR
for the nested evaluations in the lowering of the do construct.

Note: Handling of more clauses, parallel do, storage of loop index variable etc will come in separate patches.

Part of the upstreaming effort to move LLVM Flang from fir-dev branch of
https://github.com/flang-compiler/f18-llvm-project to the LLVM Project.

Reviewed By: peixin

Differential Revision: https://reviews.llvm.org/D125024

Co-authored-by: Sourabh Singh Tomar <SourabhSingh.Tomar@amd.com>
Co-authored-by: Shraiysh Vaishay <Shraiysh.Vaishay@amd.com>
2022-05-06 11:46:02 +00:00
Kiran Chandramohan aa0e167fab [Flang] Lower Unstructured do loops
The FIR `do_loop` is designed as a structured operation with a single
block inside it. Presence of unstructured constructs like jumps, exits
inside the loop will cause the loop to be marked as unstructured. These
loops are lowered using the `control-flow` dialect branch operations.

Fortran semantics do not allow the loop variable to be modified inside
the loop. To prevent accidental modification, the iteration of the
loop is modeled by two variables, trip-count and loop-variable.
-> The trip-count and loop-variable are initialized in the pre-header.
The trip-count is set as (end-start+step)/step where end, start and
step have the usual meanings. The loop-variable is initialized to start.
-> The header block contains a conditional branch instruction which
selects between branching to the body of the loop or the exit block
depending on the value of the trip-count.
-> Inside the body, the trip-count is decremented and the loop-variable
incremented by the step value. Finally it branches to the header of the
loop.

Part of the upstreaming effort to move LLVM Flang from fir-dev branch of
https://github.com/flang-compiler/f18-llvm-project to the LLVM Project.

Reviewed By: awarzynski

Differential Revision: https://reviews.llvm.org/D124837

Co-authored-by: Val Donaldson <vdonaldson@nvidia.com>
Co-authored-by: Eric Schweitz <eschweitz@nvidia.com>
Co-authored-by: Jean Perier <jperier@nvidia.com>
Co-authored-by: Peter Klausler <pklausler@nvidia.com>
2022-05-06 09:17:44 +00:00
Andrzej Warzynski a65afce731 [flang][driver] Add support for -save-temps
This patch adds support for `-save-temps` in `flang-new`, Flang's
compiler driver. The semantics of this option are inherited from Clang.

The file extension for temporary Fortran preprocessed files is set to
`i`. This is identical to what Clang uses for C (or C++) preprocessed
files. I have tried researching what other compilers do here, but I
couldn't find any definitive answers. One GFortran thread [1] suggests
that indeed it is not clear what the right approach should be.

Normally, various phases in Clang/Flang are combined. The `-save-temps`
option works by forcing the compiler to run every phase separately. As
there is no integrated assembler driver in Flang, user will have to use
`-save-temps` together with `-fno-integrated-as`. Otherwise, an
invocation to the integrated assembler would be generated generated,
which is going to fail (i.e. something equivalent to `clang -cc1as` from
Clang).

There are no specific plans for implementing an integrated assembler for
Flang for now. One possible solution would be to share it entirely with
Clang.

Note that on Windows you will get the following error when using
`-fno-integrated-as`:
```bash
  flang-new: error: there is no external assembler that can be used on this platform
```
Unfortunately, I don't have access to a Windows machine to investigate
this. Instead, I marked the tests in this patch as unsupported on
Windows.

[1] https://gcc.gnu.org/bugzilla//show_bug.cgi?id=81615

Differential Revision: https://reviews.llvm.org/D124669
2022-05-06 08:41:29 +00:00
Diana Picus f1d4cef852 [flang] Add ExternalNameConversionPass to pass pipeline
This seems to be the consensus in
https://github.com/flang-compiler/f18-llvm-project/issues/1316

The patch adds ExternalNameConversion to the default FIR CodeGen pass
pipeline, right before the FIRtoLLVM pass. It also adds a flag to
optionally disable it, and sets it in `tco`. In other words, `flang-new`
and `flang-new -fc1` will both run the pass by default, whereas `tco`
will not, so none of the tests need to be updated.

Differential Revision: https://reviews.llvm.org/D121171
2022-05-06 07:50:43 +00:00
Peter Steinfeld ebe24a2a31 [flang] Change "unsupported" messages in the runtime to "not yet implemented"
If a programmer is able to compile and link a program that contains types that
are not yet supported by the runtime, it must be because they're not yet
implemented.

This change will make it easier to find unimplemented code in tests.

Differential Revision: https://reviews.llvm.org/D125046
2022-05-05 15:20:01 -07:00
River Riddle 6609c1cc59 [mlir] Add a better error message when failing to parse an attribute
The fallback attribute parse path is parsing a Type attribute, but this results
in a really unintuitive error message: `expected non-function type`, which
doesn't really hint at tall that we were trying to parse an attribute. This
commit fixes this by trying to optionally parse a type, and on failure
emitting an error that we were expecting an attribute.

Differential Revision: https://reviews.llvm.org/D124870
2022-05-05 15:06:11 -07:00
Andrzej Warzynski c12ef70d2b [flang][driver] Add missing parentheses in an assert
The assert in https://reviews.llvm.org/D124665 was missing parentheses,
which triggered a warning in GCC (verified with GCC 11). As `-Werror` is
on by default in FLang, that triggered build errors, see e.g. [1].

The fix is rather straightforward, so I am sending this without a
review.

[1] https://lab.llvm.org/buildbot/#/builders/160/builds/7016

Differential Revision: https://reviews.llvm.org/D125027
2022-05-05 18:02:30 +00:00
Andrzej Warzynski bb0aa574e7 [flang] Fix triple in a couple of driver tests
In https://reviews.llvm.org/D124667, I added tests that check the
generated assembly. I verified the assembly on AArch64 and X86_64, but
the PPC Flang buildbot [1] started failing (i.e. the assembly was not
generic enough).

In order to fix this, I'm changing these tests to be only run on
AAarch64 - that's the architecture that most of public Flang buildbots
use.

I'm hoping that this is straightforward enough and am merging it without
a review.

[1] https://lab.llvm.org/buildbot/#/builders/21/builds/40256
2022-05-05 16:44:12 +00:00
Andrzej Warzynski b9f3b7f89a [flang][driver] Add support for consuming LLVM IR/BC files
This change makes sure that Flang's driver recognises LLVM IR and BC as
supported file formats. To this end, `isFortran` is extended and renamed
as `isSupportedByFlang` (the latter better reflects the new
functionality).

New tests are added to verify that the target triple is correctly
overridden by the frontend driver's default value or the value specified
with `-triple`. Strictly speaking, this is not a functionality that's
new in this patch (it was added in D124664). This patch simply enables
us to write such tests and hence I'm including them here.

Differential Revision: https://reviews.llvm.org/D124667
2022-05-05 15:11:50 +00:00
Peter Steinfeld d134442200 [flang][nfc] Use a message class for "not yet implemented" messages
Following a previous suggestion from Peter Klausler.

Differential Revision: https://reviews.llvm.org/D124972
2022-05-05 07:12:22 -07:00
Andrzej Warzynski bb177edc44 [flang][driver] Re-organise the code-gen actions (nfc)
All frontend actions that generate code  (MLIR, LLVM IR/BC,
Assembly/Object Code) are re-factored as essentially one action,
`CodeGenAction`, with minor specialisations. To facilate all this,
`CodeGenAction` is extended to hold `TargetMachine` and backend action
type (MLIR vs LLVM IR vs LLVM BC vs Assembly vs Object Code).

`CodeGenAction` is no longer a pure abstract class and the
corresponding `ExecuteAction` is implemented so that it covers all use
cases. All this allows a much better code re-use.

Key functionality is extracted into some helpful hooks:
  * `SetUpTargetMachine`
  * `GetOutputStream`
  * `EmitObjectCodeHelper`
  * `EmitBCHelper`
I hope that this clarifies the overall structure. I suspect that we may
need to revisit this again as the functionality grows in complexity.

Differential Revision: https://reviews.llvm.org/D124665
2022-05-05 14:05:06 +00:00
Jean Perier b910cf986a [flang] use 1-based dim in transformational runtime error msg
Flang transformational runtime was previously reporting conformity
issues in a zero based fashion to describe which dimension is non
conformant. This may confuse Fortran user, especially when the message
is about a dimension other than the first one.

Differential Revision: https://reviews.llvm.org/D124941
2022-05-05 10:33:14 +02:00
Andrzej Warzynski 02fb5b771d [flang][driver] Define the default frontend driver triple
*SUMMARY*
Currently, the frontend driver assumes that a target triple is either:
  * provided by the frontend itself (e.g. when lowering and generating
    code),
  * specified through the `-triple/-target` command line flags.

If `-triple/-target` is not used, the frontend will simply use the host
triple.

This is going to be insufficient when e.g. consuming an LLVM IR file
that has no triple specified (reading LLVM files is WIP, see D124667).
We shouldn't require the triple to be specified via the command line in
such situation. Instead, the frontend driver should contain a good
default, e.g.  the host triple.

This patch updates Flang's `CompilerInvocation` to do just that, i.e.
defines its default target triple. Similarly to Clang:
 * the default `CompilerInvocation` triple is set as the host triple,
 * the value specified with `-triple` takes precedence over the frontend
   driver default and the current module triple,
 * the frontend driver default takes precedence over the module triple.

*TESTS*
This change requires 2 unit tests to be updated. That's because relevant
frontend actions are updated to assume that there's always a valid
triple available in the current `CompilerInvocation`. This update is
required because the unit tests bypass the regular `CompilerInvocation`
set-up (in particular, they don't call
`CompilerInvocation::CreateFromArgs`). I've also taken the liberty to
disable the pre-precossor formatting in the affected unit tests as well
(it is not required).

No new tests are added. As `flang-new -fc1` does not support consuming
LLVM IR files just yet, it is not possible to compile an LLVM IR file
without a triple. More specifically, atm all LLVM IR files are generated
and stored internally and the driver makes sure that these contain a
valid target triple. This is about to change in D124667 (which adds
support for reading LLVM IR/BC files) and that's where tests for
exercising the default frontend driver triple will be added.

*WHAT DOES CLANG DO?*
For reference, the default target triple for Clang's
`CompilerInvocation` is set through option marshalling infra [1] in
Options.td. Please check the definition of the `-triple` flag:
```
def triple : Separate<["-"], "triple">,
  HelpText<"Specify target triple (e.g. i686-apple-darwin9)">,
  MarshallingInfoString<TargetOpts<"Triple">, "llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple())">,
  AlwaysEmit, Normalizer<"normalizeTriple">;
```
Ideally, we should re-use the marshalling infra in Flang.

[1] https://clang.llvm.org/docs/InternalsManual.html#option-marshalling-infrastructure

Differential Revision: https://reviews.llvm.org/D124664
2022-05-04 12:01:53 +00:00
Daniil Dudkin 8867e83d00 [flang] Fix ICE for passing a label for non alternate return arguments
When we pass an alternate return specifier to a regular (not an asterisk)
dummy argument, flang would throw an internal compiler error of
derefencing a null pointer.
To avoid the ICE, a check was added.

Reviewed By: kiranchandramohan

Differential Revision: https://reviews.llvm.org/D123947
2022-05-04 12:32:33 +03:00
Emil Kieri 1dd8da2d7c [flang] Fix semantics check for RETURN statement
The RETURN statement is allowed in functions and subroutines, but not
in main programs. It is however a common extension, which we also
implement, to allow RETURN from main programs -- we only issue a
portability warning when -pedantic or -std=f2018 are set.

This patch fixes false positives for this portability warning, where it
was triggered also when RETURN was present in functions or subroutines.

Fixexs #55080

Reviewed By: PeteSteinfeld

Differential Revision: https://reviews.llvm.org/D124732
2022-05-02 22:04:58 +02:00
Raghu Maddhipatla c685f82126 [mlir][OpenMP] Add omp.cancel and omp.cancellationpoint.
Reviewed By: kiranchandramohan, peixin, shraiysh

Differential Revision: https://reviews.llvm.org/D123828
2022-05-02 12:23:38 -05:00
Shraiysh Vaishay a60fda59dc [mlir][OpenMP] Restrict types for omp.parallel args
This patch restricts the value of `if` clause expression to an I1 value.
It also restricts the value of `num_threads` clause expression to an I32
value.

Reviewed By: kiranchandramohan

Differential Revision: https://reviews.llvm.org/D124142
2022-05-02 14:17:34 +05:30
Shraiysh Vaishay e6295c645f [flang] Added tests for taskwait and taskyield translation
Reviewed By: kiranchandramohan

Differential Revision: https://reviews.llvm.org/D124229

Co-authored-by: Sourabh Singh Tomar <SourabhSingh.Tomar@amd.com>
2022-05-02 10:48:03 +05:30
PeixinQiao 303ecc42d4 [flang] Add one semantic check for implicit interface
As Fortran 2018 C1533, a nonintrinsic elemental procedure shall not be
used as an actual argument. The semantic check for implicit iterface is
missed.

Reviewed By: klausler

Differential Revision: https://reviews.llvm.org/D124379
2022-05-01 18:40:17 +08:00
Chris Lattner d85eb4e2d6 [AsmParser] Introduce a new "Argument" abstraction + supporting logic
MLIR has a common pattern for "arguments" that uses syntax
like `%x : i32 {attrs} loc("sourceloc")` which is implemented
in adhoc ways throughout the codebase.  The approach this uses
is verbose (because it is implemented with parallel arrays) and
inconsistent (e.g. lots of things drop source location info).

Solve this by introducing OpAsmParser::Argument and make addRegion
(which sets up BlockArguments for the region) take it.  Convert the
world to propagating this down.  This means that we correctly
capture and propagate source location information in a lot more
cases (e.g. see the affine.for testcase example), and it also
simplifies much code.

Differential Revision: https://reviews.llvm.org/D124649
2022-04-29 12:19:34 -07:00
AlexisPerry 68ee5ad008 [flang] Update Google Doc link for Flang Biweekly Sync call notes
Notes from the Flang Biweekly Sync calls have been merged into the same document as the notes from the Flang Technical calls. This patch updates the link in the GettingInvolved document to point to the new location.

Reviewed By: jdoerfert

Differential Revision: https://reviews.llvm.org/D124689
2022-04-29 12:35:01 -06:00
Peter Klausler 5a7936401c [flang] Fix build bot problem
A recent change is eliciting a valid warning from the out-of-tree
flang build bot; fix by using a reference in a range-based for().

Differential Revision: https://reviews.llvm.org/D124682
2022-04-29 11:13:19 -07:00
Jean Perier 2c8cb9acb5 [flang] Handle common block with different sizes in same file
Semantics is not preventing a named common block to appear with
different size in a same file (named common block should always have
the same storage size (see Fortran 2018 8.10.2.5), but it is a common
extension to accept different sizes).

Lowering was not coping with this well, since it just use the first
common block appearance, starting with BLOCK DATAs to define common
blocks (this also was an issue with the blank common block, which can
legally appear with different size in different scoping units).

Semantics is also not preventing named common from being initialized
outside of a BLOCK DATA, and lowering was dealing badly with this,
since it only gave an initial value to common blocks Globals if the
first common block appearance, starting with BLOCK DATAs had an initial
value.

Semantics is also allowing blank common to be initialized, while
lowering was assuming this would never happen, and was never creating
an initial value for it.

Lastly, semantics was not complaining if a COMMON block was initialized
in several scoping unit in a same file, while lowering can only generate
one of these initial value.

To fix this, add a structure to keep track of COMMON block properties
(biggest size, and initial value if any) at the Program level. Once the
size of a common block appearance is know, the common block appearance
is checked against this information. It allows semantics to emit an error
in case of multiple initialization in different scopes of a same common
block, and to warn in case named common blocks appears with different
sizes. Lastly, this allows lowering to use the Program level info about
common blocks to emit the right GlobalOp for a Common Block, regardless
of the COMMON Block appearances order: It emits a GlobalOp with the
biggest size, whose lowest bytes are initialized with the initial value
if any is given in a scope where the common block appears.

Lowering is updated to go emit the common blocks before anything else so
that the related GlobalOps are available when lowering the scopes where
common block appear. It is also updated to not assume that blank common
are never initialized.

Differential Revision: https://reviews.llvm.org/D124622
2022-04-29 14:52:47 +02:00
Peter Klausler 53f775bbc0 [flang][runtime] Support B/O/Z editing of CHARACTER
This is a common extension, though semantics differ across
compilers.  I've chosen to interpret the CHARACTER data
as if it were an arbitrary-precision integer value and
format or read it as such.  This matches Intel's compilers
and nvfortran.  (GNU Fortran can't handle lengths > 1 and XLF
seems to get the enddianness wrong.)

This patch generalizes the previous implementations of
B/O/Z input and output so that they'll work for arbitrary data
in memory, and then uses them for all B/O/Z input/output,
including (now) CHARACTER.

Differential Revision: https://reviews.llvm.org/D124547
2022-04-28 12:44:31 -07:00
Chris Lattner 5dedf911de [AsmParser] Rework logic around "region argument parsing"
The asm parser had a notional distinction between parsing an
operand (like "%foo" or "%4#3") and parsing a region argument
(which isn't supposed to allow a result number like #3).

Unfortunately the implementation has two problems:

1) It didn't actually check for the result number and reject
   it.  parseRegionArgument and parseOperand were identical.
2) It had a lot of machinery built up around it that paralleled
   operand parsing.  This also was functionally identical, but
   also had some subtle differences (e.g. the parseOptional
   stuff had a different result type).

I thought about just removing all of this, but decided that the
missing error checking was important, so I reimplemented it with
a `allowResultNumber` flag on parseOperand.  This keeps the
codepaths unified and adds the missing error checks.

Differential Revision: https://reviews.llvm.org/D124470
2022-04-28 11:12:44 -07:00
Peter Klausler 36771bbad1 [flang][runtime] Correct emission & reading of unterminated final records
When the last operation on a foramtted sequential or stream file (prior
to an implied or explicit ENDFILE) is a non-advancing WRITE, ensure
that any partial record data is emitted to the file without a line
terminator.  Further, when that last record is read with a non-advancing
READ, ensure that it won't raise an end-of-record condition after its
data, but instead will signal an end-of-file.

Differential Revision: https://reviews.llvm.org/D124546
2022-04-28 09:22:07 -07:00
Kiran Chandramohan b5b3e50f65 [Flang] Initial lowering of the Fortran Do loop
This patch adds code to lower simple Fortran Do loops with loop control.
Lowering is performed by the the `genFIR` function when called with a
`Fortran::parser::DoConstruct`. `genFIR` function calls `genFIRIncrementLoopBegin`
then calls functions to lower the body of the loop and finally calls
the function `genFIRIncrementLoopEnd`. `genFIRIncrementLoopBegin` is
responsible for creating the FIR `do_loop` as well as storing the value of
the loop index to the loop variable. `genFIRIncrementLoopEnd` returns
the incremented value of the loop index and also stores the index value
outside the loop. This is important since the loop variable can be used
outside the loop. Information about a loop is collected in a structure
`IncrementLoopInfo`.

Note 1: Future patches will bring in lowering for unstructured,
infinite, while loops
Note 2: This patch is part of upstreaming code from the fir-dev branch of
https://github.com/flang-compiler/f18-llvm-project.

Reviewed By: awarzynski

Differential Revision: https://reviews.llvm.org/D124277

Co-authored-by: Eric Schweitz <eschweitz@nvidia.com>
Co-authored-by: Jean Perier <jperier@nvidia.com>
Co-authored-by: Val Donaldson <vdonaldson@nvidia.com>
Co-authored-by: Peter Klausler <pklausler@nvidia.com>
Co-authored-by: Valentin Clement <clementval@gmail.com>
2022-04-28 13:03:16 +00:00
Andrzej Warzynski dcb2ddd6c9 [flang][driver] Fix spelling (nfc)
Merely making sure that we use consistent spelling.
2022-04-28 10:37:27 +00:00
Mike Kashkarov 35cc2ec4ed [flang] Support FINDLOC/MAXLOC/MINLOC with scalar mask
Previously MASK= elements were accessed in assumption that mask is an array of
input argument rank (and in combination with explicit DIM= argument we had
out-of-bounds access), but for MAXLOC/MINLOC/FINDLOC mask should be be
conformable and could be scalar.

Add new regression tests with scalar mask for verification.

Reviewed By: klausler

Differential Revision: https://reviews.llvm.org/D124408
2022-04-28 18:59:04 +09:00
Mike Kashkarov 92e22c97e9 [flang] Fix UBOUND() constant folding for parentheses expr
Similarly to LBOUND((x)) in https://reviews.llvm.org/D123838 - fix UBOUND((x))
folding for constant arrays to return shape instead of recurse scan.

Depends on D123520

Reviewed By: jeanPerier

Differential Revision: https://reviews.llvm.org/D123944
2022-04-28 18:56:54 +09:00
Peixin-Qiao b6b8d34554 [flang] Add lowering stubs for OpenMP/OpenACC declarative constructs
This patch provides the basic infrastructure for lowering declarative
constructs for OpenMP and OpenACC.

This is part of the upstreaming effort from the fir-dev branch in [1].
[1] https://github.com/flang-compiler/f18-llvm-project

Reviewed By: kiranchandramohan, shraiysh, clementval

Differential Revision: https://reviews.llvm.org/D124225
2022-04-28 09:40:30 +08:00
Peter Steinfeld 9df99d8ac2 [flang] Fix MAXLOC/MINLOC when MASK is scalar .FALSE.
When passing a scalar .FALSE. as the MASK argument to MAXLOC, we were getting
bad memory references.  We were falling into the code intended when the MASK
argument was missing.

I fixed this by checking for a scalar MASK with a .FALSE. value and
setting the result to all zeroes in that case.  I also added tests for
MAXLOC and MINLOC with scalar values of .TRUE. and .FALSE. for the MASK
argument.

I also special cased situations where the MASK argument is a scalar with
a .TRUE. value and passed along a nullptr in such cases.

Along the way, I eliminated the unused "chars" argument from the constructor
for ExtremumLocAccumulator.

Differential Revision: https://reviews.llvm.org/D124484
2022-04-27 14:50:00 -07:00
Peter Klausler 84c6dc96ac [flang] Downgrade a fatal error to a warning
A non-CHARACTER expression in a CASE statement is allowed to have
a distinct kind (not type) from the expression in its SELECT CASE.
If a value in a CASE statement is out of range for the SELECT CASE
type, emit a warning, but it should not be a fatal error.

Differential Revision: https://reviews.llvm.org/D124544
2022-04-27 12:31:58 -07:00
Peter Klausler 787ee99d4f [flang] Allow for host association in ConvertTo(Object|Proc)Entity
Name resolution fails with a bogus "is not a variable" error message
when a host-associated object appears in a NAMELIST group.  The root
cause is that ConvertToObjectEntity() returns false for host-associated
objects.  Fix that, and also apply a similar fix to ConvertToProcEntity()
nearby.

Differential Revision: https://reviews.llvm.org/D124541
2022-04-27 12:30:03 -07:00
Mike Kashkarov d8b4ea486a [flang] Fix UBOUND() folding for constant arrays
Similarly to LBOUND in https://reviews.llvm.org/D123237, fix UBOUND() folding
for constant arrays (for both w/ and w/o DIM=): convert
GetConstantArrayLboundHelper into common helper class for both lower/upper
bounds.

Reviewed By: jeanPerier

Differential Revision: https://reviews.llvm.org/D123520
2022-04-28 01:17:47 +09:00
Kiran Chandramohan acd75440c6 [Flang] Lower the FailImage Statement
Lowering of FailImage statement generates a runtime call and the
unreachable operation. The unreachable operation cannot terminate
a structured operation like the IF operation, hence  mark as
unstructured.

Note: This patch is part of upstreaming code from the fir-dev branch of
https://github.com/flang-compiler/f18-llvm-project.

Reviewed By: clementval

Differential Revision: https://reviews.llvm.org/D124520

Co-authored-by: Eric Schweitz <eschweitz@nvidia.com>
2022-04-27 12:20:25 +00:00
Andrzej Warzynski d902dd011c [flang][driver] NFC: Make code more in line with LLVM style
This patch basically implements [1] in ExecuteCompilerInvocation.cpp. It
also:
  * replaces `CreateFrontendBaseAction` with `CreateFrontendAction`
    (only one method is needed ATM, this change removes the extra
    indirection)
  * removes `InvalidAction` from the `ActionKind` enum (I don't think it
    adds much and keeping it would mean adding a new void case in
    `CreateFrontendAction`)
  * sets the default frontend action in FrontendOptions.h to
    `ParseSyntaxOnly` (note that this is still overridden independently
    in `ParseFrontendArg` in CompilerInvocation.cpp)

No new functionality is added, hence no tests.

[1] https://llvm.org/docs/CodingStandards.html#don-t-use-default-labels-in-fully-covered-switches-over-enumerations

Differential Revision: https://reviews.llvm.org/D124245
2022-04-27 09:20:07 +00:00
Eric Schweitz 8dc8e59eba Upstream test for wide character literals.
Reviewed By: vdonaldson

Differential Revision: https://reviews.llvm.org/D124488
2022-04-26 18:25:13 -07:00
Eric Schweitz 44e58509be [NFC] More synching of sources for upstreaming.
Reviewed By: clementval

Differential Revision: https://reviews.llvm.org/D124476
2022-04-26 14:54:43 -07:00
Peter Klausler f4bb211a3b [flang] Fix crash from PDT component init in module file
Semantics now needs to preserve the parse trees from module files,
in case they contain parameterized derived type definitions with
component initializers that may require re-analysis during PDT
instantiation.  Save them in the SemanticsContext.

Differential Revision: https://reviews.llvm.org/D124467
2022-04-26 10:49:05 -07:00
Peter Klausler e1836123a7 [flang] Get ppc64le build bot back up
A recent change assumed that the native C++ "long double" maps to
a Fortran data type; but this turns out to not be true for ppc64le,
which uses "double-double" for "long double".

This is a quick patch to get the ppc64le flang build bot back up.
A better fix that either uses HostTypeExists<> or replaces "long double"
with "ieee128_t" (or some other solution) is expected to follow soon.

Differential Revision: https://reviews.llvm.org/D124423
2022-04-26 09:40:03 -07:00
Eric Schweitz 1f31795cb3 [NFC] Cleanup code to get back in synch for upstreaming.
Differential Revision: https://reviews.llvm.org/D124410
2022-04-25 15:57:04 -07:00
Peter Klausler 2c272a4e8f [flang][runtime] Fix total MAXLOC/MINLOC for non-integer data
A template argument was hard-coded as the Integer type category
rather than properly forwarding the type category of the data for
type-specific instantiations of total (no DIM=) MAXLOC and MINLOC.
This broke total MAXLOC and MINLOC reductions for real and character
data.

Differential Revision: https://reviews.llvm.org/D124303
2022-04-25 12:42:20 -07:00
Peter Klausler f65e76d16d [flang] Add semantic checks for intrinsic function REDUCE()
Support REDUCE's special semantic requirements in intrinsic
procedure semantics.

Differential Revision: https://reviews.llvm.org/D124296
2022-04-25 12:37:53 -07:00
Peter Klausler b8f5cf9d2c [flang] Accept "INFINITY" as real input
Both "INF" and "INFINITY" are standard.

Differential Revision: https://reviews.llvm.org/D124401
2022-04-25 12:12:10 -07:00
Peter Klausler 6bcdde2334 [flang][runtime] Fix KIND=16 real/complex component I/O
Don't treat KIND=16 as 80-bit extended floating-point any more on x86.

Differential Revision: https://reviews.llvm.org/D124400
2022-04-25 11:18:21 -07:00
Peter Klausler 72904a990c [flang] Avoid global name conflict when BIND(C,NAME=) is used
At the top level of program units in a source file, two subprograms
are allowed to have the same name if at least one of them has a
distinct interoperable binding name.  F18's symbol table requires
(most) symbols in a scope to have distinct names, though.  Solve
by using compiler-created names for the symbols of global scope
subprograms that have interoperable binding names.

Differential Revision: https://reviews.llvm.org/D124295
2022-04-25 09:25:44 -07:00
Peter Klausler 149d3e4365 [flang] Disambiguate F(X)=Y case where F is a function returning a pointer
F(X)=Y may be initially parsed as a statement function definition; an
existing pass will detect statement functions that should be rewritten
into assignment statemets with array element references as their
left-hand side variables.  However, F() may also be a reference to a
function that returns a data pointer, and f18 did not handle this
case correctly.

The right fix is to rewrite the parse tree for F(X)=Y into an assignment
to a function reference result.  The cases that are actually assignments
to array elements -- including all of the cases previously handled --
will have their left-hand sides converted to array element references
later by another existing rewriting step.

Differential Revision: https://reviews.llvm.org/D124299
2022-04-25 09:25:09 -07:00
Andrzej Warzynski 97a32d3e43 [flang][driver] Add support for generating executables
This patch adds 2 missing items required for `flang-new` to be able to
generate executables:

1. The Fortran_main runtime library, which implements the main entry
   point into Fortran's `PROGRAM` in Flang,

2. Extra linker flags to include Fortran runtime libraries (e.g.
   Fortran_main).

Fortran_main is the bridge between object files generated by Flang and
the C runtime that takes care of program set-up at system-level. For
every Fortran `PROGRAM`, Flang generates the `_QQmain` function.
Fortran_main implements the C `main` function that simply calls
`_QQmain`.

Additionally, "<driver-path>/../lib" directory is added to the list of
search directories for libraries. This is where the required runtime
libraries are currently located. Note that this the case for the build
directory. We haven't considered installation directories/targets yet.

With this change, you can generate an executable that will print `hello,
world!` as follows:

```bash
$ cat hello.f95
PROGRAM HELLO
  write(*, *) "hello, world!"
END PROGRAM HELLO
$ flang-new -flang-experimental-exec hello.f95
./a.out
hello, world!
```

NOTE 1: Fortran_main has to be a static library at all times. It invokes
`_QQmain`, which is the main entry point generated by Flang for the
given input file (you can check this with `flang-new -S hello.f95 -o - |
grep "Qmain"`). This means that Fortran_main has an unresolved
dependency at build time. The linker will allow this for a static
library. However, if Fortran_main was a shared object, then the linker
will produce an error: `undefined symbol: `_QQmain`.

NOTE 2: When Fortran runtime libraries are generated as shared libraries
(excluding Fortran_main, which is always static), you will need to
tell the dynamic linker (by e.g. tweaking LD_LIBRARY_PATH) where to look
for them when invoking the executables. For example:
```bash
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:<flang-build-dir>/lib/ ./a.out
```

NOTE 3: This feature is considered experimental and currently guarded
with a flag: `-flang-experimental-exec`.

Differential Revision: https://reviews.llvm.org/D122008

[1] https://github.com/flang-compiler/f18-llvm-project

CREDITS: Fortran_main was originally written by Eric Schweitz, Jean
Perier, Peter Klausler and Steve Scalpone in the fir-dev` branch in [1].

Co-authored-by: Eric Schweitz <eschweitz@nvidia.com>
Co-authored-by: Peter Klausler <pklausler@nvidia.com>
Co-authored-by: Jean Perier <jperier@nvidia.com>
Co-authored-by: Steve Scalpone <sscalpone@nvidia.com
2022-04-25 12:00:23 +00:00
Jean Perier fca52e8218 [flang] fix LBOUND lowering with KIND and no DIM arguments
The lowering code was mistakenly assuming that the second argument
in the signature provided by semantics is the DIM argument. This
caused calls with a KIND argument but no DIM to be lowered as if the
KIND argument was DIM.

Differential Revision: https://reviews.llvm.org/D124243
2022-04-25 09:20:51 +02:00
Valentin Clement (バレンタイン クレメン) 6243b90ead
[flang] Do not create arith.extui with same from/to type
In some case the lowering of `ichar` is generating an `arith.extui` operation
with the same from/to type. This operation do not accept from/to types to be
the same. If the from/to types are identical, we do not generate the extra
operation.

Reviewed By: jeanPerier

Differential Revision: https://reviews.llvm.org/D124107
2022-04-24 20:37:48 +02:00
Eric Schweitz de8a65f787 [NFC] Sync code for upstreaming.
Remove redundant code.

Differential Revision: https://reviews.llvm.org/D124310
2022-04-23 06:10:20 -07:00
River Riddle eda6f907d2 [mlir][NFC] Shift a bunch of dialect includes from the .h to the .cpp
Now that dialect constructors are generated in the .cpp file, we can
drop all of the dependent dialect includes from the .h file.

Differential Revision: https://reviews.llvm.org/D124298
2022-04-23 01:09:29 -07:00
Peter Klausler aac6e25f7d [flang][runtime] Signal record read overrun when PAD='NO'
When PAD='NO' and ADVANCE='YES', we currently signal an input
error when a formatted read tries to go past the end of a record
only when a fixed RECL= is in effect.  Other compilers will signal
an error without RECL= too, and that seems like a precedent we
should follow.

Differential Revision: https://reviews.llvm.org/D124301
2022-04-22 16:52:05 -07:00
Peter Klausler c02abb68cd [flang][runtime] Enforce some limits on kP scale factors
Ew.d and Dw.d output edit descriptors should respect limitations from
the standard on the value of a kP scale factor with respect to the
digit count (d), at least for values of k other than zero.

Differential Revision: https://reviews.llvm.org/D124300
2022-04-22 16:51:36 -07:00
Peter Klausler f1dbf8e4ad [flang][runtime] Fix edge-case FP input bugs
Blanks are allowed in more places than I allowed for, and
"NAN(foobar)" is allowed to have any parenthesis-balanced
characters in parentheses.

Update: Fix up old sanity test, then avoid usage of "limit" when null.

Differential Revision: https://reviews.llvm.org/D124294
2022-04-22 16:12:04 -07:00
Peter Klausler 839f0abdaa [flang][runtime] Accept "." as REAL input
".", possibly followed by an exponent, is a valid REAL input value (meaning zero).

Differential Revision: https://reviews.llvm.org/D124279
2022-04-22 12:38:07 -07:00
Peter Klausler cbbc662900 [flang][runtime] Ignore leading spaces even in BZ mode
When editing numeric input, always skip leading spaces, even if
BZ mode (or BLANK='ZERO') is in effect; otherwise, a sign character
preceded by blanks will not be recognized.

Differential Revision: https://reviews.llvm.org/D124278
2022-04-22 12:27:19 -07:00
Peter Klausler bf8f9b35c1 [flang] Fix regression from generic fix
A recent change that corrected the name resolution of a generic interface
when the same name was visible in scope incorrectly prevented a local
generic from shadowing an outer name that is not a generic, subprogram,
or derived type -- e.g., a simple variable -- leading to an inappropriate
error message.

Differential Revision: https://reviews.llvm.org/D124276
2022-04-22 12:26:44 -07:00
Eric Schweitz 67609cdf09 [NFC] Cosmetic changes to OpenACC.cpp.
Differential Revision: https://reviews.llvm.org/D124272
2022-04-22 10:20:33 -07:00
Andrzej Warzynski 2186a4aea0 [flang] Make the plugin API independent of the driver internals
This patch adds a few new member methods in the `PluginParseTreeAction`
frontend action base class. With these new methods, the plugin API
becomes independent of the driver internals. In particular, plugin
writers no longer require the `CompilerInstance.h` header file to access
various driver data structures (instead, they can use newly added
hooks).

This change is desirable as `CompilerInstance.h` includes various
headers from Clang (both explicitly and implicitly). Some of these
header files are generated at build time (through TableGen) and
including them creates a dependency on some of Clang's build targets.
However, plugins in Flang should not depend on Clang build targets.

Note that plugins might still work fine most of the time, even without
this change and without adding Clang build targets as dependency in
plugin's CMake definition. Indeed, these Clang build targets are often
generated early in the build process. However, that's not guaranteed and
we did notice that on occasions plugins would fail to build.

Differential Revision: https://reviews.llvm.org/D120999
2022-04-22 09:18:04 +00:00
Jean Perier 6c81b4a01e [flang] Fold transformational bessels when host runtime has bessels
Transformational bessel intrinsic functions require the same math runtime
as elemental bessel intrinsics.

Currently elemental bessels could be folded if f18 was linked with pgmath
(cmake -DLIBPGMATH_DIR option). `j0`, `y0`, ... C libm functions were not
used because they are not standard C functions: they are Posix
extensions.

This patch enable:
- Using the Posix bessel host runtime functions when available.
- folding the transformational bessel using the elemental version.

Differential Revision: https://reviews.llvm.org/D124167
2022-04-22 09:37:49 +02:00
Daniil Dudkin 488b9fd103 [flang] Do not ICE on recursive function definition in function result
The following code causes the compiler to ICE in several places due to
lack of support of recursive procedure definitions through the function
result.

  function foo() result(r)
    procedure(foo), pointer :: r
  end function foo
2022-04-21 19:04:17 +09:00
Nimish Mishra 00c511b351 Added lowering support for atomic read and write constructs
This patch adds lowering support for atomic read and write constructs.
Also added is pointer modelling code to allow FIR pointer like types to
be inferred and converted while lowering.

Reviewed By: kiranchandramohan

Differential Revision: https://reviews.llvm.org/D122725

Co-authored-by: Kiran Chandramohan <kiran.chandramohan@arm.com>
2022-04-21 12:19:13 +05:30
Shraiysh Vaishay 88bb2521b0 [mlir][OpenMP] Add checks and tests for hint clause and fix empty hint
This patch handles empty hint value for critical and atomic constructs.

This also adds checks and tests for hint clause on atomic constructs.

Reviewed By: peixin, kiranchandramohan, NimishMishra

Differential Revision: https://reviews.llvm.org/D123186
2022-04-21 07:31:03 +05:30
V Donaldson 7d61a8419b [flang] Semantics limits on kP scale factors
When known at compile time, Ew.d and Dw.d output edit descriptors
should respect limitations from the standard on the value of a
kP scale factor with respect to the digit count (d), at least for
values of k other than zero.
2022-04-20 14:43:21 -07:00
Mike Kashkarov 39ee23ed5a [flang] Set LBOUND() folding for (x) expression as ones
Set LBOUND() constant folding for parentheses expr. as ones

Array bounds should not propagate throught omitted bounds specifications or
temporary variables - fix constant folding in case of Parentheses<T> expression
by explicitly returning array of ones (or scalar in case of DIM=).

Add set of tests for (x) bounds checks (w/ and w/o 'parameter' arrays)

Reviewed By: jeanPerier

Differential Revision: https://reviews.llvm.org/D123838
2022-04-20 20:06:11 +03:00
Mike Kashkarov bd5371e4fc [flang] Fix LBOUND() folding for constant arrays
Previously constant folding uses 'dim' without checks which leads to ICE if we
do not have DIM= parameter. And for inputs without DIM= we need to form an
array of rank size with computed bounds instead of single value.

Add additional PackageConstant function to simplify 'if (dim)' handling since we
need to distinguish between scalar initialization in case of DIM= argument and
rank=1 array.

Also add a few more tests with 'parameter' type to verify folding for constant
arrays.

Reviewed By: jeanPerier

Differential Revision: https://reviews.llvm.org/D123237
2022-04-20 20:04:31 +03:00
Jean Perier 3d63d2111c [flang] Do not pass derived type by descriptor when not needed
A missing "!" in the call interface lowering caused all derived type
arguments without length parameters that require and explicit interface
to be passed via fir.box (runtime descriptor).

This was not the intent: there is no point passing a simple derived type
scalars or explicit shapes by descriptor just because they have an attribute
like TARGET. This would actually be problematic with existing code that is
not always 100% compliant: some code implicitly calls procedures with
TARGET dummy attributes (this is not something a compiler can enforce
if the call and procedure definition are not in the same file).

Add a Scope::IsDerivedTypeWithLengthParameter to avoid passing derived
types with only kind parameters by descriptor. There is no point, the
callee knows about the kind parameter values.

Differential Revision: https://reviews.llvm.org/D123990
2022-04-20 10:00:34 +02:00
River Riddle 58ceae9561 [mlir:NFC] Remove the forward declaration of FuncOp in the mlir namespace
FuncOp has been moved to the `func` namespace for a little over a month, the
using directive can be dropped now.
2022-04-18 12:01:55 -07:00
Peter Klausler b8a929cb2f [flang] Fix regression with recent work on intrinsic/generic interactions
When resolving a procedure reference, do not allow a successful
intrinsic procedure probe result to override an existing
symbol.

Differential Revision: https://reviews.llvm.org/D123905
2022-04-18 11:10:41 -07:00
Peter Klausler cd03e96f00 [flang] Add & use a better visit() (take 2)
Adds flang/include/flang/Common/log2-visit.h, which defines
a Fortran::common::visit() template function that is a drop-in
replacement for std::visit().  Modifies most use sites in
the front-end and runtime to use common::visit().

The C++ standard mandates that std::visit() have O(1) execution
time, which forces implementations to build dispatch tables.
This new common::visit() is O(log2 N) in the number of alternatives
in a variant<>, but that N tends to be small and so this change
produces a fairly significant improvement in compiler build
memory requirements, a 5-10% improvement in compiler build time,
and a small improvement in compiler execution time.

Building with -DFLANG_USE_STD_VISIT causes common::visit()
to be an alias for std::visit().

Calls to common::visit() with multiple variant arguments
are referred to std::visit(), pending further work.

This change is enabled only for GCC builds with GCC >= 9;
an earlier attempt (D122441) ran into bugs in some versions of
clang and was reverted rather than simply disabled; and it is
not well tested with MSVC. In non-GCC and older GCC builds,
common::visit() is simply an alias for std::visit().
2022-04-16 16:00:48 -07:00
Peter Klausler 1fe7a187ae [flang][runtime] Don't emit empty lines for bad writes
When an error occurs in a formatted sequential output statement
and no output was ever emitted, don't emit a blank record.
This matches the error case behavior of other Fortran compilers.

Differential Revision: https://reviews.llvm.org/D123734
2022-04-15 20:32:32 -07:00
Peter Klausler 9f5f2eb2a1 [flang] Accept %KIND type parameter inquiries on %RE,%IM, &c.
The x%KIND inquiry needs to be supported when 'x' is itself
a complex part reference or a type parameter inquiry.

Differential Revision: https://reviews.llvm.org/D123733
2022-04-15 20:22:03 -07:00
Peter Klausler de6e88ef5a [flang] Allow POINTER attribute statement on procedure interfaces
A POINTER attribute statement is allowed to add the POINTER attribute
to a procedure entity that has already been declared, e.g. with an
INTERFACE block.

Differential Revision: https://reviews.llvm.org/D123732
2022-04-15 20:20:56 -07:00
Peter Klausler 847c39838e [flang] Upgrade short actual character arguments to errors
f18 was emitting a warning about short character actual arguments to
subprograms and statement functions; every other compiler considers this
case to be an error.

Differential Revision: https://reviews.llvm.org/D123731
2022-04-15 20:05:04 -07:00
Peter Klausler 64aff3632f [flang][runtime] Fix ENDFILE for formatted stream output
A predicate expression made ENDFILE statements significant
only for sequential files, but it's applicable to formatted
stream output as well.

Differential Revision: https://reviews.llvm.org/D123730
2022-04-15 18:57:29 -07:00
Peter Klausler 9e7eef9989 [flang] Handle parameter-dependent types in PDT initializers
For parameterized derived type component initializers whose
expressions' types depend on parameter values, f18's current
scheme of analyzing the initialization expression once during
name resolution fails.  For example,

  type :: pdt(k)
    integer, kind :: k
    real :: component = real(0.0, kind=k)
  end type

To handle such cases, it is necessary to re-analyze the parse
trees of these initialization expressions once for each distinct
initialization of the type.

This patch adds code to wipe an expression parse tree of its
typed expressions, and update those of its symbol table pointers
that reference type parameters, and then re-analyze that parse
tree to generate the properly typed component initializers.

Differential Revision: https://reviews.llvm.org/D123728
2022-04-15 16:20:41 -07:00
Peter Klausler 7e225423d3 [flang] Finer control over error recovery with GetExpr()
Prior to this patch, the semantics utility GetExpr() will crash
unconditionally if it encounters a typed expression in the parse
tree that has not been set by expression semantics.  This is the
right behavior when called from lowering, by which time it is known
that the program had no fatal user errors, since it signifies a
fatal internal error.  However, prior to lowering, in the statement
semantics checking code, a more nuanced test should be used before
crashing -- specifically, we should not crash in the face of a
missing typed expression when in error recovery mode.

Getting this right requires GetExpr() and its helper class to have
access to the semantics context, so that it can check AnyFatalErrors()
before crashing.  So this patch touches nearly all of its call sites.

Differential Revision: https://reviews.llvm.org/D123873
2022-04-15 14:25:41 -07:00
Peter Klausler ca2be81e34 [flang] Fix Symbol::Rank for ProcEntityDetails
When a procedure pointer or procedure dummy argument has a
defined interface, the rank of the pointer (or dummy) is the
rank of the interface.

Also tweak code discovered in shape analysis when investigating
this problam so that it returns a vector of emptied extents rather
than std::nullopt when the extents are not scope-invariant, so that
the rank can at least be known.

Differential Revision: https://reviews.llvm.org/D123727
2022-04-15 09:54:48 -07:00
Peter Klausler e6873bfbcd [flang][runtime] Don't skip input spaces when they are significant
When formatted input (not list-directed or NAMELIST) is in "BZ" mode,
either because a BZ control edit descriptor appeared in a FORMAT or
BLANK="ZERO" appeared in OPEN or READ, input editing must not skip
over blanks before or within the input field.

Differential Revision: https://reviews.llvm.org/D123725
2022-04-14 21:30:43 -07:00
Peter Klausler 2503f28648 [flang] Accept TYPE(intrinsic type) in declarations only for non-extension type
To avoid clashing with names of user derived types, the redundant
syntax TYPE(intrinsic type spec) must be interpreted as a monomorphic
derived type when "intrinsic type spec" is a single word.  This
affects TYPE(BYTE) and TYPE(DOUBLECOMPLEX), but not TYPE(DOUBLE COMPLEX)
in free form source.

Differential Revision: https://reviews.llvm.org/D123724
2022-04-14 18:19:37 -07:00
Peter Klausler 7c71ce97e7 [flang] Defer NAMELIST group item name resolution
Items in NAMELIST groups might be host-associated implicitly-typed
variables, but name resolution can't know that when the NAMELIST
appears in a specification part and the host's execution part has
not yet been analyzed.  So defer NAMELIST group item name resolution
to the end of the execution part.  This is safe because nothing
else in name resolution depends on whether a variable is in a
NAMELIST group or not.

Differential Revision: https://reviews.llvm.org/D123723
2022-04-14 17:50:03 -07:00
Peter Klausler 625dedc3fe [flang] Allow modification of construct entities
Construct entities from ASSOCIATE, SELECT TYPE, and SELECT RANK
are modifiable if the are associated with modifiable variables
without vector subscripts.  Update WhyNotModifiable() to accept
construct entities that are appropriate.

A need for more general error reporting from one overload of
WhyNotModifiable() caused its result type to change to
std::optional<parser::Message> instead of ::MessageFixedText,
and this change had some consequences that rippled through
call sites.

Some test results that didn't allow for modifiable construct
entities needed to be updated.

Differential Revision: https://reviews.llvm.org/D123722
2022-04-14 16:58:08 -07:00
Peter Klausler 142cbd500b [flang] Fix TYPE/CLASS IS (T(...)) in SELECT TYPE
TYPE IS and CLASS IS guards in SELECT TYPE constructs are
allowed to specify the same type as the type of the selector
but f18's implementation of that predicate required strict
equality of the derived type representations.  We need to
allow for assumed values of LEN type parameters to match
explicit and deferred type parameter values in the selector
and require equality for KIND type parameters.  Implement
DerivedTypeSpec::Match() to perform this more relaxed type
comparison, and use it in check-select-type.cpp.

Differential Revision: https://reviews.llvm.org/D123721
2022-04-14 16:20:37 -07:00
Peter Klausler 95199af4ae [flang] Local generics must not shadow host-associated generics
It is possible for generic interfaces of equivalent (but not necessarily
identical -- operator(.eq.) is equivalent to operator(==)) names to
be declared in a host scope and a nested scope, and the nested declaration
should function as an extension of the host's.

Differential Revision: https://reviews.llvm.org/D123719
2022-04-14 15:43:59 -07:00
Peter Klausler 8065e48218 [flang] Inner INTRINSIC must not shadow host generic
A generic interface (however spelled) can have the same name as
an intrinsic procedure in the same scope.  When an explicit INTRINSIC
attribute statement appears in a nested scope, semantics was
unconditionally declaring a new symbol that hid the generic entirely.
Catch this case and create instead a host association symbol for
the generic that can then be decorated with the INTRINSIC attribute.

Differential Revision: https://reviews.llvm.org/D123718
2022-04-14 15:42:44 -07:00
Peter Klausler a68612a964 [flang][runtime] Preserve effect of positioning in record in non-advancing output
When formatted non-advancing output ends in a control edit descriptor
like nX or Tn or TRn that effectively extends the record, fill any
gap with explicit blanks at the completion of the WRITE.

Differential Revision: https://reviews.llvm.org/D123716
2022-04-14 15:33:15 -07:00
Peter Klausler 724709e09d [flang] Make F0.1 output editing of zero edge case consistent
The statement
  PRINT '(2F0.1)', 0.0, 0.5
should emit consistent ".0 .5" output, not "0.0 .5".

Differential Revision: https://reviews.llvm.org/D123715
2022-04-14 15:31:47 -07:00
Peter Klausler de026aeb8e [flang] Raise FP exceptions from runtime conversion to binary
Formatted READs of REAL should convert the exception flags from
the decimal-to-binary conversion library into real runtime FP
exceptions so that they at least show up in the termination message
of a STOP statement.

Differential Revision: https://reviews.llvm.org/D123714
2022-04-14 14:49:36 -07:00
Peter Klausler eb14135e35 [flang] Correct interaction between generics and intrinsics
Fortran allows a generic interface to have he same name as an
intrinsic procedure.  If the intrinsic is explicitly marked with
the INTRINSIC attribute, restrictions apply (C848) - the generic
must contain only functions or subroutines, depending on the
intrinsic.  Explicit or not, the generic overrides the intrinsic,
but the intrinsic behavior must still be available for calls
whose actual arguments do not match any of the specific procedures.

Semantics was not checking constraint C848, and it didn't allow
an explicit INTRINSIC attribute on a name of a generic interface.

Differential Revision: https://reviews.llvm.org/D123713
2022-04-14 13:56:04 -07:00
V Donaldson 96e45a8958 [flang] Use full result range for clock_gettime implementation of SYSTEM_CLOCK
Update the primary clock_gettime implementation of SYSTEM_CLOCK to use
the full range of values, dependent on the type kind of the requested
result.  Counts/sec and count max for supported kinds become:

 kind          counts/sec             count max

    1                  10                   127
    2                1000                 32767
    4                1000            2147483647
    8          1000000000   9223372036854775807
   16          1000000000   9223372036854775807

The secondary "fallback" implementation is not changed.

Real valued COUNT_RATE arguments are not changed.

The test program below has calls for kinds 1, 2, 4, 8, 16.  Support for
these types varies by compiler.  The code as given can be restricted to
accommodate these variations, with results shown below.

subroutine c
  integer(1) c1, r1, m1
  integer(2) c2, r2, m2
  integer(4) c4, r4, m4
  integer(8) c8, r8, m8
  integer(16) c16, r16, m16

  print*
  print '(a5,3a22)', 'kind', 'counts/sec', 'count max', 'count'
  print*

  call system_clock(c1, r1, m1)
  print '(i5,3i22)', 1, r1, m1, c1

  call system_clock(c2, r2, m2)
  print '(i5,3i22)', 2, r2, m2, c2

  call system_clock(c4, r4, m4)
  print '(i5,3i22)', 4, r4, m4, c4

  call system_clock(c8, r8, m8)
  print '(i5,3i22)', 8, r8, m8, c8

  call system_clock(c16, r16, m16)
  print '(i5,3i22)', 16, r16, m16, c16
end

subroutine k(j)
  j = 0
  do i=1,1000000000
    j = j + i
  enddo
end

program p
  do i=1,1 ! increase loop count to check for (kind=1) wraparound
    call k(j)
    call c
  enddo
end

=== flang output without change (last column counts vary per run) ===

 kind          counts/sec             count max                 count

    1                 -24                   127                    83
    2                1000                   290                   211
    4                1000                   290                   211
    8          1000000000             290448383             211631452
   16          1000000000             290448383             211633853

=== flang output with change (last column counts vary per run) ===

    1                  10                   127                    21
    2                1000                 32767                  2100
    4                1000            2147483647                  2100
    8          1000000000   9223372036854775807            2100183374
   16          1000000000   9223372036854775807            2100185353

Other compilers; kind support varies (last column counts vary per run).
Test and ouput modified to avoid crashes and normalize results.
Some negative values indicate unsupported kinds; others are bugs.

 kind          counts/sec             count max                 count

    1                   0                     0                  -127
    2                   0                     0                -32767
    4                1000            2147483647              69271692
    8          1000000000   9223372036854775807        69271692353290
   16          1000000000   9223372036854775807        69271692354794

=======

    1                  10                   127                     0
    2                1000                 32767                     0
    4             1000000            2147483647                     0
    8            10000000   9223372036854775807                     9

=======

    1                   0                     0                  -127
    2                1000                 32767                  3263
    4               10000            2147483647            1788192630
    8             1000000   9223372036854775807      1649443459263095

=======

    1                 -24                    -1                    36
    2                1000                    -1                -10716
    4                1000            2147483647             176018980
    8                1000   9223372036854775807         1649443460644

=======

    2                 100                 28799                 23080
    4                 100               8639999               4285480
    8                 100               8639999               4285480
   16                 100               8639999               4285480

=======

    1                 -24                    -1                     4
    2                1000                 23551                -26108
    4                1000              86399999              67541508
    8             1000000   9223372036854775807      1649443541508087
2022-04-14 13:01:32 -07:00
Peter Klausler d054959786 [flang] Fix shape analysis of RESHAPE result
Shape analysis of RESHAPE(..., SHAPE=s) should of course return
the SHAPE= actual argument when it is constant; but when it is
not, its length is still known, and thus so is the rank of the
result of RESHAPE(), and shape analysis should at least return
a shape vector of the right length rather than a result that
makes the result appear to be a scalar, which can lead to some
bogus error messages.

Also, while here: rename a private GetShapeHelper::AsShape()
routine so that it can't be confused with the ones in the API
of shape.h.

Differential Revision: https://reviews.llvm.org/D123712
2022-04-14 12:07:48 -07:00