[PATCH] D67294: Register and parse a simplified version of '#pragma omp declare variant'

2019-09-11 Thread Andrzej Warzynski via Phabricator via cfe-commits
andwar updated this revision to Diff 219673.
andwar marked 6 inline comments as done.
andwar added a comment.

- Removed `declare variant` from Attr.td
- Moved the 'vector-var-id' lookup from ParseOpenMP.cpp to SemaOpenMP.cpp
- Parsing 'vector-var-id' as an expression
- Removed the creation of the attribute in `ActOnOpenMPDeclareVariantDirective`


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D67294/new/

https://reviews.llvm.org/D67294

Files:
  include/clang/Basic/DiagnosticParseKinds.td
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Basic/OpenMPKinds.def
  include/clang/Parse/Parser.h
  include/clang/Sema/Sema.h
  lib/Basic/OpenMPKinds.cpp
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/Parse/ParseOpenMP.cpp
  lib/Sema/SemaOpenMP.cpp
  test/OpenMP/declare_variant_messages.cpp

Index: test/OpenMP/declare_variant_messages.cpp
===
--- /dev/null
+++ test/OpenMP/declare_variant_messages.cpp
@@ -0,0 +1,83 @@
+// RUN: %clang_cc1 -triple=x86_64-pc-win32 -verify -fopenmp -x c++ -std=c++11 -fms-extensions -Wno-pragma-pack %s
+
+// RUN: %clang_cc1 -triple=x86_64-pc-win32 -verify -fopenmp-simd -x c++ -std=c++11 -fms-extensions -Wno-pragma-pack %s
+
+// The dummy vector variant
+void vector_foo();
+
+//=
+// Basic errors
+//=
+// This is (and should be) perfectly fine for the parser, although semantically
+// not valid OpenMP 5.
+#pragma omp declare variant(vector_foo)
+void foo();
+
+// expected-error@+1 {{expected an OpenMP directive}}
+#pragma omp declare
+
+// expected-error@+2 {{'#pragma omp declare variant' can only be applied to functions}}
+#pragma omp declare variant(vector_foo)
+int a;
+// expected-error@+2 {{'#pragma omp declare variant' can only be applied to functions}}
+#pragma omp declare variant (vector_foo)
+#pragma omp threadprivate(a)
+int var;
+#pragma omp threadprivate(var)
+
+// expected-error@+3 {{expected an OpenMP directive}}
+// expected-error@+1 {{function declaration is expected after 'declare variant' directive}}
+#pragma omp declare variant
+#pragma omp declare
+
+// expected-error@+1 {{single declaration is expected after 'declare variant' directive}}
+#pragma omp declare variant(vector_foo)
+int b, c;
+
+//=
+// Syntax/semantic error: everything excluding linear/aligned/uniform
+//=
+// expected-error@+1 {{expected an OpenMP directive}}
+#pragma omp variant
+// expected-error@+1 {{expected '(' after '#pragma omp declare variant'}}
+#pragma omp declare variant
+// expected-warning@+2 {{extra tokens at the end of '#pragma omp declare variant' are ignored}}
+// expected-error@+1 {{expected '(' after '#pragma omp declare variant'}}
+#pragma omp declare variant )
+// expected-error@+1 {{expected unqualified-id representing 'vector-variant-id'}}
+#pragma omp declare variant()
+// expected-error@+1 {{no declaration for 'undeclared_func', only declared functions can be used as }}
+#pragma omp declare variant(undeclared_func)
+// expected-error@+2 {{expected ')'}}
+// expected-note@+1 {{to match this '('}}
+#pragma omp declare variant(vector_foo
+void foo();
+
+//=
+// Templates
+//=
+// expected-error@+1 {{'#pragma omp declare variant' can only be used to decorate instantiated templates}}
+#pragma omp declare variant(vector_foo)
+template 
+void h(C *hp, C *hp2, C *hq, C *lin) {
+  b = 0;
+}
+
+#pragma omp declare variant(vector_foo)
+template <>
+void h(int *hp, int *hp2, int *hq, int *lin) {
+  h((float *)hp, (float *)hp2, (float *)hq, (float *)lin);
+}
+
+//=
+// 'declare variant' embedded in namespaces
+//=
+namespace N {
+  // expected-error@+1 {{function declaration is expected after 'declare variant' directive}}
+  #pragma omp declare variant
+}
+// expected-error@+1 {{function declaration is expected after 'declare variant' directive}}
+#pragma omp declare variant
+// Now verify that the parser recovered fine from the previous error and identifies another one correctly
+// expected-error@+1 {{function declaration is expected after 'declare variant' directive}}
+#pragma omp declare variant
Index: lib/Sema/SemaOpenMP.cpp
===
--- lib/Sema/SemaOpenMP.cpp
+++ lib/Sema/SemaOpenMP.cpp
@@ -3438,6 +3438,7 @@
   case OMPD_declare_reduction:
   case OMPD_declare_mapper:
   case OMPD_declare_simd:
+  case OMPD_declare_variant:
   case OM

[PATCH] D67294: Register and parse a simplified version of '#pragma omp declare variant'

2019-09-11 Thread Andrzej Warzynski via Phabricator via cfe-commits
andwar added a comment.

I've addressed most of the comments except for those related to templates. I'd 
like to clarify as what is the expected behaviour there before proceeding with 
implementation.




Comment at: include/clang/Basic/Attr.td:3220
+private:
+  NamedDecl *VecVarNamedDecl;
+

ABataev wrote:
> This is definitely wrong, especially if we need to handle templates.
What else would you use? Also, we're not handling template-ids as 
'variant-func-id' just yet.



Comment at: lib/Parse/ParseOpenMP.cpp:779-783
+  auto Identinfo = PP.getIdentifierInfo(VectorVariantId.Ident->getName());
+  LookupResult Lookup(Actions, Identinfo, VectorVariantId.Loc,
+  Sema::LookupOrdinaryName);
+  CXXScopeSpec SS;
+  if (!Actions.LookupParsedName(Lookup, getCurScope(), &SS)) {

ABataev wrote:
> 1. All this lookup must be performed in Sema.
> 2. How do you want to handle templates?
> 3. Why just do not parse it as an expression? And rely on existing 
> parsing/sema analysis for expressions.
1. That's fine, let me move it there.

2. TL;DR We're not handling templates yet. 

3. How about switching to `ParseUnqualifiedId` instead? That will still require 
going through `LookupParsedName` though.

Re 2. What the interaction between templates and #pragma(s) should be? The C++ 
standard doesn't specify that, but IMHO mixing '#pragma omp declare variant' 
and templates requires that interaction to be clearly defined. 

I know that OpenMP 5 allows 'variant-func-id' to be a template-id, but I 
couldn't find an example of any attribute that would use C++ template 
parameters. Also, isn't parsing of attributes and templates _orthogonal_ in 
clang (i.e. happening at completely different points during parsing)?

In any case, we felt that support for 'template-id' could come later. How do 
you feel about it?



Comment at: lib/Sema/SemaOpenMP.cpp:4886
 
+Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareVariantDirective(
+DeclGroupPtrTy DG, IdentifierLoc &VectorVariantId, SourceRange SR) {

ABataev wrote:
> In this patch need to implement just basic checks, no need to create 
> attributes, etc. I would suggest to look at the checks for Target 
> Multiversioning attribite (see D40819)
This makes sense, but do you reckon that that should be split into separate 
functions? I was inspired by the implementation of `declare simd`. From what I 
can tell, the only Sema checking for `declare simd` is happening in 
`ActOnOpenMPDeclareVariantDirective`. It feels that doing the same for `declare 
variant` would be good for consistency. To limit this method to Sema checks, I 
will remove the call to `CreateImplicit`.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D67294/new/

https://reviews.llvm.org/D67294



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D67294: Register and parse a simplified version of '#pragma omp declare variant'

2019-09-11 Thread Andrzej Warzynski via Phabricator via cfe-commits
andwar marked 2 inline comments as done.
andwar added inline comments.



Comment at: lib/Parse/ParseOpenMP.cpp:779-783
+  auto Identinfo = PP.getIdentifierInfo(VectorVariantId.Ident->getName());
+  LookupResult Lookup(Actions, Identinfo, VectorVariantId.Loc,
+  Sema::LookupOrdinaryName);
+  CXXScopeSpec SS;
+  if (!Actions.LookupParsedName(Lookup, getCurScope(), &SS)) {

ABataev wrote:
> andwar wrote:
> > ABataev wrote:
> > > 1. All this lookup must be performed in Sema.
> > > 2. How do you want to handle templates?
> > > 3. Why just do not parse it as an expression? And rely on existing 
> > > parsing/sema analysis for expressions.
> > 1. That's fine, let me move it there.
> > 
> > 2. TL;DR We're not handling templates yet. 
> > 
> > 3. How about switching to `ParseUnqualifiedId` instead? That will still 
> > require going through `LookupParsedName` though.
> > 
> > Re 2. What the interaction between templates and #pragma(s) should be? The 
> > C++ standard doesn't specify that, but IMHO mixing '#pragma omp declare 
> > variant' and templates requires that interaction to be clearly defined. 
> > 
> > I know that OpenMP 5 allows 'variant-func-id' to be a template-id, but I 
> > couldn't find an example of any attribute that would use C++ template 
> > parameters. Also, isn't parsing of attributes and templates _orthogonal_ in 
> > clang (i.e. happening at completely different points during parsing)?
> > 
> > In any case, we felt that support for 'template-id' could come later. How 
> > do you feel about it?
> No, don't try to parse function names directly. What about `::fun` format? Or 
> `std::fun`? Your solution does not support it.
> I have basic implementation that handles all these cases. Let me commit it, 
> because we need it to support other context selectors. It is very similar to 
> your solution but handles all the problems. We just don't have time to wait, 
> need to support other context selectors.
That's true - my approach doesn't support `::fun` or `std::fun`. The idea is to 
fill in the gaps as we progress later. 

@ABataev, If you have a more generic implementation  then it makes a lot of 
sense to go with that instead. Please, feel free to re-use this patch if that 
helps.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D67294/new/

https://reviews.llvm.org/D67294



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D61446: Generalize the pass registration mechanism used by Polly to any third-party tool

2019-09-21 Thread Andrzej Warzynski via Phabricator via cfe-commits
andwar added inline comments.



Comment at: llvm/examples/Bye/Bye.cpp:53
+/* New PM Registration */
+
+llvm::PassPluginLibraryInfo getByePluginInfo() {

[nit] Empty line



Comment at: llvm/examples/Bye/CMakeLists.txt:9
+else()
+  target_link_libraries(Bye
+PUBLIC

Are all these libraries required? I tried building on Darwin and for me 
`LLVMSupport`, `LLVMCore` and `LLVMipo` were sufficient.



Comment at: llvm/examples/Bye/CMakeLists.txt:28
+endif()
+

[nit] Empty line


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61446/new/

https://reviews.llvm.org/D61446



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D76929: [AArch64][SVE] Add SVE intrinsic for LD1RQ

2020-04-03 Thread Andrzej Warzynski via Phabricator via cfe-commits
andwar added a comment.

Btw, could you also add some negative tests? (e.g. out-of-range immediate)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D76929/new/

https://reviews.llvm.org/D76929



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D76617: [SveEmitter] Fix encoding/decoding of SVETypeFlags

2020-04-06 Thread Andrzej Warzynski via Phabricator via cfe-commits
andwar added inline comments.



Comment at: clang/utils/TableGen/SveEmitter.cpp:240
+  // Returns the SVETypeFlags for the given memory element type.
+  uint64_t encodeMemoryElementType(unsigned MT) {
+return encodeFlag(MT, "MemEltTypeMask");

Shouldn't `MT` be `uint64_t` instead of `unsigned`?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D76617/new/

https://reviews.llvm.org/D76617



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D76617: [SveEmitter] Fix encoding/decoding of SVETypeFlags

2020-04-06 Thread Andrzej Warzynski via Phabricator via cfe-commits
andwar added a comment.

LGTM

This patch now implements a bit more than the original commit message would 
suggest. Could you please update? Thanks for working on this!


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D76617/new/

https://reviews.llvm.org/D76617



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D76238: [SveEmitter] Implement builtins for contiguous loads/stores

2020-04-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
Andrzej added inline comments.



Comment at: clang/include/clang/Basic/arm_sve.td:186
+def SVLDFF1   : MInst<"svldff1[_{2}]", "dPc", "csilUcUsUiUlhfd", [IsLoad], 
  MemEltTyDefault, "aarch64_sve_ldff1">;
+def SVLDFF1SB : MInst<"svldff1sb_{d}", "dPS", "silUsUiUl",   [IsLoad], 
  MemEltTyInt8,"aarch64_sve_ldff1">;
+def SVLDFF1UB : MInst<"svldff1ub_{d}", "dPW", "silUsUiUl",   [IsLoad, 
IsZExtReturn], MemEltTyInt8,"aarch64_sve_ldff1">;

Tests for `ldff1sb` seem to be missing.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D76238/new/

https://reviews.llvm.org/D76238



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D77735: [SveEmitter] Implement builtins for gathers/scatters

2020-04-21 Thread Andrzej Warzynski via Phabricator via cfe-commits
andwar added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:7458
+llvm_unreachable("Invalid SVETypeFlag!");
+
+  case SVETypeFlags::EltTyInt8:

SjoerdMeijer wrote:
> nit: no need for the newlines here and also below?
IMHO this improves readability, but I agree that that's a matter of personal 
preference :)

I'll keep it as is for the sake of consistency with `getSVEType` below.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:7555
+
+  // From ACLE we always get . This might be incompatible with
+  // the actual type being loaded. Cast accordingly.

SjoerdMeijer wrote:
> nit: can you rephrase this comment a bit I.e. the "From ACLE we always get 
> ..." is a bit confusing I think. You want to say that this is how the ACLE 
> defines this, but the IR looks different. You can also specify which bit is 
> different, because that was not immediately obvious to me. 
> 
Good point, updated!



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:7601
+  llvm::Type *SrcDataTy = getSVEType(TypeFlags);
+  llvm::Type *OverloadedTy = llvm::VectorType::get(
+  SVEBuiltinMemEltTy(TypeFlags), SrcDataTy->getVectorElementCount());

sdesmalen wrote:
> nit: This can use `auto`, which would make OverloadedTy a `llvm::VectorType`
Thanks, good point! I also updated `getSVEType` to return `VectorType` (so I 
can use `auto` for both).



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:7602
+  llvm::Type *OverloadedTy = llvm::VectorType::get(
+  SVEBuiltinMemEltTy(TypeFlags), SrcDataTy->getVectorElementCount());
+

sdesmalen wrote:
> Just be aware that `getVectorElementCount` has been removed from Type in 
> D77278, so you'll need to cast to `VectorType` and use `getElementCount` 
> instead.
> (fyi - in D77596 I've made `getSVEType` actually return a VectorType so that 
> cast wouldn't be needed)
I have done the same ;)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D77735/new/

https://reviews.llvm.org/D77735



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D77735: [SveEmitter] Implement builtins for gathers/scatters

2020-04-22 Thread Andrzej Warzynski via Phabricator via cfe-commits
andwar added a comment.

The buildbot failures are unrelated to this patch, and locally `make check-all` 
worked fine. I'll submit this patch as is.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D77735/new/

https://reviews.llvm.org/D77735



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D73951: [Clang] [Driver]Add logic to search for flang frontend

2020-04-29 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

The suggested flag, `-fortran-fe`, feels quite powerful and I wonder whether 
it's required this early into the development of the Flang driver?

IIUC, this flag would be used to workaround the fact that currently `flang` is 
a bash script and hence can't be used when the driver is in the `flang` mode. 
`-fortran-fe` could be use to redirect the call to `flang-tmp` (the temporary 
flang driver that will eventually replace the bash script with similar name). 
Wouldn't it be less work if we just used `flang-tmp` instead of `flang` here: 
https://github.com/llvm/llvm-project/blob/42a56bf63f699a620a57c34474510d9937ebf715/clang/lib/Driver/ToolChains/Flang.cpp#L72?
 Once the driver is ready to replace the bash script, we could revert the 
change in Flang.cpp (`flang-tmp` -> `flang`).

Are there any other usecases that we should cater for at this point? Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D73951/new/

https://reviews.llvm.org/D73951



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D73951: [Clang] [Driver]Add logic to search for flang frontend

2020-04-30 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

@richard.barton.arm @CarolineConcatto  thank you both for clarification! 
@CarolineConcatto , if you prefer to go ahead with this approach - could you 
please address all the outstanding comments? I've left a few comments that I'd 
like addressed first, but nothing major.

Also, IIUC, the approach that we are taking here is via a _custom_ fortran 
frontend. I'm looking at `ccc_gcc_name` as reference, which I believe stands 
for `custom c compiler`, see:

- link1 

- link2 
- link3 


I couldn't find any other documentation other than ^^^.  Anyway, I think that 
it would be useful to make it clear that this flag points to either  a _custom_ 
frontend (e.g. `cfc_flang_name`), or perhaps _alternative_ frontend (e.g. 
`afc_flang_name`). Currently the name is a bit too generic IMO (i.e. we want to 
make the intention for the flag very clear).

Last minor point - I think that this patch is more about _specfying_ rather 
than _searching_ `flang` frontend. It would be helpful to have this clarified 
in the commit message.

Thanks for working on this! :)




Comment at: clang/test/Driver/flang/clang-driver-2-frontend01.f90:7
+
+! Copy clang to two temporary file
+! t1 is the new frontend name.

1. You make only one copy here :) 

2. In this file `%t` should be sufficient (i.e. you don't need `%t1`).

3. IIUC, you don't need to copy here at all. Instead of using 
`%basename_t.tmp1` below you could use `alternative_fortran_frontend` (or some 
other name). 

I would prefer if we avoided copying in these tests. It's a step that 
complicates the test, yet doesn't add anything in terms of test coverage.



Comment at: clang/test/Driver/flang/clang-driver-2-frontend01.f90:10
+! RUN: cp %clang %t1
+! RUN: %clang --driver-mode=flang -fortran-fe %basename_t.tmp1 -### %s 2>&1 | 
FileCheck --check-prefixes=ALL %s
+

richard.barton.arm wrote:
> CarolineConcatto wrote:
> > richard.barton.arm wrote:
> > > Does %t1 not work again on this line?
> > If I don't create the fake link getProgramPath will only return the name, 
> > not the entire path.
> > t1 here is the path for the frontend.  
> > For instance:
> > clang --driver-mode=flang -fortran-fe %test
> > the frontend name is test, but when running it should print:
> >  /test -fc1
> >  without the link it will only print:
> > test -fc1
> > Like I said before it is more a preference that actually a requisite.
> Understood - thanks.
There's only one run line here, so `--check-prefixes` is not required here. 

Could you please use the default label instead, i.e. `CHECK`?



Comment at: clang/test/Driver/flang/flang-driver-2-frontend01.f90:7-8
+! Copy clang to a temporary file to be the driver name
+! RUN: cp %clang %t1
+! RUN: %t1 --driver-mode=flang -###  %s 2>&1 | FileCheck --check-prefixes=ALL 
%s
+

IIUC, copying is not required here. This could be simplified as:

```
! RUN: %clang --driver-mode=flang -###  %s 2>&1 | FileCheck 
--check-prefixes=ALL %s
```
Also, this scenario is already tested in `flang.90`. I'd rather we didn't add 
this file.



Comment at: clang/test/Driver/flang/flang-driver-2-frontend02.f90:2
+! Check wich name of flang frontend is invoked by the driver
+
+! The flag -fortran-fe is passed by the driver.

This test is very similar to `clang-driver-2-frontend01.f90` - the scenario 
tested here is already covered elsewhere and IMO this file can be removed from 
this patch.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D73951/new/

https://reviews.llvm.org/D73951



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D73951: [Clang] [Driver]Add logic to search for flang frontend

2020-05-04 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: clang/lib/Driver/ToolChains/Flang.cpp:71
   const auto& D = C.getDriver();
-  const std::string &customFortranName = D.getFFCGenericFortranName();
+  const std::string &customFortranName = D.getGenericFortranFE();
   const char *FortranName;

[nit] Could this be `customFlangName` instead? I think that it would better 
reflect the meaning.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D73951/new/

https://reviews.llvm.org/D73951



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D73951: [Clang] [Driver]Add logic to search for flang frontend

2020-05-04 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

@CarolineConcatto thank you for the updates!

- It looks like you accidentally pushed two commits in one patch :) Could you 
please squash and resubmit? (this should clean-up the diff). Ta!
- Perhaps  `CFCGenericFlangName` instead of `GenericFortranFE`? This would 
better correspond to the new flag and be consistent with 
https://github.com/llvm/llvm-project/blob/42a56bf63f699a620a57c34474510d9937ebf715/clang/lib/Driver/ToolChains/Gnu.cpp#L183.

Naming is hard! Otherwise, this is ready to land IMO.




Comment at: clang/include/clang/Driver/Driver.h:222
   /// Name to use when invoking flang.
-  std::string FFCGenericFortranName;
+  std::string GenericFortranFE;
 

`CFCGenericFlangName`?



Comment at: clang/include/clang/Driver/Driver.h:317
   /// Name to use when invoking flang.
-  const std::string &getFFCGenericFortranName() const { return 
FFCGenericFortranName; }
+  const std::string &getGenericFortranFE() const { return GenericFortranFE; }
 

`getCFCGenericFlangName`?



Comment at: clang/include/clang/Driver/Options.td:268
+def cfc_flang_name : Separate<["-"], "cfc-flang-name">, InternalDriverOpt,
+  HelpText<"Name for a custom frontend compiler(cfc) for flang">;
 

`custom fortran compiler` instead, right? IIUC:
* this flag is to specify _custom fortran compiler_ (`cfc`)
* we add `flang_name`at the end  because it can be interpreted as flang's 
alternative name and we want to be consistent with `ccc_gcc_name`



Comment at: clang/lib/Driver/Driver.cpp:1092
 
-  // Extract -ffc args.
-  if (const Arg *A = Args.getLastArg(options::OPT_fcc_fortran_name))
-FFCGenericFortranName = A->getValue();
+  // Extract -cfc args.
+  if (const Arg *A = Args.getLastArg(options::OPT_cfc_flang_name))

There's only one, called `cfc-flang-name` ;-)



Comment at: clang/test/Driver/flang/custom_frontend_flang.f90:5
+! The flag has preference over "flang" frontend.
+! Therefore the driver invokes the FE given by the flag.
+

`FE` is a bit enigmatic. Perhaphs `... invokes the custom fortran compiler 
given by ...`?



Comment at: clang/test/Driver/flang/custom_frontend_flang.f90:9
+
+! The invocations should begin with .tmp1 -fc1.
+! CHECK: "{{[^"]*}}alternative_fortran_frontend" "-fc1"

This comment is out of date :)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D73951/new/

https://reviews.llvm.org/D73951



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D131475: [Flang] Use find_program() to find clang-tblgen

2022-08-29 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Thanks for the quick fix, makes sense! 👍🏻


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D131475/new/

https://reviews.llvm.org/D131475

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128043: [flang][driver] Add support for `-O{0|1|2|3}`

2022-06-27 Thread Andrzej Warzynski via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG869385b11c32: [flang][driver] Add support for `-O{0|1|2|3}` 
(authored by awarzynski).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128043/new/

https://reviews.llvm.org/D128043

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/CodeGenOptions.def
  flang/include/flang/Frontend/CodeGenOptions.h
  flang/include/flang/Frontend/CompilerInvocation.h
  flang/include/flang/Frontend/FrontendActions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CodeGenOptions.cpp
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Driver/default-optimization-pipelines.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/flang_f_opts.f90

Index: flang/test/Driver/flang_f_opts.f90
===
--- /dev/null
+++ flang/test/Driver/flang_f_opts.f90
@@ -0,0 +1,14 @@
+! Test for warnings generated when parsing driver options. You can use this file for relatively small tests and to avoid creating
+! new test files.
+
+!---
+! RUN LINES
+!---
+! RUN: %flang -### -S -O4 %s 2>&1 | FileCheck %s
+
+!---
+! EXPECTED OUTPUT
+!---
+! CHECK: warning: -O4 is equivalent to -O3
+! CHECK-LABEL: "-fc1"
+! CHECK: -O3
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -96,6 +96,7 @@
 ! HELP-FC1-NEXT: -fdebug-measure-parse-tree
 ! HELP-FC1-NEXT: Measure the parse tree
 ! HELP-FC1-NEXT: -fdebug-module-writer   Enable debug messages while writing module files
+! HELP-FC1-NEXT: -fdebug-pass-managerPrints debug information for the new pass manage
 ! HELP-FC1-NEXT: -fdebug-pre-fir-treeDump the pre-FIR tree
 ! HELP-FC1-NEXT: -fdebug-unparse-no-sema Unparse and stop (skips the semantic checks)
 ! HELP-FC1-NEXT: -fdebug-unparse-with-symbols
@@ -120,6 +121,7 @@
 ! HELP-FC1-NEXT: -fno-analyzed-objects-for-unparse
 ! HELP-FC1-NEXT:Do not use the analyzed objects when unparsing
 ! HELP-FC1-NEXT: -fno-automatic Implies the SAVE attribute for non-automatic local objects in subprograms unless RECURSIVE
+! HELP-FC1-NEXT: -fno-debug-pass-manager Disables debug printing for the new pass manager
 ! HELP-FC1-NEXT: -fno-reformat  Dump the cooked character stream in -E mode
 ! HELP-FC1-NEXT: -fopenacc  Enable OpenACC
 ! HELP-FC1-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
Index: flang/test/Driver/default-optimization-pipelines.f90
===
--- /dev/null
+++ flang/test/Driver/default-optimization-pipelines.f90
@@ -0,0 +1,27 @@
+! Verify that`-O{n}` is indeed taken into account when defining the LLVM optimization/middle-end pass pipeline.
+
+!---
+! RUN LINES
+!---
+! RUN: %flang -S -O0 %s -Xflang -fdebug-pass-manager -o /dev/null 2>&1 | FileCheck %s --check-prefix=CHECK-O0
+! RUN: %flang_fc1 -S -O0 %s -fdebug-pass-manager -o /dev/null 2>&1 | FileCheck %s --check-prefix=CHECK-O0
+
+! RUN: %flang -S -O2 %s -Xflang -fdebug-pass-manager -o /dev/null 2>&1 | FileCheck %s --check-prefix=CHECK-O2
+! RUN: %flang_fc1 -S -O2 %s -fdebug-pass-manager -o /dev/null 2>&1 | FileCheck %s --check-prefix=CHECK-O2
+
+!---
+! EXPECTED OUTPUT
+!---
+! CHECK-O0-NOT: Running pass: SimplifyCFGPass on simple_loop_
+! CHECK-O0: Running analysis: TargetLibraryAnalysis on simple_loop_
+
+! CHECK-O2: Running pass: SimplifyCFGPass on simple_loop_
+
+!---
+! INPUT
+!---
+subroutine simple_loop
+  integer :: i
+  do i=1,5
+  end do
+end subroutine
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -46,6 +46,7 @@
 #include "llvm/IRReader/IRReader.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Passes/PassBuilder.h"
+#include "llvm/Passes/StandardInstrumentations.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Target/TargetMachine.h"
@@ -538,7 +539,6 @@
   /*Features=*/"",
   llvm::TargetOptions(), llvm::None));
   assert(tm && "Failed to create TargetMachine");
-  llvmModule->setDataLayout(tm->createDataLayout());
 }
 
 static std::unique_ptr
@@ -610,23 +610,59 @@
   codeGenPasses.run(llvmModule);
 }
 
-/// Generate LLVM byte code file from the input LLVM module.
-///
-/// \param [in] tm Target machine to aid the code-gen pipeline set-up
-/// \param [in] llvmModule LLVM module t

[PATCH] D125788: [flang][driver] Rename `flang-new` as `flang`

2022-06-27 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

In D125788#3612533 , @peixin wrote:

> In summary:
>
>> If you want to use the updated name, flang, set FLANG_USE_LEGACY_NAME to ON 
>> when configuring LLVM Flang.
>
> OFF?

Updated, thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D125788/new/

https://reviews.llvm.org/D125788

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125788: [flang][driver] Rename `flang-new` as `flang`

2022-06-27 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: clang/lib/Driver/ToolChain.cpp:185
   {"flang", "--driver-mode=flang"},
+  {"flang-new", "--driver-mode=flang"},
   {"clang-dxc", "--driver-mode=dxc"},

clementval wrote:
> Why do we need two lines here? Shouldn't we have a single line with the name 
> chosen by the cmake option?
That would require making this file "configurable" by CMake. That would be 
quite an intrusive design change, which IMO we should avoid.

Unless there's some easy way that I'm missing here?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D125788/new/

https://reviews.llvm.org/D125788

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125788: [flang][driver] Rename `flang-new` as `flang`

2022-06-27 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 440283.
awarzynski added a comment.

Incorporate @clementval 's suggestions


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D125788/new/

https://reviews.llvm.org/D125788

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Flang.cpp
  clang/test/Driver/flang/flang.f90
  clang/test/Driver/flang/flang_ucase.F90
  clang/test/Driver/flang/multiple-inputs-mixed.f90
  clang/test/Driver/flang/multiple-inputs.f90
  flang/CMakeLists.txt
  flang/docs/FlangDriver.md
  flang/docs/ImplementingASemanticCheck.md
  flang/docs/Overview.md
  flang/examples/FlangOmpReport/FlangOmpReport.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/CMakeLists.txt
  flang/test/Driver/disable-ext-name-interop.f90
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-version.f90
  flang/test/Driver/escaped-backslash.f90
  flang/test/Driver/fdefault.f90
  flang/test/Driver/flarge-sizes.f90
  flang/test/Driver/frontend-forwarding.f90
  flang/test/Driver/intrinsic-module-path.f90
  flang/test/Driver/macro-def-undef.F90
  flang/test/Driver/missing-input.f90
  flang/test/Driver/predefined-macros-compiler-version.F90
  flang/test/Driver/std2018-wrong.f90
  flang/test/Driver/std2018.f90
  flang/test/Driver/use-module-error.f90
  flang/test/Driver/use-module.f90
  flang/test/Frontend/multiple-input-files.f90
  flang/test/Lower/Intrinsics/command_argument_count.f90
  flang/test/Lower/Intrinsics/exit.f90
  flang/test/Lower/Intrinsics/get_command_argument.f90
  flang/test/Lower/Intrinsics/get_environment_variable.f90
  flang/test/Lower/OpenACC/Todo/acc-declare.f90
  flang/test/Lower/OpenACC/Todo/acc-routine.f90
  flang/test/Lower/OpenMP/Todo/omp-declarative-allocate.f90
  flang/test/Lower/OpenMP/Todo/omp-declare-reduction.f90
  flang/test/Lower/OpenMP/Todo/omp-declare-simd.f90
  flang/test/Lower/OpenMP/Todo/omp-declare-target.f90
  flang/test/lit.cfg.py
  flang/test/lit.site.cfg.py.in
  flang/tools/f18/CMakeLists.txt
  flang/tools/flang-driver/CMakeLists.txt
  flang/tools/flang-driver/driver.cpp

Index: flang/tools/flang-driver/driver.cpp
===
--- flang/tools/flang-driver/driver.cpp
+++ flang/tools/flang-driver/driver.cpp
@@ -85,14 +85,15 @@
   llvm::InitLLVM x(argc, argv);
   llvm::SmallVector args(argv, argv + argc);
 
-  clang::driver::ParsedClangName targetandMode("flang", "--driver-mode=flang");
+  clang::driver::ParsedClangName targetandMode =
+  clang::driver::ToolChain::getTargetAndModeFromProgramName(argv[0]);
   std::string driverPath = getExecutablePath(args[0]);
 
   llvm::BumpPtrAllocator a;
   llvm::StringSaver saver(a);
   ExpandResponseFiles(saver, args);
 
-  // Check if flang-new is in the frontend mode
+  // Check if flang is in the frontend mode
   auto firstArg = std::find_if(
   args.begin() + 1, args.end(), [](const char *a) { return a != nullptr; });
   if (firstArg != args.end()) {
@@ -101,7 +102,7 @@
<< "Valid tools include '-fc1'.\n";
   return 1;
 }
-// Call flang-new frontend
+// Call flang frontend
 if (llvm::StringRef(args[1]).startswith("-fc1")) {
   return executeFC1Tool(args);
 }
Index: flang/tools/flang-driver/CMakeLists.txt
===
--- flang/tools/flang-driver/CMakeLists.txt
+++ flang/tools/flang-driver/CMakeLists.txt
@@ -10,7 +10,7 @@
   Support
 )
 
-add_flang_tool(flang-new
+add_flang_tool(flang
   driver.cpp
   fc1_main.cpp
 
@@ -23,23 +23,33 @@
   Fortran_main
 )
 
-target_link_libraries(flang-new
+target_link_libraries(flang
   PRIVATE
   flangFrontend
   flangFrontendTool
 )
 
-clang_target_link_libraries(flang-new
+clang_target_link_libraries(flang
   PRIVATE
   clangDriver
   clangBasic
 )
 
+if(WIN32 AND NOT CYGWIN)
+  # Prevent versioning if the buildhost is targeting for Win32.
+else()
+  set_target_properties(flang PROPERTIES VERSION ${FLANG_EXECUTABLE_VERSION})
+endif()
+
+if (FLANG_USE_LEGACY_NAME)
+  set_target_properties(flang PROPERTIES OUTPUT_NAME flang-new)
+endif()
+
 option(FLANG_PLUGIN_SUPPORT "Build Flang with plugin support." ON)
 
-# Enable support for plugins, which need access to symbols from flang-new
+# Enable support for plugins, which need access to symbols from flang
 if(FLANG_PLUGIN_SUPPORT)
-  export_executable_symbols_for_plugins(flang-new)
+  export_executable_symbols_for_plugins(flang)
 endif()
 
-install(TARGETS flang-new DESTINATION "${CMAKE_INSTALL_BINDIR}")
+install(TARGETS flang DESTINATION "${CMAKE_INSTALL_BINDIR}")
Index: flang/tools/f18/CMakeLists.txt
===
--- flang/tools/f18/CMakeLists.txt
+++ flang/tools/f18/CMakeLists.txt
@@ -35,9 +35,9 @@
   endif()
   add_custom_command(OUTPUT ${base}.mod
 COMMAND ${CMAKE_COMMAND} -E make_directory ${FLANG_INTRINSIC_MODU

[PATCH] D128333: [clang][flang] Disable defaulting to `-fpie` for LLVM Flang

2022-06-27 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

@MaskRay, thank for taking a look!

In D128333#3605745 , @MaskRay wrote:

> gfortran defaults to PIE as well.

While we strive to be compatible with `gfortan`, there's a lot relatively 
"basic" things still missing in LLVM Flang. So this is not the highest priority 
ATM.

>> We can revisit this once support for -fpie and -fpic is available in LLVM 
>> Flang. I'm not aware of anyone actively working in this area.
>
> Disagree. The PIE default should be fine. When PIE support is added, the 
> default mode naturally becomes PIE.
> Note: -fpie object files can be linked with either -no-pie or -pie. -fno-pic 
> object files can only be linked with -no-pie.
> -fpie is more portable than -fno-pic.

But an object file with R_X86_64_32 relocations cannot be linked with a `-pie` 
object, right? How can I make sure that there are no such relocations then?

> (Why does flang use clang/lib/Driver? For clang developers, it seems that 
> `check-clang check-clang-tools` is not sufficient. `check-flang` needs to be 
> used as well.)

Otherwise, we'd have to re-implement clang/lib/Driver for LLVM Flang. This 
design was proposed and discussed here 
.

> For clang developers, it seems that `check-clang check-clang-tools` is not 
> sufficient. `check-flang` needs to be used as well.)

Isn't this a bit similar to e.g. LLVM developers? Or MLIR developers?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128333/new/

https://reviews.llvm.org/D128333

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128333: [clang][flang] Disable defaulting to `-fpie` for LLVM Flang

2022-06-28 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

In D128333#3613696 , @MaskRay wrote:

> True. If it is difficult to override the -pie default from flang side, I am 
> fine with the code change.

Thanks! The proper/long-term fix will require extending Flang's frontend driver 
so that it supports `-mrelocation-model`, `-fpic` and `-fpic-level` (and 
probably a few more). But I don't want to rush that.

>>> (Why does flang use clang/lib/Driver? For clang developers, it seems that 
>>> `check-clang check-clang-tools` is not sufficient. `check-flang` needs to 
>>> be used as well.)
>>
>> Otherwise, we'd have to re-implement clang/lib/Driver for LLVM Flang. This 
>> design was proposed and discussed here 
>> .
>
> OK, so you did bring this up. I guess I'll have to accept...

With clangDriver 

 being effectively shared between Clang and Flang, it would make a lot of sense 
to lift `clangDriver` out of Clang so that it's an independent sub-project. 
We've proposed that and folks have been mostly in favor. Relevant RFCs:

- RFC: refactoring libclangDriver/libclangFrontend to share with Flang 

- RFC: refactoring clangDriver - diagnostics classes 


Not much is really happening in this area ATM, but I'm hoping that 
https://discourse.llvm.org/t/rfc-improving-clang-s-diagnostics could unblock 
some progress.




Comment at: flang/test/Driver/no-pie.f90:3
+
+!-
+! RUN COMMANDS

MaskRay wrote:
> The `! RUN COMMANDS` and `EXPECTED OUTPUT` comments seem rather redundant. 
> I'd remove them.
This style is quite common in this directory, see e.g. 
https://github.com/llvm/llvm-project/blob/main/flang/test/Driver/emit-asm-aarch64.f90.
 I'm hoping that this makes these tests easier to follow for folks less 
familiar with LIT in general.

If that's OK, I'll leave this here (but I don't expect others to follow similar 
approach, IMO it's a matter of personal preference).



Comment at: flang/test/Driver/no-pie.f90:11
+!
+! CHECK-NOT: fpie
+! CHECK-NOT: fpic

MaskRay wrote:
> This NOT pattern can easily get stale. You need a test that driver `-pie` 
> forwards `-pie` to the linker and by default `-pie` does not pass the the 
> linker.
Good point, will update!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128333/new/

https://reviews.llvm.org/D128333

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128333: [clang][flang] Disable defaulting to `-fpie` for LLVM Flang

2022-06-28 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 440628.
awarzynski added a comment.

Update the test following the comments from @MaskRay

Also added a comment in Linux.cpp and renamed no-pie.f90 as pic-flags.f90 (to 
avoid FileCheck matching e.g. `! CHECK: pie` against the file name).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128333/new/

https://reviews.llvm.org/D128333

Files:
  clang/lib/Driver/ToolChains/Linux.cpp
  flang/test/Driver/pic-flags.f90


Index: flang/test/Driver/pic-flags.f90
===
--- /dev/null
+++ flang/test/Driver/pic-flags.f90
@@ -0,0 +1,24 @@
+! Verify that in contrast to Clang, Flang does not default to generating 
position independent executables/code
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang -### %s -target aarch64-linux-gnu 2>&1 | FileCheck %s 
--check-prefix=CHECK-NOPIE
+! RUN: %flang -### %s -target aarch64-linux-gnu -fno-pie 2>&1 | FileCheck %s 
--check-prefix=CHECK-NOPIE
+
+! RUN: %flang -### %s -target aarch64-linux-gnu -fpie 2>&1 | FileCheck %s 
--check-prefix=CHECK-PIE
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK-NOPIE: "-fc1"
+! CHECk-NOPIE-NOT: fpic
+! CHECK-NOPIE: "{{.*}}ld"
+! CHECK-NOPIE-NOT: "-pie"
+
+! CHECK-PIE: "-fc1"
+! TODO: Once Flang supports `-fpie`, it //should// use -fpic when invoking 
`flang -fc1`. Update the following line once `-fpie` is
+! available.
+! CHECk-PIE-NOT: fpic
+! CHECK-PIE: "{{.*}}ld"
+! CHECK-PIE-NOT: "-pie"
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -699,8 +699,11 @@
 }
 
 bool Linux::isPIEDefault(const llvm::opt::ArgList &Args) const {
-  return CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
- getTriple().isMusl() || getSanitizerArgs(Args).requiresPIE();
+  // TODO: Remove the special treatment for Flang once its frontend driver can
+  // generate position independent code.
+  return !getDriver().IsFlangMode() &&
+ (CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
+  getTriple().isMusl() || getSanitizerArgs(Args).requiresPIE());
 }
 
 bool Linux::IsAArch64OutlineAtomicsDefault(const ArgList &Args) const {


Index: flang/test/Driver/pic-flags.f90
===
--- /dev/null
+++ flang/test/Driver/pic-flags.f90
@@ -0,0 +1,24 @@
+! Verify that in contrast to Clang, Flang does not default to generating position independent executables/code
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang -### %s -target aarch64-linux-gnu 2>&1 | FileCheck %s --check-prefix=CHECK-NOPIE
+! RUN: %flang -### %s -target aarch64-linux-gnu -fno-pie 2>&1 | FileCheck %s --check-prefix=CHECK-NOPIE
+
+! RUN: %flang -### %s -target aarch64-linux-gnu -fpie 2>&1 | FileCheck %s --check-prefix=CHECK-PIE
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK-NOPIE: "-fc1"
+! CHECk-NOPIE-NOT: fpic
+! CHECK-NOPIE: "{{.*}}ld"
+! CHECK-NOPIE-NOT: "-pie"
+
+! CHECK-PIE: "-fc1"
+! TODO: Once Flang supports `-fpie`, it //should// use -fpic when invoking `flang -fc1`. Update the following line once `-fpie` is
+! available.
+! CHECk-PIE-NOT: fpic
+! CHECK-PIE: "{{.*}}ld"
+! CHECK-PIE-NOT: "-pie"
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -699,8 +699,11 @@
 }
 
 bool Linux::isPIEDefault(const llvm::opt::ArgList &Args) const {
-  return CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
- getTriple().isMusl() || getSanitizerArgs(Args).requiresPIE();
+  // TODO: Remove the special treatment for Flang once its frontend driver can
+  // generate position independent code.
+  return !getDriver().IsFlangMode() &&
+ (CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
+  getTriple().isMusl() || getSanitizerArgs(Args).requiresPIE());
 }
 
 bool Linux::IsAArch64OutlineAtomicsDefault(const ArgList &Args) const {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128333: [clang][flang] Disable defaulting to `-fpie` for LLVM Flang

2022-06-28 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 440874.
awarzynski added a comment.

Update the test


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128333/new/

https://reviews.llvm.org/D128333

Files:
  clang/lib/Driver/ToolChains/Linux.cpp
  flang/test/Driver/pic-flags.f90


Index: flang/test/Driver/pic-flags.f90
===
--- /dev/null
+++ flang/test/Driver/pic-flags.f90
@@ -0,0 +1,24 @@
+! Verify that in contrast to Clang, Flang does not default to generating 
position independent executables/code
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang -### %s --target=aarch64-linux-gnu 2>&1 | FileCheck %s 
--check-prefix=CHECK-NOPIE
+! RUN: %flang -### %s --target=aarch64-linux-gnu -fno-pie 2>&1 | FileCheck %s 
--check-prefix=CHECK-NOPIE
+
+! RUN: %flang -### %s --target=aarch64-linux-gnu -fpie 2>&1 | FileCheck %s 
--check-prefix=CHECK-PIE
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK-NOPIE: "-fc1"
+! CHECk-NOPIE-NOT: "-fpic"
+! CHECK-NOPIE: "{{.*}}ld"
+! CHECK-NOPIE-NOT: "-pie"
+
+! CHECK-PIE: "-fc1"
+!! TODO Once Flang supports `-fpie`, it //should// use -fpic when invoking 
`flang -fc1`. Update the following line once `-fpie` is
+! available.
+! CHECk-PIE-NOT: "-fpic"
+! CHECK-PIE: "{{.*}}ld"
+! CHECK-PIE-NOT: "-pie"
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -699,8 +699,11 @@
 }
 
 bool Linux::isPIEDefault(const llvm::opt::ArgList &Args) const {
-  return CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
- getTriple().isMusl() || getSanitizerArgs(Args).requiresPIE();
+  // TODO: Remove the special treatment for Flang once its frontend driver can
+  // generate position independent code.
+  return !getDriver().IsFlangMode() &&
+ (CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
+  getTriple().isMusl() || getSanitizerArgs(Args).requiresPIE());
 }
 
 bool Linux::IsAArch64OutlineAtomicsDefault(const ArgList &Args) const {


Index: flang/test/Driver/pic-flags.f90
===
--- /dev/null
+++ flang/test/Driver/pic-flags.f90
@@ -0,0 +1,24 @@
+! Verify that in contrast to Clang, Flang does not default to generating position independent executables/code
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang -### %s --target=aarch64-linux-gnu 2>&1 | FileCheck %s --check-prefix=CHECK-NOPIE
+! RUN: %flang -### %s --target=aarch64-linux-gnu -fno-pie 2>&1 | FileCheck %s --check-prefix=CHECK-NOPIE
+
+! RUN: %flang -### %s --target=aarch64-linux-gnu -fpie 2>&1 | FileCheck %s --check-prefix=CHECK-PIE
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK-NOPIE: "-fc1"
+! CHECk-NOPIE-NOT: "-fpic"
+! CHECK-NOPIE: "{{.*}}ld"
+! CHECK-NOPIE-NOT: "-pie"
+
+! CHECK-PIE: "-fc1"
+!! TODO Once Flang supports `-fpie`, it //should// use -fpic when invoking `flang -fc1`. Update the following line once `-fpie` is
+! available.
+! CHECk-PIE-NOT: "-fpic"
+! CHECK-PIE: "{{.*}}ld"
+! CHECK-PIE-NOT: "-pie"
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -699,8 +699,11 @@
 }
 
 bool Linux::isPIEDefault(const llvm::opt::ArgList &Args) const {
-  return CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
- getTriple().isMusl() || getSanitizerArgs(Args).requiresPIE();
+  // TODO: Remove the special treatment for Flang once its frontend driver can
+  // generate position independent code.
+  return !getDriver().IsFlangMode() &&
+ (CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
+  getTriple().isMusl() || getSanitizerArgs(Args).requiresPIE());
 }
 
 bool Linux::IsAArch64OutlineAtomicsDefault(const ArgList &Args) const {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D128333: [clang][flang] Disable defaulting to `-fpie` for LLVM Flang

2022-06-29 Thread Andrzej Warzynski via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb405407a4899: [clang][flang] Disable defaulting to `-fpie` 
for LLVM Flang (authored by awarzynski).

Changed prior to commit:
  https://reviews.llvm.org/D128333?vs=440874&id=440884#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D128333/new/

https://reviews.llvm.org/D128333

Files:
  clang/lib/Driver/ToolChains/Linux.cpp
  flang/docs/ReleaseNotes.md
  flang/test/Driver/pic-flags.f90


Index: flang/test/Driver/pic-flags.f90
===
--- /dev/null
+++ flang/test/Driver/pic-flags.f90
@@ -0,0 +1,24 @@
+! Verify that in contrast to Clang, Flang does not default to generating 
position independent executables/code
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang -### %s --target=aarch64-linux-gnu 2>&1 | FileCheck %s 
--check-prefix=CHECK-NOPIE
+! RUN: %flang -### %s --target=aarch64-linux-gnu -fno-pie 2>&1 | FileCheck %s 
--check-prefix=CHECK-NOPIE
+
+! RUN: %flang -### %s --target=aarch64-linux-gnu -fpie 2>&1 | FileCheck %s 
--check-prefix=CHECK-PIE
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK-NOPIE: "-fc1"
+! CHECk-NOPIE-NOT: "-fpic"
+! CHECK-NOPIE: "{{.*}}ld"
+! CHECK-NOPIE-NOT: "-pie"
+
+! CHECK-PIE: "-fc1"
+!! TODO Once Flang supports `-fpie`, it //should// use -fpic when invoking 
`flang -fc1`. Update the following line once `-fpie` is
+! available.
+! CHECk-PIE-NOT: "-fpic"
+! CHECK-PIE: "{{.*}}ld"
+! CHECK-PIE-NOT: "-pie"
Index: flang/docs/ReleaseNotes.md
===
--- flang/docs/ReleaseNotes.md
+++ flang/docs/ReleaseNotes.md
@@ -28,6 +28,13 @@
 
 ## Non-comprehensive list of changes in this release
 * The bash wrapper script, `flang`, is renamed as `flang-to-external-fc`.
+* In contrast to Clang, Flang will not default to using `-fpie` when linking
+  executables. This is only a temporary solution and the goal is to align with
+  Clang in the near future. First, however, the frontend driver needs to be
+  extended so that it can generate position independent code (that requires
+  adding support for e.g. `-fpic` and `-mrelocation-model` in `flang-new
+  -fc1`). Once that is available, support for the `-fpie` can officially be
+  added and the default behaviour updated.
 
 ## New Compiler Flags
 * Refined how `-f{no-}color-diagnostics` is treated to better align with Clang.
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -699,8 +699,11 @@
 }
 
 bool Linux::isPIEDefault(const llvm::opt::ArgList &Args) const {
-  return CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
- getTriple().isMusl() || getSanitizerArgs(Args).requiresPIE();
+  // TODO: Remove the special treatment for Flang once its frontend driver can
+  // generate position independent code.
+  return !getDriver().IsFlangMode() &&
+ (CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
+  getTriple().isMusl() || getSanitizerArgs(Args).requiresPIE());
 }
 
 bool Linux::IsAArch64OutlineAtomicsDefault(const ArgList &Args) const {


Index: flang/test/Driver/pic-flags.f90
===
--- /dev/null
+++ flang/test/Driver/pic-flags.f90
@@ -0,0 +1,24 @@
+! Verify that in contrast to Clang, Flang does not default to generating position independent executables/code
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang -### %s --target=aarch64-linux-gnu 2>&1 | FileCheck %s --check-prefix=CHECK-NOPIE
+! RUN: %flang -### %s --target=aarch64-linux-gnu -fno-pie 2>&1 | FileCheck %s --check-prefix=CHECK-NOPIE
+
+! RUN: %flang -### %s --target=aarch64-linux-gnu -fpie 2>&1 | FileCheck %s --check-prefix=CHECK-PIE
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK-NOPIE: "-fc1"
+! CHECk-NOPIE-NOT: "-fpic"
+! CHECK-NOPIE: "{{.*}}ld"
+! CHECK-NOPIE-NOT: "-pie"
+
+! CHECK-PIE: "-fc1"
+!! TODO Once Flang supports `-fpie`, it //should// use -fpic when invoking `flang -fc1`. Update the following line once `-fpie` is
+! available.
+! CHECk-PIE-NOT: "-fpic"
+! CHECK-PIE: "{{.*}}ld"
+! CHECK-PIE-NOT: "-pie"
Index: flang/docs/ReleaseNotes.md
===
--- flang/docs/ReleaseNotes.md
+++ flang/docs/ReleaseNotes.md
@@ -28,6 +28,13 @@
 
 ## Non-comprehensive list of changes in this release
 * The bash wrapper script, `flang`, is renamed as `flang-to-external-fc`.
+* In contrast to Clang, Flang will not default to using `-fpie` when linking
+  executables. This is only a temporary solution and the goal is to align with
+  Clang in the near future. First, however, the frontend driver needs to be
+  extended so that it can generate position independent code (that requ

[PATCH] D125788: [flang][driver] Rename `flang-new` as `flang`

2022-06-30 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Thank your for reviewing @clementval !

In D125788#3621585 , @clementval 
wrote:

> Shouldn't we just wait until we can make the permanent renaming so we do not 
> add unnecessary cmake option?

This was discussed in one of our calls. As we weren't able to agree on any 
specific time-frames, the CMake route was proposed instead. This was suggested 
by @sscalpone as an acceptable compromise. From what I recall, there were no 
objections to this.

`flang-new` has always been intended as a //temporary name// for the compiler 
driver. That's because `flang` was reserved for the bash script. The bash 
script has recently been renamed as `flang-to-external-fc` ( D125832 
) so we are free to repurpose that name.  As 
I tried to explain earlier, these names (`flang-new` vs `flang`) have always 
been very confusing to people and we are trying to improve and to clarify that, 
step by step. While this approach is not ideal, it gives us the flexibility to 
choose our preferred name sooner rather than later. If you feel that we should 
keep `flang-new`, you can continue using/building LLVM Flang as you have been 
so far. If you are ready to update the driver name, the CMake option enables 
that for you.

We discussed this in our call on Monday and agreed to go ahead provided that 
this change is technically sound. IIUC, this has now been confirmed:

> Overall the patch looks ok from a technical point.

As always, please correct me if I missed or misinterpreted something!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D125788/new/

https://reviews.llvm.org/D125788

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125788: [flang][driver] Rename `flang-new` as `flang`

2022-06-30 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: clang/lib/Driver/ToolChain.cpp:185
   {"flang", "--driver-mode=flang"},
+  {"flang-new", "--driver-mode=flang"},
   {"clang-dxc", "--driver-mode=dxc"},

richard.barton.arm wrote:
> clementval wrote:
> > This is counter intuitive. We rename flang-new but we add flang-new here. 
> > It should be configurable. 
> This is a list of all the valid prefixes of binaries that the driver 
> supports. With this change, an additional one will be supported so I don't 
> think it's an issue to have both flang and flang-new here.
> 
> The thing that confuses me is how flang-new works today without this change, 
> given that "flang" is not a suffix of "flang-new"? @awarzynski , do you know 
> why that is? Perhaps the line here is not needed at all? Or is this a bug fix 
> for flang-new that is actually unrelated to this change?
> This is counter intuitive. 

I can add a comment to clarify this.

> It should be configurable.

It is, in Flang's [[ 
https://github.com/llvm/llvm-project/blob/main/flang/tools/flang-driver/driver.cpp
 | driver.cpp ]]. Originally, the suffix was hard-coded as:
```
clang::driver::ParsedClangName targetandMode("flang", "--driver-mode=flang");
```
(i.e. the `clangDriver` library used `flang` internally despite the actual name 
being `flang-new`). This is now being replaced with (see in "driver.cpp"):
```
 clang::driver::ParsedClangName targetandMode =
  clang::driver::ToolChain::getTargetAndModeFromProgramName(argv[0]);
```

But the change in "driver.cpp" means that we can no longer make assumptions 
about the suffix and hence the update here. 

Like I mentioned earlier, we should not make this file build-time configurable. 
One possible option would be to try to update Clang's [[ 
https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Config/config.h.cmake
 | config.h.cmake ]], but that's would lead to more Flang-specific changes in 
Clang's core set-up. Also, I'm not convinced it would work here. 

> @awarzynski , do you know why that is? 

Yeah, check Flang's "driver.cpp". We should've captured this earlier. The 
original set-up from ToolChain.cpp predates `flang-new`. And then in 
"driver.cpp" we just matched what was here. There was a lot of confusion around 
naming  back then and this has slipped in. 



Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D125788/new/

https://reviews.llvm.org/D125788

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125788: [flang][driver] Rename `flang-new` as `flang`

2022-07-01 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 441643.
awarzynski added a comment.

Add a comment


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D125788/new/

https://reviews.llvm.org/D125788

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Flang.cpp
  clang/test/Driver/flang/flang.f90
  clang/test/Driver/flang/flang_ucase.F90
  clang/test/Driver/flang/multiple-inputs-mixed.f90
  clang/test/Driver/flang/multiple-inputs.f90
  flang/CMakeLists.txt
  flang/docs/FlangDriver.md
  flang/docs/ImplementingASemanticCheck.md
  flang/docs/Overview.md
  flang/examples/FlangOmpReport/FlangOmpReport.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/CMakeLists.txt
  flang/test/Driver/disable-ext-name-interop.f90
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-version.f90
  flang/test/Driver/escaped-backslash.f90
  flang/test/Driver/fdefault.f90
  flang/test/Driver/flarge-sizes.f90
  flang/test/Driver/frontend-forwarding.f90
  flang/test/Driver/intrinsic-module-path.f90
  flang/test/Driver/macro-def-undef.F90
  flang/test/Driver/missing-input.f90
  flang/test/Driver/predefined-macros-compiler-version.F90
  flang/test/Driver/std2018-wrong.f90
  flang/test/Driver/std2018.f90
  flang/test/Driver/use-module-error.f90
  flang/test/Driver/use-module.f90
  flang/test/Frontend/multiple-input-files.f90
  flang/test/Lower/Intrinsics/command_argument_count.f90
  flang/test/Lower/Intrinsics/exit.f90
  flang/test/Lower/Intrinsics/get_command_argument.f90
  flang/test/Lower/Intrinsics/get_environment_variable.f90
  flang/test/Lower/OpenACC/Todo/acc-declare.f90
  flang/test/Lower/OpenACC/Todo/acc-routine.f90
  flang/test/Lower/OpenMP/Todo/omp-declarative-allocate.f90
  flang/test/Lower/OpenMP/Todo/omp-declare-reduction.f90
  flang/test/Lower/OpenMP/Todo/omp-declare-simd.f90
  flang/test/Lower/OpenMP/Todo/omp-declare-target.f90
  flang/test/lit.cfg.py
  flang/test/lit.site.cfg.py.in
  flang/tools/f18/CMakeLists.txt
  flang/tools/flang-driver/CMakeLists.txt
  flang/tools/flang-driver/driver.cpp

Index: flang/tools/flang-driver/driver.cpp
===
--- flang/tools/flang-driver/driver.cpp
+++ flang/tools/flang-driver/driver.cpp
@@ -85,14 +85,15 @@
   llvm::InitLLVM x(argc, argv);
   llvm::SmallVector args(argv, argv + argc);
 
-  clang::driver::ParsedClangName targetandMode("flang", "--driver-mode=flang");
+  clang::driver::ParsedClangName targetandMode =
+  clang::driver::ToolChain::getTargetAndModeFromProgramName(argv[0]);
   std::string driverPath = getExecutablePath(args[0]);
 
   llvm::BumpPtrAllocator a;
   llvm::StringSaver saver(a);
   ExpandResponseFiles(saver, args);
 
-  // Check if flang-new is in the frontend mode
+  // Check if flang is in the frontend mode
   auto firstArg = std::find_if(
   args.begin() + 1, args.end(), [](const char *a) { return a != nullptr; });
   if (firstArg != args.end()) {
@@ -101,7 +102,7 @@
<< "Valid tools include '-fc1'.\n";
   return 1;
 }
-// Call flang-new frontend
+// Call flang frontend
 if (llvm::StringRef(args[1]).startswith("-fc1")) {
   return executeFC1Tool(args);
 }
Index: flang/tools/flang-driver/CMakeLists.txt
===
--- flang/tools/flang-driver/CMakeLists.txt
+++ flang/tools/flang-driver/CMakeLists.txt
@@ -10,7 +10,7 @@
   Support
 )
 
-add_flang_tool(flang-new
+add_flang_tool(flang
   driver.cpp
   fc1_main.cpp
 
@@ -23,23 +23,33 @@
   Fortran_main
 )
 
-target_link_libraries(flang-new
+target_link_libraries(flang
   PRIVATE
   flangFrontend
   flangFrontendTool
 )
 
-clang_target_link_libraries(flang-new
+clang_target_link_libraries(flang
   PRIVATE
   clangDriver
   clangBasic
 )
 
+if(WIN32 AND NOT CYGWIN)
+  # Prevent versioning if the buildhost is targeting for Win32.
+else()
+  set_target_properties(flang PROPERTIES VERSION ${FLANG_EXECUTABLE_VERSION})
+endif()
+
+if (FLANG_USE_LEGACY_NAME)
+  set_target_properties(flang PROPERTIES OUTPUT_NAME flang-new)
+endif()
+
 option(FLANG_PLUGIN_SUPPORT "Build Flang with plugin support." ON)
 
-# Enable support for plugins, which need access to symbols from flang-new
+# Enable support for plugins, which need access to symbols from flang
 if(FLANG_PLUGIN_SUPPORT)
-  export_executable_symbols_for_plugins(flang-new)
+  export_executable_symbols_for_plugins(flang)
 endif()
 
-install(TARGETS flang-new DESTINATION "${CMAKE_INSTALL_BINDIR}")
+install(TARGETS flang DESTINATION "${CMAKE_INSTALL_BINDIR}")
Index: flang/tools/f18/CMakeLists.txt
===
--- flang/tools/f18/CMakeLists.txt
+++ flang/tools/f18/CMakeLists.txt
@@ -35,9 +35,9 @@
   endif()
   add_custom_command(OUTPUT ${base}.mod
 COMMAND ${CMAKE_COMMAND} -E make_directory ${FLANG_INTRINSIC_MODULES_DIR}
-COMMAND fla

[PATCH] D122542: [flang][driver] Make --version and -version consistent with clang

2022-03-28 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski accepted this revision.
awarzynski added a comment.

Makes sense, many thanks for doing this!




Comment at: clang/include/clang/Driver/Options.td:5756
+
+}
+

[nit] IMHO this file lacks comments, hence the suggestion :) 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122542/new/

https://reviews.llvm.org/D122542

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122008: [flang][driver] Add support for generating executables

2022-03-28 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 418580.
awarzynski added a comment.
Herald added a subscriber: MaskRay.

Use llvm_add_library instead of add_flang_library

Fortran_main should be a static library, but `add_flang_library` does not parse
`STATIC` in `add_flang_library(Fortran_main STATIC Fortran_main.c)`. I could
extend `add_flang_library` instead, but `llvm_add_library` works fine as well
and this change is less intrusive.

Also rebased on top of main.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122008/new/

https://reviews.llvm.org/D122008

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  flang/include/flang/Runtime/stop.h
  flang/runtime/CMakeLists.txt
  flang/runtime/FortranMain/CMakeLists.txt
  flang/runtime/FortranMain/Fortran_main.c
  flang/test/CMakeLists.txt
  flang/test/Driver/linker-flags.f90

Index: flang/test/Driver/linker-flags.f90
===
--- /dev/null
+++ flang/test/Driver/linker-flags.f90
@@ -0,0 +1,30 @@
+! Verify that the Fortran runtime libraries are present in the linker
+! invocation. These libraries are added on top of other standard runtime
+! libraries that the Clang driver will include.
+
+! NOTE: The additional linker flags tested here are currently specified in
+! clang/lib/Driver/Toolchains/Gnu.cpp. This makes the current implementation GNU
+! (Linux) specific. The following line will make sure that this test is skipped
+! on Windows. Ideally we should find a more robust way of testing this.
+! REQUIRES: shell
+! UNSUPPORTED: darwin, macos
+
+!
+! RUN COMMAND
+!
+! RUN: %flang -### --ld-path=/usr/bin/ld %S/Inputs/hello.f90 2>&1 | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! Compiler invocation to generate the object file
+! CHECK-LABEL: {{.*}} "-emit-obj"
+! CHECK-SAME:  "-o" "[[object_file:.*]]" {{.*}}Inputs/hello.f90
+
+! Linker invocation to generate the executable
+! CHECK-LABEL:  "/usr/bin/ld"
+! CHECK-SAME: "[[object_file]]"
+! CHECK-SAME: -lFortran_main
+! CHECK-SAME: -lFortranRuntime
+! CHECK-SAME: -lFortranDecimal
+! CHECK-SAME: -lm
Index: flang/test/CMakeLists.txt
===
--- flang/test/CMakeLists.txt
+++ flang/test/CMakeLists.txt
@@ -57,6 +57,9 @@
   bbc
   llvm-objdump
   split-file
+  FortranRuntime
+  Fortran_main
+  FortranDecimal
 )
 
 if (FLANG_INCLUDE_TESTS)
Index: flang/runtime/FortranMain/Fortran_main.c
===
--- /dev/null
+++ flang/runtime/FortranMain/Fortran_main.c
@@ -0,0 +1,21 @@
+//===-- runtime/FortranMain/Fortran_main.c ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "flang/Runtime/main.h"
+#include "flang/Runtime/stop.h"
+
+/* main entry into PROGRAM */
+void _QQmain();
+
+/* C main stub */
+int main(int argc, const char *argv[], const char *envp[]) {
+  RTNAME(ProgramStart)(argc, argv, envp);
+  _QQmain();
+  RTNAME(ProgramEndStatement)();
+  return 0;
+}
Index: flang/runtime/FortranMain/CMakeLists.txt
===
--- /dev/null
+++ flang/runtime/FortranMain/CMakeLists.txt
@@ -0,0 +1,3 @@
+llvm_add_library(Fortran_main STATIC
+  Fortran_main.c
+)
Index: flang/runtime/CMakeLists.txt
===
--- flang/runtime/CMakeLists.txt
+++ flang/runtime/CMakeLists.txt
@@ -30,6 +30,8 @@
 # with different names
 include_directories(AFTER ${CMAKE_CURRENT_BINARY_DIR})
 
+add_subdirectory(FortranMain)
+
 add_flang_library(FortranRuntime
   ISO_Fortran_binding.cpp
   allocatable.cpp
Index: flang/include/flang/Runtime/stop.h
===
--- flang/include/flang/Runtime/stop.h
+++ flang/include/flang/Runtime/stop.h
@@ -27,7 +27,7 @@
 NORETURN void RTNAME(ProgramEndStatement)(NO_ARGUMENTS);
 
 // Extensions
-NORETURN void RTNAME(Exit)(int status = EXIT_SUCCESS);
+NORETURN void RTNAME(Exit)(int status DEFAULT_VALUE(EXIT_SUCCESS));
 NORETURN void RTNAME(Abort)(NO_ARGUMENTS);
 
 // Crash with an error message when the program dynamically violates a Fortran
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -379,6 +379,13 @@
  Exec, CmdArgs, Inputs, Output));
 }
 
+static void addFortranLinkerFlags(ArgStringList &CmdArgs) {
+  CmdArgs.push_back("-lFortran_main");
+  CmdArgs.push_back("-lFortranRuntime");
+  CmdArgs.push_back("-lFortranDecimal");
+  CmdA

[PATCH] D122542: [flang][driver] Make --version and -version consistent with clang

2022-03-28 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: clang/include/clang/Driver/Options.td:5756
+
+}
+

ekieri wrote:
> awarzynski wrote:
> > [nit] IMHO this file lacks comments, hence the suggestion :) 
> Sure!
> 
> On the topic of this file's structure, I found the nested "let Flags" quite 
> confusing -- Setting "Flags" inside "def version" does not work, as it would 
> be overwritten by the outer "let Flags" on line 4820. But that is a different 
> patch.
> On the topic of this file's structure, I found the nested "let Flags" quite 
> confusing -- Setting "Flags" inside "def version" does not work, as it would 
> be overwritten by the outer "let Flags" on line 4820. But that is a different 
> patch.

Fixing that is high on my TODO list, just never high enough :( Happy to review 
if you get a chance to prepare something! ;-) 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122542/new/

https://reviews.llvm.org/D122542

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-04 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

We discussed this patch in our community call today and some people expressed 
their reservations about merging this just now. As I mentioned, I would like to 
have this merged to unblock the CMake PR 
. As promised, 
here are the options that we've considered:

1. merge this patch "today",
2. merge this patch "today", but add a flag so that by default `flang-new 
file.f90` wouldn't generate an executable (we would remove this flag at a later 
time),
3. wait until the upstreaming of fir-dev is complete (based on today's update, 
I think that that would be in June/July the earliest).

Could you tell me what your preference is?

Please keep in mind that even once CMake support is available, it's going to 
land in the "latest" version of CMake. Folks will have to download the latest 
binaries from https://github.com/Kitware/CMake/releases in order to benefit 
from this.  With time, CMake shipped with various OSes will catch-up and become 
"modern" enough. But there's going to be a delay and hence it makes sense to 
get the CMake support sooner rather than later.

Please comment if I missed or misinterpreted anything. Also, I will add more 
reviewers - basically everyone who discussed this in the call today. Please add 
anyone that I've missed!

Thanks for taking a look!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122008/new/

https://reviews.llvm.org/D122008

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123070: [Driver][NFC] Simplify handling of flags in Options.td

2022-04-05 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski accepted this revision.
awarzynski added a subscriber: jansvoboda11.
awarzynski added a comment.
This revision is now accepted and ready to land.

Thanks for doing this, Emil!

This is a much appreciated clean-up. On quite a few occasions I got confused 
with the nested `let` statements. With this change, everyone should find it 
easier to identify precisely what flags are effectively set for a particular 
option.

> There are probably a developer or two on the clang side that ought to have a 
> say on this.

I agree that we should try to reach as many reviewers as possible. 
@jansvoboda11 was kind enough to review some changes for me in the past. I'll 
also ping Discourse. But I think that you should go ahead with this even there 
no more reviewers :) It's an NFC and a clear improvement compared to what we 
have now.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123070/new/

https://reviews.llvm.org/D123070

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123070: [Driver][NFC] Simplify handling of flags in Options.td

2022-04-06 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

In D123070#3429519 , @hans wrote:

> I worry that the closing comments on '}'s might rot since there's no tooling 
> to maintain them though.

I share your concern. However, from my experience these `let` statements rarely 
change (i.e. this file is fairly stable), so the risk is not that high. 
Personally, I find them very helpful.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123070/new/

https://reviews.llvm.org/D123070

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123211: [flang][driver] Add support for generating LLVM bytecode files

2022-04-06 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski created this revision.
Herald added a subscriber: mgorny.
Herald added projects: Flang, All.
awarzynski requested review of this revision.
Herald added subscribers: cfe-commits, jdoerfert.
Herald added a project: clang.

Support for generating LLVM BC files is added in Flang's compiler and
frontend drivers. This requires the `BitcodeWriterPass` pass to be run
on the input LLVM IR module and is implemented as a dedicated frontend
aciton. The new functionality as seen by the user (compiler driver):

  flang-new -c -emit-llvm file.90

or (frontend driver):

  flang-new -fc1 -emit-llvm-bc file.f90

The new behaviour is consistent with `clang` and `clang -cc1`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123211

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/CMakeLists.txt
  flang/test/Driver/driver-help.f90

Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -71,6 +71,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm-bc  Build ASTs then convert to LLVM, emit .bc file
 ! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
Index: flang/test/CMakeLists.txt
===
--- flang/test/CMakeLists.txt
+++ flang/test/CMakeLists.txt
@@ -55,6 +55,7 @@
   fir-opt
   tco
   bbc
+  llvm-dis
   llvm-objdump
   split-file
 )
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -37,6 +37,8 @@
 return std::make_unique();
   case EmitLLVM:
 return std::make_unique();
+  case EmitLLVMBitcode:
+return std::make_unique();
   case EmitObj:
 return std::make_unique(
 BackendAction::BackendActionTy::Backend_EmitObj);
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -33,6 +33,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/TargetTransformInfo.h"
+#include "llvm/Bitcode/BitcodeWriterPass.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Passes/PassBuilder.h"
@@ -472,6 +473,50 @@
   llvmModule->print(*os, /*AssemblyAnnotationWriter=*/nullptr);
 }
 
+void EmitLLVMBitcodeAction::ExecuteAction() {
+  CompilerInstance &ci = this->instance();
+  // Generate an LLVM module if it's not already present (it will already be
+  // present if the input file is an LLVM IR/BC file).
+  if (!llvmModule)
+GenerateLLVMIR();
+
+  llvm::ModulePassManager MPM;
+  llvm::ModuleAnalysisManager MAM;
+
+  // Create and configure `Target`
+  std::string error;
+  std::string theTriple = llvmModule->getTargetTriple();
+  const llvm::Target *theTarget =
+  llvm::TargetRegistry::lookupTarget(theTriple, error);
+  assert(theTarget && "Failed to create Target");
+
+  // Create and configure `TargetMachine`
+  std::unique_ptr TM;
+
+  TM.reset(theTarget->createTargetMachine(theTriple, /*CPU=*/"",
+  /*Features=*/"", llvm::TargetOptions(), llvm::None));
+  llvmModule->setDataLayout(TM->createDataLayout());
+  assert(TM && "Failed to create TargetMachine");
+
+  // Generate an output file
+  std::unique_ptr os = ci.CreateDefaultOutputFile(
+  /*Binary=*/true, /*InFile=*/GetCurrentFileOrBufferName(), "bc");
+  if (!os) {
+unsigned diagID = ci.diagnostics().getCustomDiagID(
+clang::DiagnosticsEngine::Error, "failed to create the output file");
+ci.diagnostics().Report(diagID);
+return;
+  }
+
+  // Set-up the pass manager
+  llvm::PassBuilder PB(TM.get());
+  PB.registerModuleAnalyses(MAM);
+  MPM.addPass(llvm::BitcodeWriterPass(*os));
+
+  // Run the passes
+  MPM.run(*llvmModule, MAM);
+}
+
 void EmitMLIRAction::ExecuteAction() {
   CompilerInstance &ci = this->instance();
 
Index: flang/lib/Frontend/CompilerInvocation.cpp
===
--- flang/lib/Frontend/CompilerInvocation.cpp
+++ flang/lib/Frontend/CompilerInvocation.cpp
@@ -150,6 +150,9 @@
 case clang::driver::options::OPT_e

[PATCH] D123211: [flang][driver] Add support for generating LLVM bytecode files

2022-04-06 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 420821.
awarzynski added a comment.
Herald added a reviewer: sscalpone.

Add missing test


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123211/new/

https://reviews.llvm.org/D123211

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/CMakeLists.txt
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm-bc.f90

Index: flang/test/Driver/emit-llvm-bc.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm-bc.f90
@@ -0,0 +1,8 @@
+! RUN: %flang -emit-llvm -c %s -o - | llvm-dis -o - | FileCheck %s
+! RUN: %flang_fc1 -emit-llvm-bc %s -o - | llvm-dis -o - | FileCheck %s
+
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -71,6 +71,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm-bc  Build ASTs then convert to LLVM, emit .bc file
 ! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
Index: flang/test/CMakeLists.txt
===
--- flang/test/CMakeLists.txt
+++ flang/test/CMakeLists.txt
@@ -55,6 +55,7 @@
   fir-opt
   tco
   bbc
+  llvm-dis
   llvm-objdump
   split-file
 )
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -37,6 +37,8 @@
 return std::make_unique();
   case EmitLLVM:
 return std::make_unique();
+  case EmitLLVMBitcode:
+return std::make_unique();
   case EmitObj:
 return std::make_unique(
 BackendAction::BackendActionTy::Backend_EmitObj);
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -33,6 +33,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/TargetTransformInfo.h"
+#include "llvm/Bitcode/BitcodeWriterPass.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Passes/PassBuilder.h"
@@ -472,6 +473,50 @@
   llvmModule->print(*os, /*AssemblyAnnotationWriter=*/nullptr);
 }
 
+void EmitLLVMBitcodeAction::ExecuteAction() {
+  CompilerInstance &ci = this->instance();
+  // Generate an LLVM module if it's not already present (it will already be
+  // present if the input file is an LLVM IR/BC file).
+  if (!llvmModule)
+GenerateLLVMIR();
+
+  llvm::ModulePassManager MPM;
+  llvm::ModuleAnalysisManager MAM;
+
+  // Create and configure `Target`
+  std::string error;
+  std::string theTriple = llvmModule->getTargetTriple();
+  const llvm::Target *theTarget =
+  llvm::TargetRegistry::lookupTarget(theTriple, error);
+  assert(theTarget && "Failed to create Target");
+
+  // Create and configure `TargetMachine`
+  std::unique_ptr TM;
+
+  TM.reset(theTarget->createTargetMachine(theTriple, /*CPU=*/"",
+  /*Features=*/"", llvm::TargetOptions(), llvm::None));
+  llvmModule->setDataLayout(TM->createDataLayout());
+  assert(TM && "Failed to create TargetMachine");
+
+  // Generate an output file
+  std::unique_ptr os = ci.CreateDefaultOutputFile(
+  /*Binary=*/true, /*InFile=*/GetCurrentFileOrBufferName(), "bc");
+  if (!os) {
+unsigned diagID = ci.diagnostics().getCustomDiagID(
+clang::DiagnosticsEngine::Error, "failed to create the output file");
+ci.diagnostics().Report(diagID);
+return;
+  }
+
+  // Set-up the pass manager
+  llvm::PassBuilder PB(TM.get());
+  PB.registerModuleAnalyses(MAM);
+  MPM.addPass(llvm::BitcodeWriterPass(*os));
+
+  // Run the passes
+  MPM.run(*llvmModule, MAM);
+}
+
 void EmitMLIRAction::ExecuteAction() {
   CompilerInstance &ci = this->instance();
 
Index: flang/lib/Frontend/CompilerInvocation.cpp
===
--- flang/lib/Frontend/CompilerInvocation.cpp
+++ flang/lib/Frontend/CompilerInvocation.cpp
@@ -150,6 +150,9 @@
 case clang::driver::options::OPT_emit_llvm:
   opts.programA

[PATCH] D123211: [flang][driver] Add support for generating LLVM bytecode files

2022-04-06 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 420862.
awarzynski added a comment.

Move code a bit, add comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123211/new/

https://reviews.llvm.org/D123211

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/CMakeLists.txt
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm-bc.f90

Index: flang/test/Driver/emit-llvm-bc.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm-bc.f90
@@ -0,0 +1,19 @@
+! Test the options for generating LLVM byte-code `-emit-llvm-bc` option
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang -emit-llvm -c %s -o - | llvm-dis -o - | FileCheck %s
+! RUN: %flang_fc1 -emit-llvm-bc %s -o - | llvm-dis -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -71,6 +71,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm-bc  Build ASTs then convert to LLVM, emit .bc file
 ! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
Index: flang/test/CMakeLists.txt
===
--- flang/test/CMakeLists.txt
+++ flang/test/CMakeLists.txt
@@ -55,6 +55,7 @@
   fir-opt
   tco
   bbc
+  llvm-dis
   llvm-objdump
   split-file
 )
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -37,6 +37,8 @@
 return std::make_unique();
   case EmitLLVM:
 return std::make_unique();
+  case EmitLLVMBitcode:
+return std::make_unique();
   case EmitObj:
 return std::make_unique(
 BackendAction::BackendActionTy::Backend_EmitObj);
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -33,6 +33,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/TargetTransformInfo.h"
+#include "llvm/Bitcode/BitcodeWriterPass.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Passes/PassBuilder.h"
@@ -472,6 +473,49 @@
   llvmModule->print(*os, /*AssemblyAnnotationWriter=*/nullptr);
 }
 
+void EmitLLVMBitcodeAction::ExecuteAction() {
+  CompilerInstance &ci = this->instance();
+  // Generate an LLVM module if it's not already present (it will already be
+  // present if the input file is an LLVM IR/BC file).
+  if (!llvmModule)
+GenerateLLVMIR();
+
+  // Create and configure `Target`
+  std::string error;
+  std::string theTriple = llvmModule->getTargetTriple();
+  const llvm::Target *theTarget =
+  llvm::TargetRegistry::lookupTarget(theTriple, error);
+  assert(theTarget && "Failed to create Target");
+
+  // Create and configure `TargetMachine`
+  std::unique_ptr TM;
+
+  TM.reset(theTarget->createTargetMachine(theTriple, /*CPU=*/"",
+  /*Features=*/"", llvm::TargetOptions(), llvm::None));
+  assert(TM && "Failed to create TargetMachine");
+  llvmModule->setDataLayout(TM->createDataLayout());
+
+  // Generate an output file
+  std::unique_ptr os = ci.CreateDefaultOutputFile(
+  /*Binary=*/true, /*InFile=*/GetCurrentFileOrBufferName(), "bc");
+  if (!os) {
+unsigned diagID = ci.diagnostics().getCustomDiagID(
+clang::DiagnosticsEngine::Error, "failed to create the output file");
+ci.diagnostics().Report(diagID);
+return;
+  }
+
+  // Set-up the pass manager
+  llvm::ModulePassManager MPM;
+  llvm::ModuleAnalysisManager MAM;
+  llvm::PassBuilder PB(TM.get());
+  PB.registerModuleAnalyses(MAM);
+  MPM.addPass(llvm::BitcodeWriterPass(*os));
+
+  // Run the passes
+  MPM.run(*llvmModule, MAM);
+}
+
 void EmitMLIRAction::ExecuteAction() {
   CompilerInstance &ci = this->instance();
 
Index: flang/lib/Frontend/CompilerInvocation.cpp
==

[PATCH] D123211: [flang][driver] Add support for generating LLVM bytecode files

2022-04-06 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:483
+
+  llvm::ModulePassManager MPM;
+  llvm::ModuleAnalysisManager MAM;

rovka wrote:
> Nit: I think you can move these closer to their first use.
Thanks, I thought that I _did_ move it :)



Comment at: flang/test/CMakeLists.txt:58
   bbc
+  llvm-dis
   llvm-objdump

rovka wrote:
> Were you going to add a test that uses this?
Sorry, forgot to add in the original revision. Should be there now.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123211/new/

https://reviews.llvm.org/D123211

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123211: [flang][driver] Add support for generating LLVM bytecode files

2022-04-06 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Thanks for taking a look Diana!

> Why not use the BackendAction for this?

This action only requires the middle-end in LLVM :) The `BackendAction` will 
use the backend, but that's not needed here.

> There seems to be a lot of shared code, up until the point where you create 
> and use the pass manager

This is the bit that's shared:

  CompilerInstance &ci = this->instance();
  // Generate an LLVM module if it's not already present (it will already be
  // present if the input file is an LLVM IR/BC file).
  if (!llvmModule)
GenerateLLVMIR();
  
  // Create and configure `Target`
  std::string error;
  std::string theTriple = llvmModule->getTargetTriple();
  const llvm::Target *theTarget =
  llvm::TargetRegistry::lookupTarget(theTriple, error);
  assert(theTarget && "Failed to create Target");
  
  // Create and configure `TargetMachine`
  std::unique_ptr TM;
  
  TM.reset(theTarget->createTargetMachine(theTriple, /*CPU=*/"",
  /*Features=*/"", llvm::TargetOptions(), llvm::None));
  assert(TM && "Failed to create TargetMachine");
  llvmModule->setDataLayout(TM->createDataLayout());

I wouldn't say it's "a lot", but probably enough for a dedicated method. I've 
been conservative with regard to sharing code as I anticipate things to change 
in the future (I expect `-O{0|1|2|3|s|z}` to complicate the logic a bit).

> (and in the future, when the backend switches to the new pass manager, there 
> will be even more shared code).

I'm not sure about the timelines for this. And even then, the logic might be 
quite different (again, middle-end vs back-end).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123211/new/

https://reviews.llvm.org/D123211

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D130513: [Flang] Add -fconvert option to swap endianness for unformatted files

2022-07-26 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Thanks for working on this. This is not my area of expertise, so I focused on 
the implementation in the driver.




Comment at: clang/include/clang/Driver/Options.td:4897
 def ffixed_line_length_VALUE : Joined<["-"], "ffixed-line-length-">, 
Group, Alias;
+def fconvert_EQ : Joined<["-"], "fconvert=">, Group,
+  HelpText<"Set endian conversion of data for unformatted files">;

jpenix-quic wrote:
> peixin wrote:
> > Why do you move it here? Maybe it is not implemented now, clang may need 
> > this option eventually. @MaskRay 
> I was using the fixed line length options as a reference for how to handle 
> this--based on the discussion in the review here 
> (https://reviews.llvm.org/D95460) about forwarding options to gfortran, I was 
> thinking that it would also be safe to handle fconvert similarly, but I'm not 
> 100% sure and definitely might be misunderstanding something!
GFortran support has been effectively broken since LLVM 12 (see e.g. this [[ 
https://github.com/llvm/llvm-project/commit/6a75496836ea14bcfd2f4b59d35a1cad4ac58cee
 | change ]]). We would do ourselves a favor if we just removed it altogether 
(I'm not aware of anyone requiring  it). 

And if Clang ever needs this option, we can always update this definition 
accordingly. No need to optimize for hypothetical scenarios that may or may not 
happen :) To me, this change makes perfect sense.



Comment at: clang/lib/Driver/ToolChains/Flang.cpp:52
+options::OPT_fno_automatic,
+options::OPT_fconvert_EQ});
 }

jpenix-quic wrote:
> Reading through https://reviews.llvm.org/D95460 again, I'm not sure this is 
> the appropriate place to add . I am marking this as a TODO that I will 
> revisit with the other feedback!
You can use `AddOtherOptions` instead. `AddFortranDialectOptions` is more about 
language options. Is this a language option? It's a bit of a borderline. Feel 
free to add another hook too.

Btw, the reformatting is an unrelated change. Could you submit in a separate 
patch? Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D130513/new/

https://reviews.llvm.org/D130513

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D131533: [Flang][Driver] Enable PIC in the frontend

2022-08-10 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Many thanks for implementing this! I've only skimmed through so far, but mostly 
makes sense. Will take a closer look later.

Could you update the summary by adding more detail? What options are enabled 
and whether the semantics from Clang are preserved or not (they should unless 
there is a good reason not to)? It would help if you could list all of them. 
More comments inline.




Comment at: clang/include/clang/Driver/Options.td:5954-5959
+def mrelocation_model : Separate<["-"], "mrelocation-model">,
+  HelpText<"The relocation model to use">, 
Values<"static,pic,ropi,rwpi,ropi-rwpi,dynamic-no-pic">,
+  Flags<[CC1Option, CC1AsOption, FC1Option, NoDriverOption]>,
+  NormalizedValuesScope<"llvm::Reloc">,
+  NormalizedValues<["Static", "PIC_", "ROPI", "RWPI", "ROPI_RWPI", 
"DynamicNoPIC"]>,
+  MarshallingInfoEnum, "PIC_">;

As per comments in Options.td, this is a "Code-gen Option" rather than a 
"Language Option". Could you move it back somewhere near the original [[ 
https://github.com/llvm/llvm-project/blob/e5e93b6130bde96d7e14851e218c5bf055f8a834/clang/include/clang/Driver/Options.td#L5231-L5233
 | comment ]]?

I would also suggest using `let` (there's going to be more options like this):
```
let Flags = [CC1Option, CC1AsOption, FC1Option, NoDriverOption] {

def mrelocation_model : Separate<["-"], "mrelocation-model">,
  HelpText<"The relocation model to use">, 
Values<"static,pic,ropi,rwpi,ropi-rwpi,dynamic-no-pic">,
  NormalizedValuesScope<"llvm::Reloc">,
  NormalizedValues<["Static", "PIC_", "ROPI", "RWPI", "ROPI_RWPI", 
"DynamicNoPIC"]>,
  MarshallingInfoEnum, "PIC_">;

} // let Flags = [CC1Option, CC1AsOption, FC1Option, NoDriverOption]
```



Comment at: clang/include/clang/Driver/Options.td:6320-6325
+def pic_level : Separate<["-"], "pic-level">,
+  HelpText<"Value for __PIC__">,
+  MarshallingInfoInt>;
+def pic_is_pie : Flag<["-"], "pic-is-pie">,
+  HelpText<"File is for a position independent executable">,
+  MarshallingInfoFlag>;

These are code-gen options to me. While originally located under "Language 
Options", I think that it would make more sense to move them near "CodeGen 
Options" instead (e.g. near `mrelocation_model`). @MaskRay any thoughts?



Comment at: clang/lib/Driver/ToolChains/Flang.cpp:120
 
+  // -fPIC/-fPIE and their variants. Similar to clang.
+  llvm::Reloc::Model RelocationModel;

I would skip "Similar to clang" - this applies most of things here.



Comment at: flang/test/Driver/pic-flags.f90:1
 ! Verify that in contrast to Clang, Flang does not default to generating 
position independent executables/code
 

This comment is no longer valid



Comment at: flang/test/Driver/pic-flags.f90:3
 
-! RUN: %flang -### %s --target=aarch64-linux-gnu 2>&1 | FileCheck %s 
--check-prefix=CHECK-NOPIE
-! RUN: %flang -### %s --target=aarch64-linux-gnu -fno-pie 2>&1 | FileCheck %s 
--check-prefix=CHECK-NOPIE
-
-! RUN: %flang -### %s --target=aarch64-linux-gnu -fpie 2>&1 | FileCheck %s 
--check-prefix=CHECK-PIE
-
-! CHECK-NOPIE: "-fc1"
-! CHECk-NOPIE-NOT: "-fpic"
-! CHECK-NOPIE: "{{.*}}ld"
-! CHECK-NOPIE-NOT: "-pie"
-
-! CHECK-PIE: "-fc1"
-!! TODO Once Flang supports `-fpie`, it //should// use -fpic when invoking 
`flang -fc1`. Update the following line once `-fpie` is
-! available.
-! CHECk-PIE-NOT: "-fpic"
-! CHECK-PIE: "{{.*}}ld"
-! CHECK-PIE-NOT: "-pie"
+! RUN: %flang -v -S -emit-llvm -o - %s --target=aarch64-linux-gnu -fno-pie 
2>&1 | FileCheck %s --check-prefix=CHECK-NOPIE
+

Why would you replace `-###` with `-v`? Same for other RUN lines. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D131533/new/

https://reviews.llvm.org/D131533

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D106137: [flang][driver] Add support for Frontend Plugins

2021-07-16 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

@stuartellis , thank you for working on this! I've left a few comments - mostly 
nits.




Comment at: flang/examples/HelloWorld/CMakeLists.txt:1-5
+add_llvm_library(
+flangHelloWorldPlugin
+MODULE
+HelloWorldPlugin.cpp
+)

I think that this should be fine as is, but will not work on Windows. Check 
this example: [[ 
https://github.com/llvm/llvm-project/blob/main/clang/examples/PrintFunctionNames/CMakeLists.txt
 | PrintFunctionNames ]]. I think that it's fine not to support Windows for 
now, but we should document this. Also, your tests need to marked as Linux-only 
(e.g. with `// REQUIRES: shell` or something similar).



Comment at: flang/examples/HelloWorld/HelloWorldPlugin.cpp:1
+#include "flang/Frontend/FrontendActions.h"
+#include "flang/Frontend/FrontendPluginRegistry.h"

Missing LLVM file header: 
https://llvm.org/docs/CodingStandards.html#file-headers



Comment at: flang/include/flang/Frontend/FrontendPluginRegistry.h:27
+#endif // LLVM_FLANG_FRONTEND_FRONTENDPLUGINREGISTRY_H
\ No newline at end of file


FIXME



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:202
 
+  if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) {
+opts.plugins.push_back(a->getValue());

[nit] Perhaps worth adding a comment to highlight _which_ option is being 
parsed?



Comment at: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp:87
+  if (plugin.getName() == ci.frontendOpts().ActionName) {
+std::unique_ptr P(plugin.instantiate());
+return std::move(P);

Lower case `P`



Comment at: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp:92
+unsigned diagID = ci.diagnostics().getCustomDiagID(
+clang::DiagnosticsEngine::Error, "unable to find plugin '%0'");
+ci.diagnostics().Report(diagID) << ci.frontendOpts().ActionName;

Could you add a test for this diagnostic?



Comment at: flang/test/Driver/plugin-example.f90:7
+! RUN: %flang_fc1 -load %llvmshlibdir/flangHelloWorldPlugin%pluginext -plugin 
-hello-world %s 2>&1 | FileCheck %s
+! CHECK: Hello World from your new plugin

[tiny nit] Could you make it Flang specific? E.g. `Hello World from your new 
Flang plugin`



Comment at: flang/test/lit.cfg.py:55
+# Plugins (loadable modules)
+if config.has_plugins and config.llvm_plugin_ext:
+config.available_features.add('plugins')

Could `llvm_plugin_ext` be ever empty? Perhaps I'm missing something, but it 
feels that `if config.has_plugins` should be sufficient here.



Comment at: flang/tools/flang-driver/CMakeLists.txt:30
 
+export_executable_symbols_for_plugins(flang-new)
+

We should make it possible to turn this off, perhaps:
```lang=clamg
# Some clever comment
if(FLANG_PLUGIN_SUPPORT)
  export_executable_symbols_for_plugins(flang-new)
endif()
```


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D106137/new/

https://reviews.llvm.org/D106137

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105881: [flang][driver] Switch to `BoolFOption` for boolean options

2021-07-20 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Apologies, it has taken me a bit longer to get back to this. @jansvoboda11 , 
now I'm realising the key disadvantage of using `OptInFFlag/OptOutFFlag` - it's 
impossible to express the `opt-in`/`opt-out` semantics in TableGen. In fact, 
only the contents of `clang -cc1 --help` are being tweaked by using 
`OptInFFlag/OptOutFFlag`. Basically:

- for `OptInFFlang`, only `-ffoo` is printed with `-clang -cc1 --help` (the 
help text for `-ffno-foo` becomes irrelevant)
- for `OptOutFFlang`, only `-fno-foo` is printed with `-clang -cc1 --help` (the 
help text for `-ffoo` is irrelevant)

IIUC, this is achieved through `flags` (`CC1Option` vs `[]`). In Flang, we rely 
on the fact that "no help text? don't include it in `flang-new -fc1 --help`" 
instead. This behavior is implemented in `clangDriver` and applies to all 
drivers that use it (so this is nothing specific to Flang). This way, we can 
always mark Flang options with the relevant flags (e.g. `FC1Option`). In other 
words, we can claim them and make it clear that other drivers can ignore them. 
In general, I think that Options.td would become a bit cleaner and easier to 
reason about if all options specified all their flags. That wouldn't be easy to 
achieve though!

I'm just about send an updated patch. It takes into account the points that I 
raised above ^^^. It also fixes the failing tests reported by @PeteSteinfeld. 
Does this new approach work for Clang (I quickly tested `clang -cc1 --help` and 
see no difference)?

It would be nicer to have the `opt-in`/`opt-out` semantics for Flang in 
TableGen through something similar to `BoolFOption`. No need for this just now 
- one step at a time :)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D105881/new/

https://reviews.llvm.org/D105881

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105881: [flang][driver] Switch to `BoolFOption` for boolean options

2021-07-20 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 360100.
awarzynski added a comment.

Switch from `BoolFOption` to `OptInFFlag`/`OptOutFFlag`

I've refactored `OptInFFlag`/`OptOutFFlag` a tiny bit and created 
specialisations for `clang -cc1` (`OptInCC1FFlag`/`OptOutCC1FFlag`). I have 
added some comments in Options.td to clarify the semantics of 
`OptInFFlag`/`OptOutFFlag`. Does this make sense to you?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D105881/new/

https://reviews.llvm.org/D105881

Files:
  clang/include/clang/Driver/Options.td
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90

Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -40,7 +40,6 @@
 ! HELP-NEXT:Specify where to find the compiled intrinsic modules
 ! HELP-NEXT: -flarge-sizes  Use INTEGER(KIND=8) for the result type in size-related intrinsics
 ! HELP-NEXT: -flogical-abbreviations Enable logical abbreviations
-! HELP-NEXT: -fno-color-diagnostics Disable colors in diagnostics
 ! HELP-NEXT: -fopenacc  Enable OpenACC
 ! HELP-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
 ! HELP-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
@@ -68,6 +67,8 @@
 ! HELP-FC1-NEXT: -E Only run the preprocessor
 ! HELP-FC1-NEXT: -falternative-parameter-statement
 ! HELP-FC1-NEXT: Enable the old style PARAMETER statement
+! HELP-FC1-NEXT: -fanalyzed-objects-for-unparse
+! HELP-FC1-NEXT:Use the analyzed objects when unparsing
 ! HELP-FC1-NEXT: -fbackslashSpecify that backslash in string introduces an escape character
 ! HELP-FC1-NEXT: -fdebug-dump-all   Dump symbols and the parse tree after the semantic checks
 ! HELP-FC1-NEXT: -fdebug-dump-parse-tree-no-sema
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -40,7 +40,6 @@
 ! CHECK-NEXT:Specify where to find the compiled intrinsic modules
 ! CHECK-NEXT: -flarge-sizes  Use INTEGER(KIND=8) for the result type in size-related intrinsics
 ! CHECK-NEXT: -flogical-abbreviations Enable logical abbreviations
-! CHECK-NEXT: -fno-color-diagnostics Disable colors in diagnostics
 ! CHECK-NEXT: -fopenacc  Enable OpenACC
 ! CHECK-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
 ! CHECK-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
Index: flang/lib/Frontend/CompilerInvocation.cpp
===
--- flang/lib/Frontend/CompilerInvocation.cpp
+++ flang/lib/Frontend/CompilerInvocation.cpp
@@ -277,33 +277,27 @@
 }
   }
 
-  if (const llvm::opt::Arg *arg =
-  args.getLastArg(clang::driver::options::OPT_fimplicit_none,
-  clang::driver::options::OPT_fno_implicit_none)) {
-opts.features_.Enable(
-Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
-arg->getOption().matches(clang::driver::options::OPT_fimplicit_none));
-  }
-  if (const llvm::opt::Arg *arg =
-  args.getLastArg(clang::driver::options::OPT_fbackslash,
-  clang::driver::options::OPT_fno_backslash)) {
-opts.features_.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
-arg->getOption().matches(clang::driver::options::OPT_fbackslash));
-  }
-  if (const llvm::opt::Arg *arg =
-  args.getLastArg(clang::driver::options::OPT_flogical_abbreviations,
-  clang::driver::options::OPT_fno_logical_abbreviations)) {
-opts.features_.Enable(
-Fortran::common::LanguageFeature::LogicalAbbreviations,
-arg->getOption().matches(
-clang::driver::options::OPT_flogical_abbreviations));
-  }
-  if (const llvm::opt::Arg *arg =
-  args.getLastArg(clang::driver::options::OPT_fxor_operator,
-  clang::driver::options::OPT_fno_xor_operator)) {
-opts.features_.Enable(Fortran::common::LanguageFeature::XOROperator,
-arg->getOption().matches(clang::driver::options::OPT_fxor_operator));
-  }
+  // -f{no-}implicit-none
+  opts.features_.Enable(
+  Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
+  args.hasFlag(clang::driver::options::OPT_fimplicit_none,
+  clang::driver::options::OPT_fno_implicit_none, false));
+
+  // -f{no-}backslash
+  opts.features_.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
+  args.hasFlag(clang::driver::options::OPT_fbackslash,
+  clang::driver::options::OPT_fno_backslash, false));
+
+  // -f{no-}logical-abbreviations
+  opts.features_.Enable(Fortran::common::LanguageF

[PATCH] D105881: [flang][driver] Switch to `BoolFOption` for boolean options

2021-07-27 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Thank you for your detailed reply!

In D105881#2904699 , @jansvoboda11 
wrote:

> Sorry, I'm not sure I follow.

OK, let me try to clarify. I've tried to split this into threads.

(flag == OptionFlag 

 )

**SEMANTICS**

> In D105881#2890134 , @awarzynski 
> wrote:
>
>> @jansvoboda11 , now I'm realising the key disadvantage of using 
>> `OptInFFlag/OptOutFFlag` - it's impossible to express the `opt-in`/`opt-out` 
>> semantics in TableGen.
>
> What do you mean exactly?

BoolOption 

 (from which BoolFOption 

 derives) has e.g. the `default` value and a bunch of `assert`s to define the 
relation between `-ffoo` and `-fno-foo`. So effectively, the opt-in/opt-out 
semantics are enforced here. `OptInFFlag`/`OptOutFFlag` have none of this. It's 
just a syntactic sugar to automate the generation of `-ffoo` and `-fno-foo`. 
That's fine, we can add such checks inside the driver.

**CC1Option**

> I think the semantics are expressed pretty well from Clang's point of view:

OK, that's fair enough. But what about the output from `clang --help` and 
`clang -cc1 --help`? Let's look at -feliminate-unused-debug-types 

 (the only instance of `OptOutFFLag`):

  # Only -fno-eliminate-unusued-debug-types is printed
  clang -cc1 --help | grep eliminate-unused
-fno-eliminate-unused-debug-types
  # Both -fno-eliminate-unusued-debug-types and -feliminate-unusued-debug-types 
printed?
  clang --help | grep eliminate-unused
-feliminate-unused-debug-types
-fno-eliminate-unused-debug-types

To me this behavior is counter-intuitive. So are these `clang` options? `clang 
-cc1` options? Both? What's the point of adding `CC1Option` if both `clang` and 
`clang -cc1` accept them. The definition of `CC1Option` from Options.td:

  // CC1Option - This option should be accepted by clang -cc1.
  def CC1Option : OptionFlag;

OK, so currently `-fno-eliminate-unused-debug-types` is a `CC1Option` and 
_should_ be accepted by `clang -cc1`. How about 
`-feliminate-unused-debug-types`?

  clang -cc1 -feliminate-unused-debug-types file.c
  error: unknown argument: '-feliminate-unused-debug-types'

Makes sense, but:

  clang -c -feliminate-unused-debug-types file.c
  clang-13: warning: argument unused during compilation: 
'-feliminate-unused-debug-types' [-Wunused-command-line-argument]

Shouldn't it be rejected by `clang` with an error as well? Shouldn't 
`CC1Option` be used consistently for `-feliminate-unused-debug-types`  and 
`-fno-eliminate-unused-debug-types`?

>> In fact, only the contents of `clang -cc1 --help` are being tweaked by using 
>> `OptInFFlag/OptOutFFlag`.
>
> That's incorrect, `OptInFFlag` and `OptOutFFlag` both set `HelpText` for the 
> positive and negative driver flags.

Yes, but in `clang --cc1 --help`, only the variant with `CC1Option` is being 
printed and the other one is ignored. So why bother adding the other one?

Btw, now I see that `-cc1` does reject `-feliminate-unused-debug-types`, so 
it's not only about the contents of `clang -cc1 --help`. I was wrong, sorry 
about that and thanks for pointing this out!

**Content of `--help`**

>> In Flang, we rely on the fact that "no help text? don't include it in 
>> `flang-new -fc1 --help`" instead. This behavior is implemented in 
>> `clangDriver` and applies to all drivers that use it (so this is nothing 
>> specific to Flang).
>
> I see. Is this intentional?
>
>> This way, we can always mark Flang options with the relevant flags (e.g. 
>> `FC1Option`). In other words, we can claim them and make it clear that other 
>> drivers can ignore them.
>
> I don't understand this. Can you elaborate? Are you relying on the 
> absence/presence of a help text to mark flags with `FC1Option`? When does 
> this happen? (In `Options.td`? The TableGen backend? The consumer of 
> `Options.inc`?)

See the implementation of printHelp 

 from OptTable.cpp. Basically: "No help text? Not printing". We rely on this 
**not to print** options supported by Flang, but for which we have no help 
text. We only used that for boolean options (so we have a help text for e.g. 
`-ffoo`, but not for `-fno-foo`). This is a minor thing and I am not concerned 
about loosing it.

As for `FC1Option` (and `FlangOption`), we always add these explicitly in 
Opt

[PATCH] D106137: [flang][driver] Add support for Frontend Plugins

2021-07-27 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

I think that this is almost ready to be merged. Just a couple more comments.




Comment at: flang/examples/CMakeLists.txt:1
 # This test is not run by default as it requires input.
 add_executable(external-hello-world

Could you add the following at the top of this file:
```
if(NOT FLANG_BUILD_EXAMPLES)
  set(EXCLUDE_FROM_ALL ON)
endif()
```
This will make sure that the examples are not build with e.g. `ninja` when 
`FLANG_BUILD_EXAMPLES` is `Off`.

In [[ 
https://github.com/llvm/llvm-project/blob/43e45f0ec920b45d6073c0aff47597c44948f52c/clang/examples/CMakeLists.txt#L1-L4
 | Clang ]], CMake also contains 
```  set_property(DIRECTORY PROPERTY EXCLUDE_FROM_ALL ON)
```
I think that `set(EXCLUDE_FROM_ALL ON)` should be sufficient though (see [[ 
https://cmake.org/cmake/help/latest/prop_tgt/EXCLUDE_FROM_ALL.html#prop_tgt:EXCLUDE_FROM_ALL
 | CMake ]]  docs for `EXCLUDE_FROM_ALL`). 

Note  that in LLVM, there is [[ 
https://github.com/llvm/llvm-project/blob/43e45f0ec920b45d6073c0aff47597c44948f52c/llvm/cmake/modules/AddLLVM.cmake#L1264-L1273
 | add_llvm_example_library ]]. It would be nice to use that, be we'd need to 
make sure that `LLVM_BUILD_EXAMPLES` is set correctly. But that's not required 
just now and could be added later.



Comment at: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp:147
+  // If there were errors in processing arguments, don't do anything else.
+  if (flang->diagnostics().hasErrorOccurred())
+return false;

This will silence this warning:
```
if (flang->diagnostics().hasErrorOccurred()) {
return false;
}
```


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D106137/new/

https://reviews.llvm.org/D106137

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120568: [flang][driver] Add support for -S and implement -c/-emit-obj

2022-03-09 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 414043.
awarzynski added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D120568/new/

https://reviews.llvm.org/D120568

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/lib/Optimizer/Support/FIRContext.cpp
  flang/test/CMakeLists.txt
  flang/test/Driver/code-gen-aarch64.f90
  flang/test/Driver/code-gen-x86.f90
  flang/test/Driver/code-gen.f90
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-asm-aarch64.f90
  flang/test/Driver/emit-asm-x86.f90
  flang/test/Driver/syntax-only.f90
  flang/test/Fir/target-rewrite-triple.fir
  flang/test/lit.cfg.py
  flang/test/lit.site.cfg.py.in
  flang/tools/flang-driver/fc1_main.cpp
  flang/unittests/Frontend/CMakeLists.txt
  flang/unittests/Frontend/FrontendActionTest.cpp

Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -11,6 +11,7 @@
 #include "flang/Frontend/FrontendOptions.h"
 #include "flang/FrontendTool/Utils.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/raw_ostream.h"
 
 #include "gtest/gtest.h"
@@ -188,4 +189,35 @@
   EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
   .contains("define void @_QQmain()"));
 }
+
+TEST_F(FrontendActionTest, EmitAsm) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitAssembly;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Initialise LLVM backend
+  llvm::InitializeAllTargets();
+  llvm::InitializeAllTargetMCs();
+  llvm::InitializeAllAsmPrinters();
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data()).contains("_QQmain"));
+}
 } // namespace
Index: flang/unittests/Frontend/CMakeLists.txt
===
--- flang/unittests/Frontend/CMakeLists.txt
+++ flang/unittests/Frontend/CMakeLists.txt
@@ -1,3 +1,7 @@
+set(LLVM_LINK_COMPONENTS
+  ${LLVM_TARGETS_TO_BUILD}
+)
+
 add_flang_unittest(FlangFrontendTests
   CompilerInstanceTest.cpp
   FrontendActionTest.cpp
Index: flang/tools/flang-driver/fc1_main.cpp
===
--- flang/tools/flang-driver/fc1_main.cpp
+++ flang/tools/flang-driver/fc1_main.cpp
@@ -20,6 +20,7 @@
 #include "llvm/Option/Arg.h"
 #include "llvm/Option/ArgList.h"
 #include "llvm/Option/OptTable.h"
+#include "llvm/Support/TargetSelect.h"
 
 #include 
 
@@ -48,6 +49,11 @@
   bool success =
   CompilerInvocation::CreateFromArgs(flang->invocation(), argv, diags);
 
+  // Initialize targets first, so that --version shows registered targets.
+  llvm::InitializeAllTargets();
+  llvm::InitializeAllTargetMCs();
+  llvm::InitializeAllAsmPrinters();
+
   diagsBuffer->FlushDiagnostics(flang->diagnostics());
 
   if (!success)
Index: flang/test/lit.site.cfg.py.in
===
--- flang/test/lit.site.cfg.py.in
+++ flang/test/lit.site.cfg.py.in
@@ -18,6 +18,7 @@
 config.flang_standalone_build = @FLANG_STANDALONE_BUILD@
 config.has_plugins = @LLVM_ENABLE_PLUGINS@
 config.cc = "@CMAKE_C_COMPILER@"
+config.targets_to_build = "@TARGETS_TO_BUILD@"
 
 # Support substitution of the tools_dir with user parameters. This is
 # used when we can't determine the tool dir at configuration time.
Index: flang/test/lit.cfg.py
===
--- flang/test/lit.cfg.py
+++ flang/test/lit.cfg.py
@@ -39,6 +39,11 @@
 llvm_config.feature_config(
 [('--assertion-mode', {'ON': 'asserts'})])
 
+# Targets
+config.targets = frozenset(config.targets_to_build.split())
+for arch in config.targets_to_build.split():
+config.available_features.add(arch.lower() + '-registered-target')
+
 # excludes: A list of directories to exclude from t

[PATCH] D120568: [flang][driver] Add support for -S and implement -c/-emit-obj

2022-03-09 Thread Andrzej Warzynski via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG38101b4e95aa: [flang][driver] Add support for -S and 
implement -c/-emit-obj (authored by awarzynski).

Changed prior to commit:
  https://reviews.llvm.org/D120568?vs=414043&id=414102#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D120568/new/

https://reviews.llvm.org/D120568

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/lib/Optimizer/Support/FIRContext.cpp
  flang/test/CMakeLists.txt
  flang/test/Driver/code-gen-aarch64.f90
  flang/test/Driver/code-gen-x86.f90
  flang/test/Driver/code-gen.f90
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-asm-aarch64.f90
  flang/test/Driver/emit-asm-x86.f90
  flang/test/Driver/syntax-only.f90
  flang/test/Fir/target-rewrite-triple.fir
  flang/test/lit.cfg.py
  flang/test/lit.site.cfg.py.in
  flang/tools/flang-driver/fc1_main.cpp
  flang/unittests/Frontend/CMakeLists.txt
  flang/unittests/Frontend/FrontendActionTest.cpp

Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -11,6 +11,7 @@
 #include "flang/Frontend/FrontendOptions.h"
 #include "flang/FrontendTool/Utils.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/raw_ostream.h"
 
 #include "gtest/gtest.h"
@@ -188,4 +189,35 @@
   EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
   .contains("define void @_QQmain()"));
 }
+
+TEST_F(FrontendActionTest, EmitAsm) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitAssembly;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Initialise LLVM backend
+  llvm::InitializeAllTargets();
+  llvm::InitializeAllTargetMCs();
+  llvm::InitializeAllAsmPrinters();
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data()).contains("_QQmain"));
+}
 } // namespace
Index: flang/unittests/Frontend/CMakeLists.txt
===
--- flang/unittests/Frontend/CMakeLists.txt
+++ flang/unittests/Frontend/CMakeLists.txt
@@ -1,3 +1,7 @@
+set(LLVM_LINK_COMPONENTS
+  ${LLVM_TARGETS_TO_BUILD}
+)
+
 add_flang_unittest(FlangFrontendTests
   CompilerInstanceTest.cpp
   FrontendActionTest.cpp
Index: flang/tools/flang-driver/fc1_main.cpp
===
--- flang/tools/flang-driver/fc1_main.cpp
+++ flang/tools/flang-driver/fc1_main.cpp
@@ -20,6 +20,7 @@
 #include "llvm/Option/Arg.h"
 #include "llvm/Option/ArgList.h"
 #include "llvm/Option/OptTable.h"
+#include "llvm/Support/TargetSelect.h"
 
 #include 
 
@@ -48,6 +49,11 @@
   bool success =
   CompilerInvocation::CreateFromArgs(flang->invocation(), argv, diags);
 
+  // Initialize targets first, so that --version shows registered targets.
+  llvm::InitializeAllTargets();
+  llvm::InitializeAllTargetMCs();
+  llvm::InitializeAllAsmPrinters();
+
   diagsBuffer->FlushDiagnostics(flang->diagnostics());
 
   if (!success)
Index: flang/test/lit.site.cfg.py.in
===
--- flang/test/lit.site.cfg.py.in
+++ flang/test/lit.site.cfg.py.in
@@ -18,6 +18,7 @@
 config.flang_standalone_build = @FLANG_STANDALONE_BUILD@
 config.has_plugins = @LLVM_ENABLE_PLUGINS@
 config.cc = "@CMAKE_C_COMPILER@"
+config.targets_to_build = "@TARGETS_TO_BUILD@"
 
 # Support substitution of the tools_dir with user parameters. This is
 # used when we can't determine the tool dir at configuration time.
Index: flang/test/lit.cfg.py
===
--- flang/test/lit.cfg.py
+++ flang/test/lit.cfg.py
@@ -39,6

[PATCH] D121374: [flang][driver] Add support for `-mllvm`

2022-03-10 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski created this revision.
awarzynski added reviewers: rovka, schweitz, Leporacanthicus, 
kiranchandramohan, shraiysh.
Herald added a reviewer: sscalpone.
Herald added a subscriber: dang.
Herald added projects: Flang, All.
awarzynski requested review of this revision.
Herald added subscribers: cfe-commits, jdoerfert.
Herald added a project: clang.

This option is added in both `flang-new` (the compiler driver) and
`flang-new -fc1` (the frontend driver). The semantics are consistent
with `clang` and `clang -cc1`.

As Flang does not run any LLVM passes when invoked with `-emit-llvm`
(i.e. `flang-new -S -emit-llvm `), the tests use
`-S`/`-c`/`-emit-obj` instead. These options require an LLVM backend to
be run by the driver to generate the output (this makese `-mllvm`
relevant here).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121374

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/mllvm.f90

Index: flang/test/Driver/mllvm.f90
===
--- /dev/null
+++ flang/test/Driver/mllvm.f90
@@ -0,0 +1,32 @@
+! Test the `-mlvm` option
+
+!
+! RUN COMMAND
+!
+! 1. Test typical usage.
+! RUN: %flang -S -mllvm -print-before-all %s -o - 2>&1 | FileCheck %s --check-prefix=OUTPUT
+! RUN: %flang_fc1 -S -mllvm -print-before-all %s -o - 2>&1 | FileCheck %s --check-prefix=OUTPUT
+
+! 2. Does the option forwarding from `flang-new` to `flang-new -fc1` work?
+! RUN: %flang -### -S -mllvm -print-before-all %s -o - 2>&1 | FileCheck %s --check-prefix=OPTION_FORWARDING
+
+! 3. Test invalid usage (`-print-before` requires an argument)
+! RUN: not %flang -S -mllvm -print-before %s -o - 2>&1 | FileCheck %s --check-prefix=INVALID_USAGE
+
+!
+! EXPECTED OUTPUT
+!
+! OUTPUT: *** IR Dump Before Pre-ISel Intrinsic Lowering (pre-isel-intrinsic-lowering) ***
+! OUTPUT-NEXT: ; ModuleID = 'FIRModule'
+! OUTPUT-NEXT: source_filename = "FIRModule"
+
+! Verify that `-mllvm ` is forwarded to flang -fc1
+! OPTION_FORWARDING: flang-new" "-fc1"
+! OPTION_FORWARDING-SAME: "-mllvm" "-print-before-all"
+
+! INVALID_USAGE: flang (LLVM option parsing): for the --print-before option: requires a value!
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -47,6 +47,7 @@
 ! HELP-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
 ! HELP-NEXT: -help  Display available options
 ! HELP-NEXT: -IAdd directory to the end of the list of include search paths
+! HELP-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
 ! HELP-NEXT: -module-dir   Put MODULE files in 
 ! HELP-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! HELP-NEXT: -o   Write output to 
@@ -121,6 +122,7 @@
 ! HELP-FC1-NEXT: -init-only Only execute frontend initialization
 ! HELP-FC1-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-FC1-NEXT: -load Load the named plugin (dynamic shared object)
+! HELP-FC1-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
 ! HELP-FC1-NEXT: -module-dir   Put MODULE files in 
 ! HELP-FC1-NEXT: -module-suffix  Use  as the suffix for module files (the default value is `.mod`)
 ! HELP-FC1-NEXT: -nocpp Disable predefined and command line preprocessor macros
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -47,6 +47,7 @@
 ! CHECK-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
 ! CHECK-NEXT: -help Display available options
 ! CHECK-NEXT: -IAdd directory to the end of the list of include search paths
+! CHECK-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
 ! CHECK-NEXT: -module-dir   Put MODULE files in 
 ! CHECK-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! CHECK-NEXT: -o  Write output to 
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -135,6 +135,19 @@
 }
   }
 
+  // Honor -mllvm. This should happen AFTER plugins have been loaded!
+  if (!flang->frontendOpts().llvmArgs.em

[PATCH] D121374: [flang][driver] Add support for `-mllvm`

2022-03-10 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/test/Driver/mllvm.f90:1
+! Test the `-mlvm` option
+

xbolva00 wrote:
> mllvm
Does it matter? `-mllvm` is consistent with other tests in this directory (e.g. 
https://github.com/llvm/llvm-project/blob/main/flang/test/Driver/emit-llvm.f90#L1).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121374/new/

https://reviews.llvm.org/D121374

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121374: [flang][driver] Add support for `-mllvm`

2022-03-10 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/test/Driver/mllvm.f90:1
+! Test the `-mlvm` option
+

xbolva00 wrote:
> awarzynski wrote:
> > xbolva00 wrote:
> > > mllvm
> > Does it matter? `-mllvm` is consistent with other tests in this directory 
> > (e.g. 
> > https://github.com/llvm/llvm-project/blob/main/flang/test/Driver/emit-llvm.f90#L1).
> Just typo “mlvm”
Sorry, I misread that :/ I thought that you meant `mllvm` instead of `-mllvm`. 
My bad, thanks for pointing this out! :)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121374/new/

https://reviews.llvm.org/D121374

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121374: [flang][driver] Add support for `-mllvm`

2022-03-11 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 414648.
awarzynski added a comment.

Fix option spelling in test


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121374/new/

https://reviews.llvm.org/D121374

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/mllvm.f90

Index: flang/test/Driver/mllvm.f90
===
--- /dev/null
+++ flang/test/Driver/mllvm.f90
@@ -0,0 +1,32 @@
+! Test the `-mllvm` option
+
+!
+! RUN COMMAND
+!
+! 1. Test typical usage.
+! RUN: %flang -S -mllvm -print-before-all %s -o - 2>&1 | FileCheck %s --check-prefix=OUTPUT
+! RUN: %flang_fc1 -S -mllvm -print-before-all %s -o - 2>&1 | FileCheck %s --check-prefix=OUTPUT
+
+! 2. Does the option forwarding from `flang-new` to `flang-new -fc1` work?
+! RUN: %flang -### -S -mllvm -print-before-all %s -o - 2>&1 | FileCheck %s --check-prefix=OPTION_FORWARDING
+
+! 3. Test invalid usage (`-print-before` requires an argument)
+! RUN: not %flang -S -mllvm -print-before %s -o - 2>&1 | FileCheck %s --check-prefix=INVALID_USAGE
+
+!
+! EXPECTED OUTPUT
+!
+! OUTPUT: *** IR Dump Before Pre-ISel Intrinsic Lowering (pre-isel-intrinsic-lowering) ***
+! OUTPUT-NEXT: ; ModuleID = 'FIRModule'
+! OUTPUT-NEXT: source_filename = "FIRModule"
+
+! Verify that `-mllvm ` is forwarded to flang -fc1
+! OPTION_FORWARDING: flang-new" "-fc1"
+! OPTION_FORWARDING-SAME: "-mllvm" "-print-before-all"
+
+! INVALID_USAGE: flang (LLVM option parsing): for the --print-before option: requires a value!
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -47,6 +47,7 @@
 ! HELP-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
 ! HELP-NEXT: -help  Display available options
 ! HELP-NEXT: -IAdd directory to the end of the list of include search paths
+! HELP-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
 ! HELP-NEXT: -module-dir   Put MODULE files in 
 ! HELP-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! HELP-NEXT: -o   Write output to 
@@ -121,6 +122,7 @@
 ! HELP-FC1-NEXT: -init-only Only execute frontend initialization
 ! HELP-FC1-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-FC1-NEXT: -load Load the named plugin (dynamic shared object)
+! HELP-FC1-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
 ! HELP-FC1-NEXT: -module-dir   Put MODULE files in 
 ! HELP-FC1-NEXT: -module-suffix  Use  as the suffix for module files (the default value is `.mod`)
 ! HELP-FC1-NEXT: -nocpp Disable predefined and command line preprocessor macros
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -47,6 +47,7 @@
 ! CHECK-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
 ! CHECK-NEXT: -help Display available options
 ! CHECK-NEXT: -IAdd directory to the end of the list of include search paths
+! CHECK-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
 ! CHECK-NEXT: -module-dir   Put MODULE files in 
 ! CHECK-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! CHECK-NEXT: -o  Write output to 
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -135,6 +135,19 @@
 }
   }
 
+  // Honor -mllvm. This should happen AFTER plugins have been loaded!
+  if (!flang->frontendOpts().llvmArgs.empty()) {
+unsigned numArgs = flang->frontendOpts().llvmArgs.size();
+auto args = std::make_unique(numArgs + 2);
+args[0] = "flang (LLVM option parsing)";
+
+for (unsigned i = 0; i != numArgs; ++i)
+  args[i + 1] = flang->frontendOpts().llvmArgs[i].c_str();
+
+args[numArgs + 1] = nullptr;
+llvm::cl::ParseCommandLineOptions(numArgs + 1, args.get());
+  }
+
   // If there were errors in processing arguments, don't do anything else.
   if (flang->diagnostics().hasErrorOccurred()) {
 return false;
Index: flang/lib/Frontend/CompilerInvocation.cpp
=

[PATCH] D121374: [flang][driver] Add support for `-mllvm`

2022-03-16 Thread Andrzej Warzynski via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa7c08bcf777e: [flang][driver] Add support for `-mllvm` 
(authored by awarzynski).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D121374/new/

https://reviews.llvm.org/D121374

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/mllvm.f90

Index: flang/test/Driver/mllvm.f90
===
--- /dev/null
+++ flang/test/Driver/mllvm.f90
@@ -0,0 +1,32 @@
+! Test the `-mllvm` option
+
+!
+! RUN COMMAND
+!
+! 1. Test typical usage.
+! RUN: %flang -S -mllvm -print-before-all %s -o - 2>&1 | FileCheck %s --check-prefix=OUTPUT
+! RUN: %flang_fc1 -S -mllvm -print-before-all %s -o - 2>&1 | FileCheck %s --check-prefix=OUTPUT
+
+! 2. Does the option forwarding from `flang-new` to `flang-new -fc1` work?
+! RUN: %flang -### -S -mllvm -print-before-all %s -o - 2>&1 | FileCheck %s --check-prefix=OPTION_FORWARDING
+
+! 3. Test invalid usage (`-print-before` requires an argument)
+! RUN: not %flang -S -mllvm -print-before %s -o - 2>&1 | FileCheck %s --check-prefix=INVALID_USAGE
+
+!
+! EXPECTED OUTPUT
+!
+! OUTPUT: *** IR Dump Before Pre-ISel Intrinsic Lowering (pre-isel-intrinsic-lowering) ***
+! OUTPUT-NEXT: ; ModuleID = 'FIRModule'
+! OUTPUT-NEXT: source_filename = "FIRModule"
+
+! Verify that `-mllvm ` is forwarded to flang -fc1
+! OPTION_FORWARDING: flang-new" "-fc1"
+! OPTION_FORWARDING-SAME: "-mllvm" "-print-before-all"
+
+! INVALID_USAGE: flang (LLVM option parsing): for the --print-before option: requires a value!
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -47,6 +47,7 @@
 ! HELP-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
 ! HELP-NEXT: -help  Display available options
 ! HELP-NEXT: -IAdd directory to the end of the list of include search paths
+! HELP-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
 ! HELP-NEXT: -module-dir   Put MODULE files in 
 ! HELP-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! HELP-NEXT: -o   Write output to 
@@ -121,6 +122,7 @@
 ! HELP-FC1-NEXT: -init-only Only execute frontend initialization
 ! HELP-FC1-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-FC1-NEXT: -load Load the named plugin (dynamic shared object)
+! HELP-FC1-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
 ! HELP-FC1-NEXT: -module-dir   Put MODULE files in 
 ! HELP-FC1-NEXT: -module-suffix  Use  as the suffix for module files (the default value is `.mod`)
 ! HELP-FC1-NEXT: -nocpp Disable predefined and command line preprocessor macros
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -47,6 +47,7 @@
 ! CHECK-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
 ! CHECK-NEXT: -help Display available options
 ! CHECK-NEXT: -IAdd directory to the end of the list of include search paths
+! CHECK-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
 ! CHECK-NEXT: -module-dir   Put MODULE files in 
 ! CHECK-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! CHECK-NEXT: -o  Write output to 
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -135,6 +135,19 @@
 }
   }
 
+  // Honor -mllvm. This should happen AFTER plugins have been loaded!
+  if (!flang->frontendOpts().llvmArgs.empty()) {
+unsigned numArgs = flang->frontendOpts().llvmArgs.size();
+auto args = std::make_unique(numArgs + 2);
+args[0] = "flang (LLVM option parsing)";
+
+for (unsigned i = 0; i != numArgs; ++i)
+  args[i + 1] = flang->frontendOpts().llvmArgs[i].c_str();
+
+args[numArgs + 1] = nullptr;
+llvm::cl::ParseCommandLineOptions(numArgs + 1, args.get());
+  }
+
   // If there were errors in processing arguments, don't do anything else.
   if (flang->diagnostics().hasErrorOccurred()) {
 return false;
Index: flang/lib/Frontend/

[PATCH] D122008: [flang][driver] Add support for generating executables

2022-03-18 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski created this revision.
awarzynski added reviewers: kiranchandramohan, clementval.
Herald added a subscriber: mgorny.
Herald added a reviewer: sscalpone.
Herald added projects: Flang, All.
awarzynski requested review of this revision.
Herald added subscribers: cfe-commits, jdoerfert.
Herald added a project: clang.

This patch adds 2 missing items required for `flang-new` to be able to
generate executables:

1. Extra linker flags to include Fortran runtime libraries.

2. The Fortran_main runtime library, which implements the main entry point into 
Fortran's PROGRAM.

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

  $ cat hello.f90
  program hello
write (*,*), "hello, world!"
  end program hello
  $ flang-new hello.f90
  ./a.out
  hello, world!

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

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

Co-authored-by: Peter Klausler 
Co-authored-by: Jean Perier 
Co-authored-by: Steve Scalpone https://reviews.llvm.org/D122008

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  flang/include/flang/Runtime/stop.h
  flang/runtime/CMakeLists.txt
  flang/runtime/FortranMain/CMakeLists.txt
  flang/runtime/FortranMain/Fortran_main.c
  flang/test/CMakeLists.txt
  flang/test/Driver/linker-flags.f90

Index: flang/test/Driver/linker-flags.f90
===
--- /dev/null
+++ flang/test/Driver/linker-flags.f90
@@ -0,0 +1,30 @@
+! Verify that the Fortran runtime libraries are present in the linker
+! invocation. These libraries are added on top of other standard runtime
+! libraries that the Clang driver will include.
+
+! NOTE: The additional linker flags tested here are currently specified in
+! clang/lib/Driver/Toolchains/Gnu.cpp. This makes the current implementation GNU
+! (Linux) specific. The following line will make sure that this test is skipped
+! on Windows. Ideally we should find a more robust way of testing this.
+! REQUIRES: shell
+! UNSUPPORTED: darwin, macos
+
+!
+! RUN COMMAND
+!
+! RUN: %flang -### --ld-path=/usr/bin/ld %S/Inputs/hello.f90 2>&1 | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! Compiler invocation to generate the object file
+! CHECK-LABEL: {{.*}} "-emit-obj"
+! CHECK-SAME:  "-o" "[[object_file:.*]]" {{.*}}Inputs/hello.f90
+
+! Linker invocation to generate the executable
+! CHECK-LABEL:  "/usr/bin/ld"
+! CHECK-SAME: "[[object_file]]"
+! CHECK-SAME: -lFortran_main
+! CHECK-SAME: -lFortranRuntime
+! CHECK-SAME: -lFortranDecimal
+! CHECK-SAME: -lm
Index: flang/test/CMakeLists.txt
===
--- flang/test/CMakeLists.txt
+++ flang/test/CMakeLists.txt
@@ -47,6 +47,7 @@
 
 set(FLANG_TEST_DEPENDS
   flang-new llvm-config FileCheck count not module_files fir-opt tco bbc llvm-objdump
+  FortranRuntime Fortran_main FortranDecimal
 )
 
 if (FLANG_INCLUDE_TESTS)
Index: flang/runtime/FortranMain/Fortran_main.c
===
--- /dev/null
+++ flang/runtime/FortranMain/Fortran_main.c
@@ -0,0 +1,22 @@
+//===-- runtime/FortranMain/Fortran_main.c ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "flang/Runtime/main.h"
+#include "flang/Runtime/stop.h"
+
+/* main entry into PROGRAM */
+void _QQmain();
+
+/* C main stub */
+int main(int argc, const char *argv[], const char *envp[])
+{
+  RTNAME(ProgramStart)(argc, argv, envp);
+  _QQmain();
+  RTNAME(ProgramEndStatement)();
+  return 0;
+}
Index: flang/runtime/FortranMain/CMakeLists.txt
===
--- /dev/null
+++ flang/runtime/FortranMain/CMakeLists.txt
@@ -0,0 +1,3 @@
+add_flang_library(Fortran_main STATIC
+  Fortran_main.c
+)
Index: flang/runtime/CMakeLists.txt
===
--- flang/runtime/CMakeLists.txt
+++ flang/runtime/CMakeLists.txt
@@ -30,6 +30,8 @@
 # with different names
 include_directories(AFTER ${CMAKE_CURRENT_BINARY_DIR})
 
+add_subdirectory(FortranMain)
+
 add_flang_library(FortranRuntime
   ISO_Fortran_binding.cpp
   allocatable.cpp
Index: flang/include/flang/Runtime/stop.h
===
--- flang/include/flang/Runtime/stop.h
+++ flang/include/flang/Runtime/stop.h
@@ -27,7 +27,7 @@
 NORETURN void RTNAME(ProgramEndStatement)(NO_ARGUMENTS);
 
 // Extensions
-NORETURN void RTNAME(Exit)(int status = EXIT_SUCCESS);
+NORETURN void RTNAME(Exit)(int status DEFAULT_VALUE(EXIT_SUCCESS));
 NORETURN void RTNAME(Ab

[PATCH] D122008: [flang][driver] Add support for generating executables

2022-03-18 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 416513.
awarzynski added a comment.

Fix formatting


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122008/new/

https://reviews.llvm.org/D122008

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  flang/include/flang/Runtime/stop.h
  flang/runtime/CMakeLists.txt
  flang/runtime/FortranMain/CMakeLists.txt
  flang/runtime/FortranMain/Fortran_main.c
  flang/test/CMakeLists.txt
  flang/test/Driver/linker-flags.f90

Index: flang/test/Driver/linker-flags.f90
===
--- /dev/null
+++ flang/test/Driver/linker-flags.f90
@@ -0,0 +1,30 @@
+! Verify that the Fortran runtime libraries are present in the linker
+! invocation. These libraries are added on top of other standard runtime
+! libraries that the Clang driver will include.
+
+! NOTE: The additional linker flags tested here are currently specified in
+! clang/lib/Driver/Toolchains/Gnu.cpp. This makes the current implementation GNU
+! (Linux) specific. The following line will make sure that this test is skipped
+! on Windows. Ideally we should find a more robust way of testing this.
+! REQUIRES: shell
+! UNSUPPORTED: darwin, macos
+
+!
+! RUN COMMAND
+!
+! RUN: %flang -### --ld-path=/usr/bin/ld %S/Inputs/hello.f90 2>&1 | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! Compiler invocation to generate the object file
+! CHECK-LABEL: {{.*}} "-emit-obj"
+! CHECK-SAME:  "-o" "[[object_file:.*]]" {{.*}}Inputs/hello.f90
+
+! Linker invocation to generate the executable
+! CHECK-LABEL:  "/usr/bin/ld"
+! CHECK-SAME: "[[object_file]]"
+! CHECK-SAME: -lFortran_main
+! CHECK-SAME: -lFortranRuntime
+! CHECK-SAME: -lFortranDecimal
+! CHECK-SAME: -lm
Index: flang/test/CMakeLists.txt
===
--- flang/test/CMakeLists.txt
+++ flang/test/CMakeLists.txt
@@ -47,6 +47,7 @@
 
 set(FLANG_TEST_DEPENDS
   flang-new llvm-config FileCheck count not module_files fir-opt tco bbc llvm-objdump
+  FortranRuntime Fortran_main FortranDecimal
 )
 
 if (FLANG_INCLUDE_TESTS)
Index: flang/runtime/FortranMain/Fortran_main.c
===
--- /dev/null
+++ flang/runtime/FortranMain/Fortran_main.c
@@ -0,0 +1,21 @@
+//===-- runtime/FortranMain/Fortran_main.c ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "flang/Runtime/main.h"
+#include "flang/Runtime/stop.h"
+
+/* main entry into PROGRAM */
+void _QQmain();
+
+/* C main stub */
+int main(int argc, const char *argv[], const char *envp[]) {
+  RTNAME(ProgramStart)(argc, argv, envp);
+  _QQmain();
+  RTNAME(ProgramEndStatement)();
+  return 0;
+}
Index: flang/runtime/FortranMain/CMakeLists.txt
===
--- /dev/null
+++ flang/runtime/FortranMain/CMakeLists.txt
@@ -0,0 +1,3 @@
+add_flang_library(Fortran_main STATIC
+  Fortran_main.c
+)
Index: flang/runtime/CMakeLists.txt
===
--- flang/runtime/CMakeLists.txt
+++ flang/runtime/CMakeLists.txt
@@ -30,6 +30,8 @@
 # with different names
 include_directories(AFTER ${CMAKE_CURRENT_BINARY_DIR})
 
+add_subdirectory(FortranMain)
+
 add_flang_library(FortranRuntime
   ISO_Fortran_binding.cpp
   allocatable.cpp
Index: flang/include/flang/Runtime/stop.h
===
--- flang/include/flang/Runtime/stop.h
+++ flang/include/flang/Runtime/stop.h
@@ -27,7 +27,7 @@
 NORETURN void RTNAME(ProgramEndStatement)(NO_ARGUMENTS);
 
 // Extensions
-NORETURN void RTNAME(Exit)(int status = EXIT_SUCCESS);
+NORETURN void RTNAME(Exit)(int status DEFAULT_VALUE(EXIT_SUCCESS));
 NORETURN void RTNAME(Abort)(NO_ARGUMENTS);
 
 // Crash with an error message when the program dynamically violates a Fortran
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -379,6 +379,13 @@
  Exec, CmdArgs, Inputs, Output));
 }
 
+static void addFortranLinkerFlags(ArgStringList &CmdArgs) {
+  CmdArgs.push_back("-lFortran_main");
+  CmdArgs.push_back("-lFortranRuntime");
+  CmdArgs.push_back("-lFortranDecimal");
+  CmdArgs.push_back("-lm");
+}
+
 void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
const InputInfo &Output,
const InputInfoList &Inputs,
@@ -665,6 +672,10 @@
 }
   }
 
+  // Additional

[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski created this revision.
awarzynski added a reviewer: rovka.
Herald added subscribers: sdasgup3, wenzhicui, wrengr, Chia-hungDuan, dcaballe, 
cota, teijeong, rdzhabarov, tatianashp, msifontes, jurahul, Kayjukh, grosul1, 
Joonsoo, liufengdb, aartbik, mgester, arpith-jacob, antiagainst, shauheen, 
rriddle, mehdi_amini, mgorny.
Herald added a reviewer: sscalpone.
Herald added projects: Flang, All.
awarzynski requested review of this revision.
Herald added subscribers: cfe-commits, stephenneuendorffer, nicolasvasilache, 
jdoerfert, MaskRay.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123297

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/mllvm_vs_mmlir.f90

Index: flang/test/Driver/mllvm_vs_mmlir.f90
===
--- /dev/null
+++ flang/test/Driver/mllvm_vs_mmlir.f90
@@ -0,0 +1,18 @@
+! Verify that `-mllvm` options are forwarded to LLVM and `-mmlir` to MLIR
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1  -mmlir --help | FileCheck %s --check-prefix=MLIR
+! RUN: %flang_fc1  -mllvm --help | FileCheck %s --check-prefix=MLLVM
+
+!
+! EXPECTED OUTPUT
+!
+! MLIR: flang (MLIR option parsing) [options]
+! MLIR: --mlir-{{.*}}
+! MLIR-NOT: --print-ir-after-all
+
+! MLLVM: flang (LLVM option parsing) [options]
+! MLLVM: --print-ir-after-all
+! MLLVM-NOT: --mlir-{{.*}}
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -48,6 +48,7 @@
 ! HELP-NEXT: -help  Display available options
 ! HELP-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! HELP-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! HELP-NEXT: -module-dir   Put MODULE files in 
 ! HELP-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! HELP-NEXT: -o   Write output to 
@@ -123,6 +124,7 @@
 ! HELP-FC1-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-FC1-NEXT: -load Load the named plugin (dynamic shared object)
 ! HELP-FC1-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! HELP-FC1-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! HELP-FC1-NEXT: -module-dir   Put MODULE files in 
 ! HELP-FC1-NEXT: -module-suffix  Use  as the suffix for module files (the default value is `.mod`)
 ! HELP-FC1-NEXT: -nocpp Disable predefined and command line preprocessor macros
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -48,6 +48,7 @@
 ! CHECK-NEXT: -help Display available options
 ! CHECK-NEXT: -IAdd directory to the end of the list of include search paths
 ! CHECK-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! CHECK-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! CHECK-NEXT: -module-dir   Put MODULE files in 
 ! CHECK-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! CHECK-NEXT: -o  Write output to 
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -11,6 +11,8 @@
 //
 //===--===//
 
+#include "mlir/IR/MLIRContext.h"
+#include "mlir/Pass/PassManager.h"
 #include "flang/Frontend/CompilerInstance.h"
 #include "flang/Frontend/FrontendActions.h"
 #include "flang/Frontend/FrontendPluginRegistry.h"
@@ -148,6 +150,21 @@
 llvm::cl::ParseCommandLineOptions(numArgs + 1, args.get());
   }
 
+  // Honor -mmlir. This should happen AFTER plugins have been loaded!
+  if (!flang->frontendOpts().mlirArgs.empty()) {
+mlir::registerMLIRContextCLOptions();
+mlir::registerPassManagerCLOptions();
+unsigned numArgs = flang->frontendOpts().mlirArgs.size();
+auto args = std::make_unique(numArgs + 2);
+args[0] = "flang (MLIR option parsing)";
+
+for (unsigned i = 0; i != numArgs; ++i)
+  args[i + 1] = flang->frontendOpts().mlirArgs[i].c_str(

[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 421168.
awarzynski edited the summary of this revision.
awarzynski added a comment.

Fix pre-commit CI


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123297/new/

https://reviews.llvm.org/D123297

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/mllvm_vs_mmlir.f90

Index: flang/test/Driver/mllvm_vs_mmlir.f90
===
--- /dev/null
+++ flang/test/Driver/mllvm_vs_mmlir.f90
@@ -0,0 +1,18 @@
+! Verify that `-mllvm` options are forwarded to LLVM and `-mmlir` to MLIR
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1  -mmlir --help | FileCheck %s --check-prefix=MLIR
+! RUN: %flang_fc1  -mllvm --help | FileCheck %s --check-prefix=MLLVM
+
+!
+! EXPECTED OUTPUT
+!
+! MLIR: flang (MLIR option parsing) [options]
+! MLIR: --mlir-{{.*}}
+! MLIR-NOT: --mir-strip-debugify-only
+
+! MLLVM: flang (LLVM option parsing) [options]
+! MLLVM: --mir-strip-debugify-only
+! MLLVM-NOT: --mlir-{{.*}}
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -48,6 +48,7 @@
 ! HELP-NEXT: -help  Display available options
 ! HELP-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! HELP-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! HELP-NEXT: -module-dir   Put MODULE files in 
 ! HELP-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! HELP-NEXT: -o   Write output to 
@@ -123,6 +124,7 @@
 ! HELP-FC1-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-FC1-NEXT: -load Load the named plugin (dynamic shared object)
 ! HELP-FC1-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! HELP-FC1-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! HELP-FC1-NEXT: -module-dir   Put MODULE files in 
 ! HELP-FC1-NEXT: -module-suffix  Use  as the suffix for module files (the default value is `.mod`)
 ! HELP-FC1-NEXT: -nocpp Disable predefined and command line preprocessor macros
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -48,6 +48,7 @@
 ! CHECK-NEXT: -help Display available options
 ! CHECK-NEXT: -IAdd directory to the end of the list of include search paths
 ! CHECK-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! CHECK-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! CHECK-NEXT: -module-dir   Put MODULE files in 
 ! CHECK-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! CHECK-NEXT: -o  Write output to 
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -11,6 +11,8 @@
 //
 //===--===//
 
+#include "mlir/IR/MLIRContext.h"
+#include "mlir/Pass/PassManager.h"
 #include "flang/Frontend/CompilerInstance.h"
 #include "flang/Frontend/FrontendActions.h"
 #include "flang/Frontend/FrontendPluginRegistry.h"
@@ -148,6 +150,21 @@
 llvm::cl::ParseCommandLineOptions(numArgs + 1, args.get());
   }
 
+  // Honor -mmlir. This should happen AFTER plugins have been loaded!
+  if (!flang->frontendOpts().mlirArgs.empty()) {
+mlir::registerMLIRContextCLOptions();
+mlir::registerPassManagerCLOptions();
+unsigned numArgs = flang->frontendOpts().mlirArgs.size();
+auto args = std::make_unique(numArgs + 2);
+args[0] = "flang (MLIR option parsing)";
+
+for (unsigned i = 0; i != numArgs; ++i)
+  args[i + 1] = flang->frontendOpts().mlirArgs[i].c_str();
+
+args[numArgs + 1] = nullptr;
+llvm::cl::ParseCommandLineOptions(numArgs + 1, args.get());
+  }
+
   // If there were errors in processing arguments, don't do anything else.
   if (flang->diagnostics().hasErrorOccurred()) {
 return false;
Index: flang/lib/FrontendTool/CMakeLists.txt

[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

In D123297#3435816 , @rovka wrote:

> I don't know the command line library that well, so I have this curiosity: 
> what happens if LLVM and MLIR have 2 different options with the same name? Do 
> we get a compile time error?

The llvm::cl API uses global variables. So, if a variable is defined twice, you 
will get a compilation error. I will advertise this before merging so that 
folks from LLVM and MLIR are aware of this change. I'm hoping that they won't 
mind having to use distinct variable names for CL options in MLIR and LLVM.

> Or is there a risk that someone might -mllvm -XYZ and it would end up in 
> MLIR's XYZ option instead, because we're processing the MLIR options after 
> the LLVM ones?

Note that `-mllvm` options are saved in `llvmArgs` and `-mmlir` options are 
saved in `mlirArgs` (this is taken care of in "CompilerInvocation.cpp"). This 
should guarantee that the right option set is used.




Comment at: flang/test/Driver/mllvm_vs_mmlir.f90:17
+! MLLVM: flang (LLVM option parsing) [options]
+! MLLVM: --print-ir-after-all
+! MLLVM-NOT: --mlir-{{.*}}

rovka wrote:
> rovka wrote:
> > Is this the most llvm-ish option we have? I'm concerned that MLIR might 
> > also decide to add an option that sounds like this (and for sure 
> > -print-ir-before-all is mentioned in the [[ 
> > https://mlir.llvm.org/getting_started/Debugging/ |  MLIR docs ]]).
> > Is this the most llvm-ish option we have? I'm concerned that MLIR might 
> > also decide to add an option that sounds like this (and for sure 
> > -print-ir-before-all is mentioned in the [[ 
> > https://mlir.llvm.org/getting_started/Debugging/ |  MLIR docs ]]).
> 
> Right, I think that might be why the premerge tests are failing...
> Is this the most llvm-ish option we have? 

Sadly, most LLVM options have rather generic names that could at some point be 
added in MLIR. Perhaps you'll spot something more suitable:

```lang=bash
USAGE: flang (LLVM option parsing) [options]

OPTIONS:

Color Options:

  --color   - Use colors in output 
(default=autodetect)

General options:

  --aarch64-neon-syntax= - Choose style of NEON code 
to emit from AArch64 backend:
=generic-   Emit generic NEON 
assembly
=apple  -   Emit Apple-style NEON 
assembly
  --aarch64-use-aa  - Enable the use of AA 
during codegen.
  --abort-on-max-devirt-iterations-reached  - Abort when the max 
iterations for devirtualization CGSCC repeat pass is reached
  --allow-ginsert-as-artifact   - Allow G_INSERT to be 
considered an artifact. Hack around AMDGPU test infinite loops.
  --always-execute-loop-body- force the body of a loop 
to execute at least once
  --array-constructor-initial-buffer-size=- set the incremental array 
construction buffer size (default=32)
  --cfg-hide-cold-paths=- Hide blocks with relative 
frequency below the given value
  --cfg-hide-deoptimize-paths   -
  --cfg-hide-unreachable-paths  -
  --cost-kind=   - Target cost kind
=throughput -   Reciprocal throughput
=latency-   Instruction latency
=code-size  -   Code size
=size-latency   -   Code size and latency
  --debugify-level=  - Kind of debug info to add
=locations  -   Locations only
=location+variables -   Locations and Variables
  --debugify-quiet  - Suppress verbose debugify 
output
  --default-kinds= - string to set default 
kind values
  --disable-i2p-p2i-opt - Disables 
inttoptr/ptrtoint roundtrip optimization
  --dot-cfg-mssa= - file name for generated 
dot file
  --enable-cse-in-irtranslator  - Should enable CSE in 
irtranslator
  --enable-cse-in-legalizer - Should enable CSE in 
Legalizer
  --enable-gvn-memdep   -
  --enable-load-in-loop-pre -
  --enable-load-pre -
  --enable-loop-simplifycfg-term-folding-
  --enable-name-compression - Enable name/filename 
string compression
  --enable-split-backedge-in-load-pre   -
  --experimental-debug-variable-locations   - Use experimental new 
value-tracking variable locations
  --fdebug-dump-pre-fir - dump the Pre-FIR tree 
prior to FIR generation
  --fs-profile-debug-bw-threshold=- Only show debug 

[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 421223.
awarzynski added a comment.

Make sure the MLIR CL options are "applied"


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123297/new/

https://reviews.llvm.org/D123297

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/mllvm_vs_mmlir.f90

Index: flang/test/Driver/mllvm_vs_mmlir.f90
===
--- /dev/null
+++ flang/test/Driver/mllvm_vs_mmlir.f90
@@ -0,0 +1,18 @@
+! Verify that `-mllvm` options are forwarded to LLVM and `-mmlir` to MLIR
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1  -mmlir --help | FileCheck %s --check-prefix=MLIR
+! RUN: %flang_fc1  -mllvm --help | FileCheck %s --check-prefix=MLLVM
+
+!
+! EXPECTED OUTPUT
+!
+! MLIR: flang (MLIR option parsing) [options]
+! MLIR: --mlir-{{.*}}
+! MLIR-NOT: --mir-strip-debugify-only
+
+! MLLVM: flang (LLVM option parsing) [options]
+! MLLVM: --mir-strip-debugify-only
+! MLLVM-NOT: --mlir-{{.*}}
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -48,6 +48,7 @@
 ! HELP-NEXT: -help  Display available options
 ! HELP-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! HELP-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! HELP-NEXT: -module-dir   Put MODULE files in 
 ! HELP-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! HELP-NEXT: -o   Write output to 
@@ -123,6 +124,7 @@
 ! HELP-FC1-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-FC1-NEXT: -load Load the named plugin (dynamic shared object)
 ! HELP-FC1-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! HELP-FC1-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! HELP-FC1-NEXT: -module-dir   Put MODULE files in 
 ! HELP-FC1-NEXT: -module-suffix  Use  as the suffix for module files (the default value is `.mod`)
 ! HELP-FC1-NEXT: -nocpp Disable predefined and command line preprocessor macros
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -48,6 +48,7 @@
 ! CHECK-NEXT: -help Display available options
 ! CHECK-NEXT: -IAdd directory to the end of the list of include search paths
 ! CHECK-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! CHECK-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! CHECK-NEXT: -module-dir   Put MODULE files in 
 ! CHECK-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! CHECK-NEXT: -o  Write output to 
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -11,6 +11,8 @@
 //
 //===--===//
 
+#include "mlir/IR/MLIRContext.h"
+#include "mlir/Pass/PassManager.h"
 #include "flang/Frontend/CompilerInstance.h"
 #include "flang/Frontend/FrontendActions.h"
 #include "flang/Frontend/FrontendPluginRegistry.h"
@@ -148,6 +150,21 @@
 llvm::cl::ParseCommandLineOptions(numArgs + 1, args.get());
   }
 
+  // Honor -mmlir. This should happen AFTER plugins have been loaded!
+  if (!flang->frontendOpts().mlirArgs.empty()) {
+mlir::registerMLIRContextCLOptions();
+mlir::registerPassManagerCLOptions();
+unsigned numArgs = flang->frontendOpts().mlirArgs.size();
+auto args = std::make_unique(numArgs + 2);
+args[0] = "flang (MLIR option parsing)";
+
+for (unsigned i = 0; i != numArgs; ++i)
+  args[i + 1] = flang->frontendOpts().mlirArgs[i].c_str();
+
+args[numArgs + 1] = nullptr;
+llvm::cl::ParseCommandLineOptions(numArgs + 1, args.get());
+  }
+
   // If there were errors in processing arguments, don't do anything else.
   if (flang->diagnostics().hasErrorOccurred()) {
 return false;
Index: flang/lib/FrontendTool/CMakeLists.txt
=

[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/test/Driver/mllvm_vs_mmlir.f90:17
+! MLLVM: flang (LLVM option parsing) [options]
+! MLLVM: --print-ir-after-all
+! MLLVM-NOT: --mlir-{{.*}}

rriddle wrote:
> awarzynski wrote:
> > awarzynski wrote:
> > > rovka wrote:
> > > > rovka wrote:
> > > > > Is this the most llvm-ish option we have? I'm concerned that MLIR 
> > > > > might also decide to add an option that sounds like this (and for 
> > > > > sure -print-ir-before-all is mentioned in the [[ 
> > > > > https://mlir.llvm.org/getting_started/Debugging/ |  MLIR docs ]]).
> > > > > Is this the most llvm-ish option we have? I'm concerned that MLIR 
> > > > > might also decide to add an option that sounds like this (and for 
> > > > > sure -print-ir-before-all is mentioned in the [[ 
> > > > > https://mlir.llvm.org/getting_started/Debugging/ |  MLIR docs ]]).
> > > > 
> > > > Right, I think that might be why the premerge tests are failing...
> > > > Is this the most llvm-ish option we have? 
> > > 
> > > Sadly, most LLVM options have rather generic names that could at some 
> > > point be added in MLIR. Perhaps you'll spot something more suitable:
> > > 
> > > ```lang=bash
> > > USAGE: flang (LLVM option parsing) [options]
> > > 
> > > OPTIONS:
> > > 
> > > Color Options:
> > > 
> > >   --color   - Use colors in 
> > > output (default=autodetect)
> > > 
> > > General options:
> > > 
> > >   --aarch64-neon-syntax= - Choose style of 
> > > NEON code to emit from AArch64 backend:
> > > =generic-   Emit generic NEON 
> > > assembly
> > > =apple  -   Emit Apple-style 
> > > NEON assembly
> > >   --aarch64-use-aa  - Enable the use of 
> > > AA during codegen.
> > >   --abort-on-max-devirt-iterations-reached  - Abort when the max 
> > > iterations for devirtualization CGSCC repeat pass is reached
> > >   --allow-ginsert-as-artifact   - Allow G_INSERT to 
> > > be considered an artifact. Hack around AMDGPU test infinite loops.
> > >   --always-execute-loop-body- force the body of a 
> > > loop to execute at least once
> > >   --array-constructor-initial-buffer-size=- set the incremental 
> > > array construction buffer size (default=32)
> > >   --cfg-hide-cold-paths=- Hide blocks with 
> > > relative frequency below the given value
> > >   --cfg-hide-deoptimize-paths   -
> > >   --cfg-hide-unreachable-paths  -
> > >   --cost-kind=   - Target cost kind
> > > =throughput -   Reciprocal 
> > > throughput
> > > =latency-   Instruction 
> > > latency
> > > =code-size  -   Code size
> > > =size-latency   -   Code size and 
> > > latency
> > >   --debugify-level=  - Kind of debug info 
> > > to add
> > > =locations  -   Locations only
> > > =location+variables -   Locations and 
> > > Variables
> > >   --debugify-quiet  - Suppress verbose 
> > > debugify output
> > >   --default-kinds= - string to set 
> > > default kind values
> > >   --disable-i2p-p2i-opt - Disables 
> > > inttoptr/ptrtoint roundtrip optimization
> > >   --dot-cfg-mssa= - file name for 
> > > generated dot file
> > >   --enable-cse-in-irtranslator  - Should enable CSE 
> > > in irtranslator
> > >   --enable-cse-in-legalizer - Should enable CSE 
> > > in Legalizer
> > >   --enable-gvn-memdep   -
> > >   --enable-load-in-loop-pre -
> > >   --enable-load-pre -
> > >   --enable-loop-simplifycfg-term-folding-
> > >   --enable-name-compression - Enable 
> > > name/filename string compression
> > >   --enable-split-backedge-in-load-pre   -
> > >   --experimental-debug-variable-locations   - Use experimental 
> > > new value-tracking variable locations
> > >   --fdebug-dump-pre-fir - dump the Pre-FIR 
> > > tree prior to FIR generation
> > >   --fs-profile-debug-bw-threshold=- Only show debug 
> > > message if the source branch weight is greater  than this value.
> > >   --fs-profile-debug-prob-diff-threshold= - Only show debug 
> > > message if the branch probility is greater than this value (in 
> > > percentage).
> > >   --gen-array-coor  - in lowering create 
> > > ArrayCoorOp instead of CoordinateOp
> > >   --generate-merged-

[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

In D123297#3436867 , @mehdi_amini 
wrote:

> `-mmlir` is fine with me, but note that MLIR has much less global options 
> than LLVM: you will only get access to context and passmanager options and 
> not individual passes flags. That's not a criticism :)
> (that's what makes it not likely to have conflicts by the way: the set of 
> MLIR option is well identified)

Thanks for taking a look! All this should be fine - the main rationale for this 
patch is to enable MLIR options in `flang-new` so that tests using `tco` or 
`bbc` (and which use MLIR options) can be ported to use `flang-new`. We were 
discussing this recently in https://reviews.llvm.org/D121171.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123297/new/

https://reviews.llvm.org/D123297

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-11 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/test/Driver/mllvm_vs_mmlir.f90:17
+! MLLVM: flang (LLVM option parsing) [options]
+! MLLVM: --print-ir-after-all
+! MLLVM-NOT: --mlir-{{.*}}

awarzynski wrote:
> rriddle wrote:
> > awarzynski wrote:
> > > awarzynski wrote:
> > > > rovka wrote:
> > > > > rovka wrote:
> > > > > > Is this the most llvm-ish option we have? I'm concerned that MLIR 
> > > > > > might also decide to add an option that sounds like this (and for 
> > > > > > sure -print-ir-before-all is mentioned in the [[ 
> > > > > > https://mlir.llvm.org/getting_started/Debugging/ |  MLIR docs ]]).
> > > > > > Is this the most llvm-ish option we have? I'm concerned that MLIR 
> > > > > > might also decide to add an option that sounds like this (and for 
> > > > > > sure -print-ir-before-all is mentioned in the [[ 
> > > > > > https://mlir.llvm.org/getting_started/Debugging/ |  MLIR docs ]]).
> > > > > 
> > > > > Right, I think that might be why the premerge tests are failing...
> > > > > Is this the most llvm-ish option we have? 
> > > > 
> > > > Sadly, most LLVM options have rather generic names that could at some 
> > > > point be added in MLIR. Perhaps you'll spot something more suitable:
> > > > 
> > > > ```lang=bash
> > > > USAGE: flang (LLVM option parsing) [options]
> > > > 
> > > > OPTIONS:
> > > > 
> > > > Color Options:
> > > > 
> > > >   --color   - Use colors in 
> > > > output (default=autodetect)
> > > > 
> > > > General options:
> > > > 
> > > >   --aarch64-neon-syntax= - Choose style of 
> > > > NEON code to emit from AArch64 backend:
> > > > =generic-   Emit generic 
> > > > NEON assembly
> > > > =apple  -   Emit 
> > > > Apple-style NEON assembly
> > > >   --aarch64-use-aa  - Enable the use of 
> > > > AA during codegen.
> > > >   --abort-on-max-devirt-iterations-reached  - Abort when the 
> > > > max iterations for devirtualization CGSCC repeat pass is reached
> > > >   --allow-ginsert-as-artifact   - Allow G_INSERT to 
> > > > be considered an artifact. Hack around AMDGPU test infinite loops.
> > > >   --always-execute-loop-body- force the body of 
> > > > a loop to execute at least once
> > > >   --array-constructor-initial-buffer-size=- set the 
> > > > incremental array construction buffer size (default=32)
> > > >   --cfg-hide-cold-paths=- Hide blocks with 
> > > > relative frequency below the given value
> > > >   --cfg-hide-deoptimize-paths   -
> > > >   --cfg-hide-unreachable-paths  -
> > > >   --cost-kind=   - Target cost kind
> > > > =throughput -   Reciprocal 
> > > > throughput
> > > > =latency-   Instruction 
> > > > latency
> > > > =code-size  -   Code size
> > > > =size-latency   -   Code size and 
> > > > latency
> > > >   --debugify-level=  - Kind of debug 
> > > > info to add
> > > > =locations  -   Locations only
> > > > =location+variables -   Locations and 
> > > > Variables
> > > >   --debugify-quiet  - Suppress verbose 
> > > > debugify output
> > > >   --default-kinds= - string to set 
> > > > default kind values
> > > >   --disable-i2p-p2i-opt - Disables 
> > > > inttoptr/ptrtoint roundtrip optimization
> > > >   --dot-cfg-mssa= - file name for 
> > > > generated dot file
> > > >   --enable-cse-in-irtranslator  - Should enable CSE 
> > > > in irtranslator
> > > >   --enable-cse-in-legalizer - Should enable CSE 
> > > > in Legalizer
> > > >   --enable-gvn-memdep   -
> > > >   --enable-load-in-loop-pre -
> > > >   --enable-load-pre -
> > > >   --enable-loop-simplifycfg-term-folding-
> > > >   --enable-name-compression - Enable 
> > > > name/filename string compression
> > > >   --enable-split-backedge-in-load-pre   -
> > > >   --experimental-debug-variable-locations   - Use experimental 
> > > > new value-tracking variable locations
> > > >   --fdebug-dump-pre-fir - dump the Pre-FIR 
> > > > tree prior to FIR generation
> > > >   --fs-profile-debug-bw-threshold=- Only show debug 
> > > > message if the source branch weight is greater  than this value.
> > > >   --fs-profile-debug-prob-diff-threshold= - Only show debug 
> > > > message if the branch probili

[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-12 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 422143.
awarzynski added a comment.

Updates required after https://reviews.llvm.org/D122444


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122008/new/

https://reviews.llvm.org/D122008

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  flang/include/flang/Runtime/stop.h
  flang/runtime/CMakeLists.txt
  flang/runtime/FortranMain/CMakeLists.txt
  flang/runtime/FortranMain/Fortran_main.c
  flang/test/CMakeLists.txt
  flang/test/Driver/linker-flags.f90

Index: flang/test/Driver/linker-flags.f90
===
--- /dev/null
+++ flang/test/Driver/linker-flags.f90
@@ -0,0 +1,30 @@
+! Verify that the Fortran runtime libraries are present in the linker
+! invocation. These libraries are added on top of other standard runtime
+! libraries that the Clang driver will include.
+
+! NOTE: The additional linker flags tested here are currently specified in
+! clang/lib/Driver/Toolchains/Gnu.cpp. This makes the current implementation GNU
+! (Linux) specific. The following line will make sure that this test is skipped
+! on Windows. Ideally we should find a more robust way of testing this.
+! REQUIRES: shell
+! UNSUPPORTED: darwin, macos
+
+!
+! RUN COMMAND
+!
+! RUN: %flang -### --ld-path=/usr/bin/ld %S/Inputs/hello.f90 2>&1 | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! Compiler invocation to generate the object file
+! CHECK-LABEL: {{.*}} "-emit-obj"
+! CHECK-SAME:  "-o" "[[object_file:.*]]" {{.*}}Inputs/hello.f90
+
+! Linker invocation to generate the executable
+! CHECK-LABEL:  "/usr/bin/ld"
+! CHECK-SAME: "[[object_file]]"
+! CHECK-SAME: -lFortran_main
+! CHECK-SAME: -lFortranRuntime
+! CHECK-SAME: -lFortranDecimal
+! CHECK-SAME: -lm
Index: flang/test/CMakeLists.txt
===
--- flang/test/CMakeLists.txt
+++ flang/test/CMakeLists.txt
@@ -57,6 +57,9 @@
   bbc
   llvm-objdump
   split-file
+  FortranRuntime
+  Fortran_main
+  FortranDecimal
 )
 
 if (FLANG_INCLUDE_TESTS)
Index: flang/runtime/FortranMain/Fortran_main.c
===
--- /dev/null
+++ flang/runtime/FortranMain/Fortran_main.c
@@ -0,0 +1,21 @@
+//===-- runtime/FortranMain/Fortran_main.c ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "flang/Runtime/main.h"
+#include "flang/Runtime/stop.h"
+
+/* main entry into PROGRAM */
+void _QQmain();
+
+/* C main stub */
+int main(int argc, const char *argv[], const char *envp[]) {
+  RTNAME(ProgramStart)(argc, argv, envp);
+  _QQmain();
+  RTNAME(ProgramEndStatement)();
+  return 0;
+}
Index: flang/runtime/FortranMain/CMakeLists.txt
===
--- /dev/null
+++ flang/runtime/FortranMain/CMakeLists.txt
@@ -0,0 +1,3 @@
+llvm_add_library(Fortran_main STATIC
+  Fortran_main.c
+)
Index: flang/runtime/CMakeLists.txt
===
--- flang/runtime/CMakeLists.txt
+++ flang/runtime/CMakeLists.txt
@@ -30,6 +30,8 @@
 # with different names
 include_directories(AFTER ${CMAKE_CURRENT_BINARY_DIR})
 
+add_subdirectory(FortranMain)
+
 add_flang_library(FortranRuntime
   ISO_Fortran_binding.cpp
   allocatable.cpp
Index: flang/include/flang/Runtime/stop.h
===
--- flang/include/flang/Runtime/stop.h
+++ flang/include/flang/Runtime/stop.h
@@ -27,7 +27,7 @@
 NORETURN void RTNAME(ProgramEndStatement)(NO_ARGUMENTS);
 
 // Extensions
-NORETURN void RTNAME(Exit)(int status = EXIT_SUCCESS);
+NORETURN void RTNAME(Exit)(int status DEFAULT_VALUE(EXIT_SUCCESS));
 NORETURN void RTNAME(Abort)(NO_ARGUMENTS);
 
 // Crash with an error message when the program dynamically violates a Fortran
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -382,6 +382,29 @@
  Exec, CmdArgs, Inputs, Output));
 }
 
+static void addFortranRuntimeLibraryPath(const ToolChain &TC,
+ const ArgList &Args,
+ ArgStringList &CmdArgs) {
+  // Default to the /../lib directory. This works fine on the
+  // platforms that we have tested so far. We will probably have to re-fine
+  // this in the future. In particular:
+  //* on some platforms, we may need to use lib64 instead of lib (you can use
+  //CLANG_LIBDIR_SUFFIX to automate this)
+  //* this lo

[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-12 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/test/Driver/mllvm_vs_mmlir.f90:17
+! MLLVM: flang (LLVM option parsing) [options]
+! MLLVM: --print-ir-after-all
+! MLLVM-NOT: --mlir-{{.*}}

rovka wrote:
> awarzynski wrote:
> > awarzynski wrote:
> > > rriddle wrote:
> > > > awarzynski wrote:
> > > > > awarzynski wrote:
> > > > > > rovka wrote:
> > > > > > > rovka wrote:
> > > > > > > > Is this the most llvm-ish option we have? I'm concerned that 
> > > > > > > > MLIR might also decide to add an option that sounds like this 
> > > > > > > > (and for sure -print-ir-before-all is mentioned in the [[ 
> > > > > > > > https://mlir.llvm.org/getting_started/Debugging/ |  MLIR docs 
> > > > > > > > ]]).
> > > > > > > > Is this the most llvm-ish option we have? I'm concerned that 
> > > > > > > > MLIR might also decide to add an option that sounds like this 
> > > > > > > > (and for sure -print-ir-before-all is mentioned in the [[ 
> > > > > > > > https://mlir.llvm.org/getting_started/Debugging/ |  MLIR docs 
> > > > > > > > ]]).
> > > > > > > 
> > > > > > > Right, I think that might be why the premerge tests are failing...
> > > > > > > Is this the most llvm-ish option we have? 
> > > > > > 
> > > > > > Sadly, most LLVM options have rather generic names that could at 
> > > > > > some point be added in MLIR. Perhaps you'll spot something more 
> > > > > > suitable:
> > > > > > 
> > > > > > ```lang=bash
> > > > > > USAGE: flang (LLVM option parsing) [options]
> > > > > > 
> > > > > > OPTIONS:
> > > > > > 
> > > > > > Color Options:
> > > > > > 
> > > > > >   --color   - Use colors in 
> > > > > > output (default=autodetect)
> > > > > > 
> > > > > > General options:
> > > > > > 
> > > > > >   --aarch64-neon-syntax= - Choose style 
> > > > > > of NEON code to emit from AArch64 backend:
> > > > > > =generic-   Emit 
> > > > > > generic NEON assembly
> > > > > > =apple  -   Emit 
> > > > > > Apple-style NEON assembly
> > > > > >   --aarch64-use-aa  - Enable the 
> > > > > > use of AA during codegen.
> > > > > >   --abort-on-max-devirt-iterations-reached  - Abort when 
> > > > > > the max iterations for devirtualization CGSCC repeat pass is reached
> > > > > >   --allow-ginsert-as-artifact   - Allow 
> > > > > > G_INSERT to be considered an artifact. Hack around AMDGPU test 
> > > > > > infinite loops.
> > > > > >   --always-execute-loop-body- force the 
> > > > > > body of a loop to execute at least once
> > > > > >   --array-constructor-initial-buffer-size=- set the 
> > > > > > incremental array construction buffer size (default=32)
> > > > > >   --cfg-hide-cold-paths=- Hide blocks 
> > > > > > with relative frequency below the given value
> > > > > >   --cfg-hide-deoptimize-paths   -
> > > > > >   --cfg-hide-unreachable-paths  -
> > > > > >   --cost-kind=   - Target cost 
> > > > > > kind
> > > > > > =throughput -   Reciprocal 
> > > > > > throughput
> > > > > > =latency-   Instruction 
> > > > > > latency
> > > > > > =code-size  -   Code size
> > > > > > =size-latency   -   Code size 
> > > > > > and latency
> > > > > >   --debugify-level=  - Kind of debug 
> > > > > > info to add
> > > > > > =locations  -   Locations 
> > > > > > only
> > > > > > =location+variables -   Locations 
> > > > > > and Variables
> > > > > >   --debugify-quiet  - Suppress 
> > > > > > verbose debugify output
> > > > > >   --default-kinds= - string to set 
> > > > > > default kind values
> > > > > >   --disable-i2p-p2i-opt - Disables 
> > > > > > inttoptr/ptrtoint roundtrip optimization
> > > > > >   --dot-cfg-mssa= - file name for 
> > > > > > generated dot file
> > > > > >   --enable-cse-in-irtranslator  - Should enable 
> > > > > > CSE in irtranslator
> > > > > >   --enable-cse-in-legalizer - Should enable 
> > > > > > CSE in Legalizer
> > > > > >   --enable-gvn-memdep   -
> > > > > >   --enable-load-in-loop-pre -
> > > > > >   --enable-load-pre -
> > > > > >   --enable-loop-simplifycfg-term-folding-
> > > > > >   --enable-name-compression - Enable 
> > > > > > name/filename string compression
> > > > > >   --enable-split-backedge-in-load-pre   -
> > > > > >   --experimental-debug-varia

[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-12 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

I did a bit of digging and realised that MLIR llvm::cl options are lazily 
constructed on demand 

 (see the definition of options 

 in PassManagerOptions.cpp). This means that:

- Flang and LLVM global options are always visible and displayed when passing 
`-mllvm -help`,
- MLIR global options are only visible when explicitly initialised and 
displayed when passing `-mmlir -help`.

Since Flang and LLVM global options are always visible, llvm::cl will display 
them alongside MLIR options when using `-mmlir -help`. In other words,  `-mmlir 
-help` is a superset of `--mllvm -help`. This is not ideal, but we'd need to 
refactor all option definitions in Flang and LLVM to improve this. I suggesting 
leaving this for later.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123297/new/

https://reviews.llvm.org/D123297

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-12 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 422163.
awarzynski added a comment.

Rebase on top of `main`, re-fine the test

Make sure that the test file correctly takes into account that `-mmlir -help` 
is a superset of `-mllvm -help`.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123297/new/

https://reviews.llvm.org/D123297

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/mllvm_vs_mmlir.f90

Index: flang/test/Driver/mllvm_vs_mmlir.f90
===
--- /dev/null
+++ flang/test/Driver/mllvm_vs_mmlir.f90
@@ -0,0 +1,16 @@
+! Verify that `-mllvm` options are forwarded to LLVM and `-mmlir` to MLIR
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1  -mmlir --help | FileCheck %s --check-prefix=MLIR
+! RUN: %flang_fc1  -mllvm --help | FileCheck %s --check-prefix=MLLVM
+
+!
+! EXPECTED OUTPUT
+!
+! MLIR: flang (MLIR option parsing) [options]
+! MLIR: --mlir-{{.*}}
+
+! MLLVM: flang (LLVM option parsing) [options]
+! MLLVM-NOT: --mlir-{{.*}}
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -48,6 +48,7 @@
 ! HELP-NEXT: -help  Display available options
 ! HELP-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! HELP-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! HELP-NEXT: -module-dir   Put MODULE files in 
 ! HELP-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! HELP-NEXT: -o   Write output to 
@@ -123,6 +124,7 @@
 ! HELP-FC1-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-FC1-NEXT: -load Load the named plugin (dynamic shared object)
 ! HELP-FC1-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! HELP-FC1-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! HELP-FC1-NEXT: -module-dir   Put MODULE files in 
 ! HELP-FC1-NEXT: -module-suffix  Use  as the suffix for module files (the default value is `.mod`)
 ! HELP-FC1-NEXT: -nocpp Disable predefined and command line preprocessor macros
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -48,6 +48,7 @@
 ! CHECK-NEXT: -help Display available options
 ! CHECK-NEXT: -IAdd directory to the end of the list of include search paths
 ! CHECK-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! CHECK-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! CHECK-NEXT: -module-dir   Put MODULE files in 
 ! CHECK-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! CHECK-NEXT: -o  Write output to 
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -11,6 +11,8 @@
 //
 //===--===//
 
+#include "mlir/IR/MLIRContext.h"
+#include "mlir/Pass/PassManager.h"
 #include "flang/Frontend/CompilerInstance.h"
 #include "flang/Frontend/FrontendActions.h"
 #include "flang/Frontend/FrontendPluginRegistry.h"
@@ -148,6 +150,21 @@
 llvm::cl::ParseCommandLineOptions(numArgs + 1, args.get());
   }
 
+  // Honor -mmlir. This should happen AFTER plugins have been loaded!
+  if (!flang->frontendOpts().mlirArgs.empty()) {
+mlir::registerMLIRContextCLOptions();
+mlir::registerPassManagerCLOptions();
+unsigned numArgs = flang->frontendOpts().mlirArgs.size();
+auto args = std::make_unique(numArgs + 2);
+args[0] = "flang (MLIR option parsing)";
+
+for (unsigned i = 0; i != numArgs; ++i)
+  args[i + 1] = flang->frontendOpts().mlirArgs[i].c_str();
+
+args[numArgs + 1] = nullptr;
+llvm::cl::ParseCommandLineOptions(numArgs + 1, args.get());
+  }
+
   // If there were errors in processing arguments, don't do anything else.
   if (flang->diagnostics().hasErrorOccurred()) {
 return false;
Index: flang/lib/FrontendTool/CMakeLists.txt
=

[PATCH] D123211: [flang][driver] Add support for generating LLVM bytecode files

2022-04-12 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

In D123211#3435421 , @rovka wrote:

> Is there actually a significant difference, besides the naming (which is easy 
> to change)? AFAICT the BackendAction isn't initializing anything 
> backend-related except very close to where it's using it, so that can happen 
> inside a switch/if branch.

Currently the driver does the bare minimum to generate machine code, hence in 
practice both actions are near identical. I expect this to change, but I might 
be wrong :)

> I was thinking also about the code for generating the output file, which can 
> be folded into the switch from BackendAction. If you consider that too, it 
> becomes a very large percentage of EmitLLVMBitcodeAction::ExecuteAction that 
> can be shared.

Ack!

> Ok. IMO the template method pattern would work well here (or less formally, 
> just a simple switch to the same effect), but I can understand if you think 
> it's premature to go that route.

Definitely not objecting code re-use! :) But I would like to wait for a few 
patches for optimisation pipelines to land first. And if anyone feels 
differently and sends a patch, I'd be alright with that.




Comment at: flang/lib/Frontend/FrontendActions.cpp:491
+  // Create and configure `TargetMachine`
+  std::unique_ptr TM;
+

ekieri wrote:
> Is there a reason why use TM.reset instead of initialising TM like you do 
> with os below?
Good question!

Note that [[ 
https://github.com/llvm/llvm-project/blob/3d0e0e1027203fe5e89104ad81ee7bb53e525f95/llvm/include/llvm/MC/TargetRegistry.h#L446-L452
 | createTargetMachine ]] that I use below returns a plain pointer. [[ 
https://github.com/llvm/llvm-project/blob/3d0e0e1027203fe5e89104ad81ee7bb53e525f95/clang/include/clang/Frontend/CompilerInstance.h#L703-L706
 | createDefaultOutputFile ]] that I use for initialising `os` below returns 
`std::unique_ptr`. IIUC, I can only [[ 
https://en.cppreference.com/w/cpp/memory/unique_ptr/reset | reset ]] a 
`unique_ptr` (like `TM`) with a plain pointer.

Have I missed anything?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123211/new/

https://reviews.llvm.org/D123211

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123211: [flang][driver] Add support for generating LLVM bytecode files

2022-04-13 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:491
+  // Create and configure `TargetMachine`
+  std::unique_ptr TM;
+

ekieri wrote:
> awarzynski wrote:
> > ekieri wrote:
> > > Is there a reason why use TM.reset instead of initialising TM like you do 
> > > with os below?
> > Good question!
> > 
> > Note that [[ 
> > https://github.com/llvm/llvm-project/blob/3d0e0e1027203fe5e89104ad81ee7bb53e525f95/llvm/include/llvm/MC/TargetRegistry.h#L446-L452
> >  | createTargetMachine ]] that I use below returns a plain pointer. [[ 
> > https://github.com/llvm/llvm-project/blob/3d0e0e1027203fe5e89104ad81ee7bb53e525f95/clang/include/clang/Frontend/CompilerInstance.h#L703-L706
> >  | createDefaultOutputFile ]] that I use for initialising `os` below 
> > returns `std::unique_ptr`. IIUC, I can only [[ 
> > https://en.cppreference.com/w/cpp/memory/unique_ptr/reset | reset ]] a 
> > `unique_ptr` (like `TM`) with a plain pointer.
> > 
> > Have I missed anything?
> Well, I had missed that. Thanks! Let's see if I got it right this time.
> 
> So unique_ptr has an _explicit_ constructor taking a raw pointer 
> ([[https://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr | 
> constructor (2)]]). So as you say (if I interpreted you correctly),
> 
>   std::unique_ptr TM = 
> theTarget->createTargetMachine(...);
> 
> does not work, as it requires an implicit conversion from raw to unique 
> pointer. But constructor syntax should (and does for me) work:
> 
>   std::unique_ptr 
> TM(theTarget->createTargetMachine(...));
> 
> as this makes the conversion explicit. Does this make sense, or did I miss 
> something more?
> Does this make sense, or did I miss something more?

Yes, I'm the one who missed something here :) Many thanks for pointing this out!

I convinced myself that I checked this, but clearly I didn't. And I confused 
the copy-assignment with a proper constructor. Every day is a school day!

I'll merge this shortly and I will incorporate your suggestion. Thanks for your 
patience going over this with me :)




Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123211/new/

https://reviews.llvm.org/D123211

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123211: [flang][driver] Add support for generating LLVM bytecode files

2022-04-13 Thread Andrzej Warzynski via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdd56939a4b04: [flang][driver] Add support for generating 
LLVM bytecode files (authored by awarzynski).

Changed prior to commit:
  https://reviews.llvm.org/D123211?vs=420862&id=422453#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123211/new/

https://reviews.llvm.org/D123211

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/CMakeLists.txt
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm-bc.f90

Index: flang/test/Driver/emit-llvm-bc.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm-bc.f90
@@ -0,0 +1,19 @@
+! Test the options for generating LLVM byte-code `-emit-llvm-bc` option
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang -emit-llvm -c %s -o - | llvm-dis -o - | FileCheck %s
+! RUN: %flang_fc1 -emit-llvm-bc %s -o - | llvm-dis -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -71,6 +71,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm-bc  Build ASTs then convert to LLVM, emit .bc file
 ! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
Index: flang/test/CMakeLists.txt
===
--- flang/test/CMakeLists.txt
+++ flang/test/CMakeLists.txt
@@ -55,6 +55,7 @@
   fir-opt
   tco
   bbc
+  llvm-dis
   llvm-objdump
   split-file
 )
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -37,6 +37,8 @@
 return std::make_unique();
   case EmitLLVM:
 return std::make_unique();
+  case EmitLLVMBitcode:
+return std::make_unique();
   case EmitObj:
 return std::make_unique(
 BackendAction::BackendActionTy::Backend_EmitObj);
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -33,6 +33,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/TargetTransformInfo.h"
+#include "llvm/Bitcode/BitcodeWriterPass.h"
 #include "llvm/IR/LegacyPassManager.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Passes/PassBuilder.h"
@@ -472,6 +473,48 @@
   llvmModule->print(*os, /*AssemblyAnnotationWriter=*/nullptr);
 }
 
+void EmitLLVMBitcodeAction::ExecuteAction() {
+  CompilerInstance &ci = this->instance();
+  // Generate an LLVM module if it's not already present (it will already be
+  // present if the input file is an LLVM IR/BC file).
+  if (!llvmModule)
+GenerateLLVMIR();
+
+  // Create and configure `Target`
+  std::string error;
+  std::string theTriple = llvmModule->getTargetTriple();
+  const llvm::Target *theTarget =
+  llvm::TargetRegistry::lookupTarget(theTriple, error);
+  assert(theTarget && "Failed to create Target");
+
+  // Create and configure `TargetMachine`
+  std::unique_ptr TM(
+  theTarget->createTargetMachine(theTriple, /*CPU=*/"",
+  /*Features=*/"", llvm::TargetOptions(), llvm::None));
+  assert(TM && "Failed to create TargetMachine");
+  llvmModule->setDataLayout(TM->createDataLayout());
+
+  // Generate an output file
+  std::unique_ptr os = ci.CreateDefaultOutputFile(
+  /*Binary=*/true, /*InFile=*/GetCurrentFileOrBufferName(), "bc");
+  if (!os) {
+unsigned diagID = ci.diagnostics().getCustomDiagID(
+clang::DiagnosticsEngine::Error, "failed to create the output file");
+ci.diagnostics().Report(diagID);
+return;
+  }
+
+  // Set-up the pass manager
+  llvm::ModulePassManager MPM;
+  llvm::ModuleAnalysisManager MAM;
+  llvm::PassBuilder PB(TM.get());
+  PB.registerModuleAnalyses(MAM);
+  MPM.addPass(llvm::BitcodeWriterPass(*os));
+
+  // Run the passes
+  MPM.run(*llvmModule, MAM);
+}
+
 void EmitMLIRAction::ExecuteAc

[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-13 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp:15
+#include "mlir/IR/MLIRContext.h"
+#include "mlir/Pass/PassManager.h"
 #include "flang/Frontend/CompilerInstance.h"

rovka wrote:
> Nit: Should these come after the llvm/ headers? (So it's alphabetical except 
> for flang, which may go first)
Thanks, I will fix this before merging!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123297/new/

https://reviews.llvm.org/D123297

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-13 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Thank you all for your feedback!

**CMake integration** 
I have a couple more data points. I've experimented with CMake using Tin's 
CMake PR . I 
confirm that together with this patch, I was able to build a small CMake 
project:

  -- The Fortran compiler identification is LLVMFlang 15.0.0
  -- Detecting Fortran compiler ABI info
  -- Detecting Fortran compiler ABI info - done
  -- Check for working Fortran compiler: /home/build/release/bin/flang-new - 
skipped
  -- Configuring done
  -- Generating done
  -- Build files have been written to: /home/work/cmake_test

As you can see, the compiler discovery worked fine (I was able to build and 
executable using the CMake generated Make files). I also tried the same 
experiment with an extra flag (Option 2 above) and that didn't work. I 
investigated a bit and discovered that internally CMake calls try_compile 

 (CMake docs ). I 
don't see  any way to pass custom compiler options there (i.e. `try_compile` 
expects `flang-new file.f90` to just work). This makes me rather hesitant to 
pursue Option 2 at all.

@sscalpone I hope that this answers your question. I'm happy to re-open that PR 
myself, but it would probably make more sense for Tin to do it (since he wrote 
it originally). Either way, we will be making sure that it's attributed to Tin.

I think that it's also worth taking into account CMake's release cycle. Based 
on the following, it looks like a new version is released every March, July and 
November:

- https://discourse.cmake.org/c/announcements/8
- https://github.com/Kitware/CMake/releases

It would be extremely helpful to align adding CMake support for LLVM Flang with 
LLVM releases.

**LLVM 15 Release**
While people seem to lean towards Option 3, I would like this change to be 
merged on time for LLVM 15. LLVM 16 will be out in 2023 - lets not wait that 
long. Also, with no public progress tracker for upstreaming, I would really 
like to make sure that there is a cut off date for this to land in LLVM.

**Other points**

In D122008#3427407 , @sscalpone wrote:

> As I said this morning, I prefer to wait with this patch until the 
> upstreaming is finished.  The reason is not only to do with upstreaming, but 
> also with a concurrent effort to button up any assertion and runtime errors 
> so the initial user experience is better.

Can you give us an indication when to expect this to be completed? Also, like 
@richard.barton.arm pointed out, people already can see the issues that you 
mentioned even without this patch (i.e. miscompilation errors are orthogonal  
to this).

Note that this is only the first step. We still need to rename `flang-new` as 
`flang`. That's likely going to require a separate discussion. In fact, from my 
experience most people new to LLVM Flang use `flang` rather than `flang-new` 
and  most (all?) find it very confusing. This change is unlikely to change 
their perception of LLVM Flang because it only affects `flang-new`.

Lastly, I don't quite understand why can't we use project's documentation to 
communicate the level of support instead of artificially delaying patches like 
this one. This is what we currently claim (extracted from index.md 
, 
contributed in https://reviews.llvm.org/D120067 by myself):

> While it is capable of generating executables for a number of examples, some 
> functionality is still missing.

I wrote that, perhaps naively, believing that this patch (or something similar) 
would soon be merged. In any case, if Flang developers are concerned how LLVM 
Flang is perceived by compiler users, then could we please fix this through 
better documentation and LLVM release notes?

**New proposal**
@rovka and @rouson , I know that you voted for Option 2, but after my CMake 
experiment I feel that we should really choose between Option 1 and 3. As there 
isn't enough support for Option 1, we should probably park this for now. Please 
let me know if Option 2 would unblock any of you (or anyone else!) and we can 
re-visit. Otherwise, lets wait a bit. Our goal is to have this merged in time 
for LLVM 15.

Thank you all for reading,
Andrzej


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122008/new/

https://reviews.llvm.org/D122008

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-13 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 422525.
awarzynski added a comment.

Updates based on feedback from @MaskRay (thank you!)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122008/new/

https://reviews.llvm.org/D122008

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  flang/include/flang/Runtime/stop.h
  flang/runtime/CMakeLists.txt
  flang/runtime/FortranMain/CMakeLists.txt
  flang/runtime/FortranMain/Fortran_main.c
  flang/test/CMakeLists.txt
  flang/test/Driver/linker-flags.f90

Index: flang/test/Driver/linker-flags.f90
===
--- /dev/null
+++ flang/test/Driver/linker-flags.f90
@@ -0,0 +1,30 @@
+! Verify that the Fortran runtime libraries are present in the linker
+! invocation. These libraries are added on top of other standard runtime
+! libraries that the Clang driver will include.
+
+! NOTE: The additional linker flags tested here are currently specified in
+! clang/lib/Driver/Toolchains/Gnu.cpp. This makes the current implementation GNU
+! (Linux) specific. The following line will make sure that this test is skipped
+! on Windows. Ideally we should find a more robust way of testing this.
+! REQUIRES: shell
+! UNSUPPORTED: darwin, macos
+
+!
+! RUN COMMAND
+!
+! RUN: %flang -### --ld-path=/usr/bin/ld %S/Inputs/hello.f90 2>&1 | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! Compiler invocation to generate the object file
+! CHECK-LABEL: {{.*}} "-emit-obj"
+! CHECK-SAME:  "-o" "[[object_file:.*]]" {{.*}}Inputs/hello.f90
+
+! Linker invocation to generate the executable
+! CHECK-LABEL:  "/usr/bin/ld"
+! CHECK-SAME: "[[object_file]]"
+! CHECK-SAME: -lFortran_main
+! CHECK-SAME: -lFortranRuntime
+! CHECK-SAME: -lFortranDecimal
+! CHECK-SAME: -lm
Index: flang/test/CMakeLists.txt
===
--- flang/test/CMakeLists.txt
+++ flang/test/CMakeLists.txt
@@ -58,6 +58,9 @@
   llvm-dis
   llvm-objdump
   split-file
+  FortranRuntime
+  Fortran_main
+  FortranDecimal
 )
 
 if (FLANG_INCLUDE_TESTS)
Index: flang/runtime/FortranMain/Fortran_main.c
===
--- /dev/null
+++ flang/runtime/FortranMain/Fortran_main.c
@@ -0,0 +1,21 @@
+//===-- runtime/FortranMain/Fortran_main.c ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "flang/Runtime/main.h"
+#include "flang/Runtime/stop.h"
+
+/* main entry into PROGRAM */
+void _QQmain();
+
+/* C main stub */
+int main(int argc, const char *argv[], const char *envp[]) {
+  RTNAME(ProgramStart)(argc, argv, envp);
+  _QQmain();
+  RTNAME(ProgramEndStatement)();
+  return 0;
+}
Index: flang/runtime/FortranMain/CMakeLists.txt
===
--- /dev/null
+++ flang/runtime/FortranMain/CMakeLists.txt
@@ -0,0 +1,3 @@
+llvm_add_library(Fortran_main STATIC
+  Fortran_main.c
+)
Index: flang/runtime/CMakeLists.txt
===
--- flang/runtime/CMakeLists.txt
+++ flang/runtime/CMakeLists.txt
@@ -30,6 +30,8 @@
 # with different names
 include_directories(AFTER ${CMAKE_CURRENT_BINARY_DIR})
 
+add_subdirectory(FortranMain)
+
 add_flang_library(FortranRuntime
   ISO_Fortran_binding.cpp
   allocatable.cpp
Index: flang/include/flang/Runtime/stop.h
===
--- flang/include/flang/Runtime/stop.h
+++ flang/include/flang/Runtime/stop.h
@@ -27,7 +27,7 @@
 NORETURN void RTNAME(ProgramEndStatement)(NO_ARGUMENTS);
 
 // Extensions
-NORETURN void RTNAME(Exit)(int status = EXIT_SUCCESS);
+NORETURN void RTNAME(Exit)(int status DEFAULT_VALUE(EXIT_SUCCESS));
 NORETURN void RTNAME(Abort)(NO_ARGUMENTS);
 
 // Crash with an error message when the program dynamically violates a Fortran
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -382,6 +382,28 @@
  Exec, CmdArgs, Inputs, Output));
 }
 
+static void addFortranRuntimeLibraryPath(const ToolChain &TC,
+ const ArgList &Args,
+ ArgStringList &CmdArgs) {
+  // Default to the /../lib directory. This works fine on the
+  // platforms that we have tested so far. We will probably have to re-fine
+  // this in the future. In particular:
+  //* on some platforms, we may need to use lib64 instead of lib
+  //* this logic should also work on other similar platforms too, so we

[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-14 Thread Andrzej Warzynski via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6c93e1d329e6: [flang][driver] Add support for `-mmlir` 
(authored by awarzynski).

Changed prior to commit:
  https://reviews.llvm.org/D123297?vs=422163&id=422787#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123297/new/

https://reviews.llvm.org/D123297

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/mllvm_vs_mmlir.f90

Index: flang/test/Driver/mllvm_vs_mmlir.f90
===
--- /dev/null
+++ flang/test/Driver/mllvm_vs_mmlir.f90
@@ -0,0 +1,19 @@
+! Verify that `-mllvm` options are forwarded to LLVM and `-mmlir` to MLIR.
+
+! In practice, '-mmlir --help' is a super-set of '-mllvm --help' and that limits what we can test here. With a better seperation of
+! LLVM, MLIR and Flang global options, we should be able to write a stricter test.
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1  -mmlir --help | FileCheck %s --check-prefix=MLIR
+! RUN: %flang_fc1  -mllvm --help | FileCheck %s --check-prefix=MLLVM
+
+!
+! EXPECTED OUTPUT
+!
+! MLIR: flang (MLIR option parsing) [options]
+! MLIR: --mlir-{{.*}}
+
+! MLLVM: flang (LLVM option parsing) [options]
+! MLLVM-NOT: --mlir-{{.*}}
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -48,6 +48,7 @@
 ! HELP-NEXT: -help  Display available options
 ! HELP-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! HELP-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! HELP-NEXT: -module-dir   Put MODULE files in 
 ! HELP-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! HELP-NEXT: -o   Write output to 
@@ -124,6 +125,7 @@
 ! HELP-FC1-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-FC1-NEXT: -load Load the named plugin (dynamic shared object)
 ! HELP-FC1-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! HELP-FC1-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! HELP-FC1-NEXT: -module-dir   Put MODULE files in 
 ! HELP-FC1-NEXT: -module-suffix  Use  as the suffix for module files (the default value is `.mod`)
 ! HELP-FC1-NEXT: -nocpp Disable predefined and command line preprocessor macros
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -48,6 +48,7 @@
 ! CHECK-NEXT: -help Display available options
 ! CHECK-NEXT: -IAdd directory to the end of the list of include search paths
 ! CHECK-NEXT: -mllvm  Additional arguments to forward to LLVM's option processing
+! CHECK-NEXT: -mmlir  Additional arguments to forward to MLIR's option processing
 ! CHECK-NEXT: -module-dir   Put MODULE files in 
 ! CHECK-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! CHECK-NEXT: -o  Write output to 
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -19,6 +19,8 @@
 #include "llvm/Option/Option.h"
 #include "llvm/Support/BuryPointer.h"
 #include "llvm/Support/CommandLine.h"
+#include "mlir/IR/MLIRContext.h"
+#include "mlir/Pass/PassManager.h"
 
 namespace Fortran::frontend {
 
@@ -150,6 +152,21 @@
 llvm::cl::ParseCommandLineOptions(numArgs + 1, args.get());
   }
 
+  // Honor -mmlir. This should happen AFTER plugins have been loaded!
+  if (!flang->frontendOpts().mlirArgs.empty()) {
+mlir::registerMLIRContextCLOptions();
+mlir::registerPassManagerCLOptions();
+unsigned numArgs = flang->frontendOpts().mlirArgs.size();
+auto args = std::make_unique(numArgs + 2);
+args[0] = "flang (MLIR option parsing)";
+
+for (unsigned i = 0; i != numArgs; ++i)
+  args[i + 1] = flang->frontendOpts().mlirArgs[i].c_str();
+
+args[numArgs + 1] = nullptr;
+llvm::cl::ParseCommandLineOptions(numArgs + 1, args.get());
+  }
+
   // If there were errors in proc

[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-14 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: clang/include/clang/Driver/Options.td:3272
   MarshallingInfoStringVector>;
+def mmlir : Separate<["-"], "mmlir">,Flags<[CoreOption,FC1Option,FlangOption]>,
+  HelpText<"Additional arguments to forward to MLIR's option processing">;

MaskRay wrote:
> 
Thanks, included in the final version!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D123297/new/

https://reviews.llvm.org/D123297

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-14 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

@h-vetinari & @rouson, thanks for the encouragement!

In D122008#3450214 , @h-vetinari 
wrote:

> I'd be more than a little surprised that there's no way to do this. Have you 
> tried CMAKE_Fortran_FLAGS 
> ? AFAICT, 
> the environment variables should be respected.

I completely forgot about `CMAKE_Fortran_FLAGS`! Indeed, it worked :) I really 
appreciate you doing all that digging and the suggestion itself! Yes, sounds 
like we can return to Option 2, which is fantastic news and great team effort!

I will post an updated version of this patch shortly. My suggestion for the new 
flag: `-flang-experimental-exec`. Hopefully not too long or to vague and 
informative enough. WDYT?

In D122008#3450346 , @rouson wrote:

> I don't know the time required to complete the remaining tasks, but the 
> following issues show 216 of 235 tasks completed with 2 in progress:

Thanks for that executive summary @rouson, it does look encouraging :) 
Unfortunately, upstreaming is effectively on hold ATM. People are not too keen 
to commit to any dates (understandable), but we (Arm) will continue working 
towards the LLVM 15 target (fingers crossed!).

**Summary**
AFAICT, Option 2 addresses all the issues raised here and (more importantly) 
unblocks a few new streams of development. IMO, it's a very good compromise and 
we should go ahead with it. I will leave this here for a few more days in case 
people have more comments.

Thank you,
-Andrzej


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122008/new/

https://reviews.llvm.org/D122008

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-14 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 422836.
awarzynski added a comment.

Add a flang, `-flang-experimental-exec`, to guard the new functionality.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122008/new/

https://reviews.llvm.org/D122008

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Gnu.cpp
  flang/include/flang/Runtime/stop.h
  flang/runtime/CMakeLists.txt
  flang/runtime/FortranMain/CMakeLists.txt
  flang/runtime/FortranMain/Fortran_main.c
  flang/test/CMakeLists.txt
  flang/test/Driver/linker-flags.f90

Index: flang/test/Driver/linker-flags.f90
===
--- /dev/null
+++ flang/test/Driver/linker-flags.f90
@@ -0,0 +1,30 @@
+! Verify that the Fortran runtime libraries are present in the linker
+! invocation. These libraries are added on top of other standard runtime
+! libraries that the Clang driver will include.
+
+! NOTE: The additional linker flags tested here are currently specified in
+! clang/lib/Driver/Toolchains/Gnu.cpp. This makes the current implementation GNU
+! (Linux) specific. The following line will make sure that this test is skipped
+! on Windows. Ideally we should find a more robust way of testing this.
+! REQUIRES: shell
+! UNSUPPORTED: darwin, macos
+
+!
+! RUN COMMAND
+!
+! RUN: %flang -### --ld-path=/usr/bin/ld %S/Inputs/hello.f90 2>&1 | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! Compiler invocation to generate the object file
+! CHECK-LABEL: {{.*}} "-emit-obj"
+! CHECK-SAME:  "-o" "[[object_file:.*]]" {{.*}}Inputs/hello.f90
+
+! Linker invocation to generate the executable
+! CHECK-LABEL:  "/usr/bin/ld"
+! CHECK-SAME: "[[object_file]]"
+! CHECK-SAME: -lFortran_main
+! CHECK-SAME: -lFortranRuntime
+! CHECK-SAME: -lFortranDecimal
+! CHECK-SAME: -lm
Index: flang/test/CMakeLists.txt
===
--- flang/test/CMakeLists.txt
+++ flang/test/CMakeLists.txt
@@ -58,6 +58,9 @@
   llvm-dis
   llvm-objdump
   split-file
+  FortranRuntime
+  Fortran_main
+  FortranDecimal
 )
 
 if (FLANG_INCLUDE_TESTS)
Index: flang/runtime/FortranMain/Fortran_main.c
===
--- /dev/null
+++ flang/runtime/FortranMain/Fortran_main.c
@@ -0,0 +1,21 @@
+//===-- runtime/FortranMain/Fortran_main.c ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "flang/Runtime/main.h"
+#include "flang/Runtime/stop.h"
+
+/* main entry into PROGRAM */
+void _QQmain();
+
+/* C main stub */
+int main(int argc, const char *argv[], const char *envp[]) {
+  RTNAME(ProgramStart)(argc, argv, envp);
+  _QQmain();
+  RTNAME(ProgramEndStatement)();
+  return 0;
+}
Index: flang/runtime/FortranMain/CMakeLists.txt
===
--- /dev/null
+++ flang/runtime/FortranMain/CMakeLists.txt
@@ -0,0 +1,3 @@
+llvm_add_library(Fortran_main STATIC
+  Fortran_main.c
+)
Index: flang/runtime/CMakeLists.txt
===
--- flang/runtime/CMakeLists.txt
+++ flang/runtime/CMakeLists.txt
@@ -30,6 +30,8 @@
 # with different names
 include_directories(AFTER ${CMAKE_CURRENT_BINARY_DIR})
 
+add_subdirectory(FortranMain)
+
 add_flang_library(FortranRuntime
   ISO_Fortran_binding.cpp
   allocatable.cpp
Index: flang/include/flang/Runtime/stop.h
===
--- flang/include/flang/Runtime/stop.h
+++ flang/include/flang/Runtime/stop.h
@@ -27,7 +27,7 @@
 NORETURN void RTNAME(ProgramEndStatement)(NO_ARGUMENTS);
 
 // Extensions
-NORETURN void RTNAME(Exit)(int status = EXIT_SUCCESS);
+NORETURN void RTNAME(Exit)(int status DEFAULT_VALUE(EXIT_SUCCESS));
 NORETURN void RTNAME(Abort)(NO_ARGUMENTS);
 
 // Crash with an error message when the program dynamically violates a Fortran
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -382,6 +382,28 @@
  Exec, CmdArgs, Inputs, Output));
 }
 
+static void addFortranRuntimeLibraryPath(const ToolChain &TC,
+ const ArgList &Args,
+ ArgStringList &CmdArgs) {
+  // Default to the /../lib directory. This works fine on the
+  // platforms that we have tested so far. We will probably have to re-fine
+  // this in the future. In particular:
+  //* on some platforms, we may need to use lib64 instead of lib
+  //* this 

[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-14 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 422841.
awarzynski added a comment.

Update the tests after the previous update


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122008/new/

https://reviews.llvm.org/D122008

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Gnu.cpp
  flang/include/flang/Runtime/stop.h
  flang/runtime/CMakeLists.txt
  flang/runtime/FortranMain/CMakeLists.txt
  flang/runtime/FortranMain/Fortran_main.c
  flang/test/CMakeLists.txt
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/linker-flags.f90

Index: flang/test/Driver/linker-flags.f90
===
--- /dev/null
+++ flang/test/Driver/linker-flags.f90
@@ -0,0 +1,30 @@
+! Verify that the Fortran runtime libraries are present in the linker
+! invocation. These libraries are added on top of other standard runtime
+! libraries that the Clang driver will include.
+
+! NOTE: The additional linker flags tested here are currently specified in
+! clang/lib/Driver/Toolchains/Gnu.cpp. This makes the current implementation GNU
+! (Linux) specific. The following line will make sure that this test is skipped
+! on Windows. Ideally we should find a more robust way of testing this.
+! REQUIRES: shell
+! UNSUPPORTED: darwin, macos
+
+!
+! RUN COMMAND
+!
+! RUN: %flang -### -flang-experimental-exec --ld-path=/usr/bin/ld %S/Inputs/hello.f90 2>&1 | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! Compiler invocation to generate the object file
+! CHECK-LABEL: {{.*}} "-emit-obj"
+! CHECK-SAME:  "-o" "[[object_file:.*]]" {{.*}}Inputs/hello.f90
+
+! Linker invocation to generate the executable
+! CHECK-LABEL:  "/usr/bin/ld"
+! CHECK-SAME: "[[object_file]]"
+! CHECK-SAME: -lFortran_main
+! CHECK-SAME: -lFortranRuntime
+! CHECK-SAME: -lFortranDecimal
+! CHECK-SAME: -lm
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -38,6 +38,8 @@
 ! HELP-NEXT: -finput-charset= Specify the default character set for source files
 ! HELP-NEXT: -fintrinsic-modules-path 
 ! HELP-NEXT:Specify where to find the compiled intrinsic modules
+! HELP-NEXT: -flang-experimental-exec
+! HELP-NEXT:Enable support for generating executables (experimental)
 ! HELP-NEXT: -flarge-sizes  Use INTEGER(KIND=8) for the result type in size-related intrinsics
 ! HELP-NEXT: -flogical-abbreviations Enable logical abbreviations
 ! HELP-NEXT: -fno-automatic Implies the SAVE attribute for non-automatic local objects in subprograms unless RECURSIVE
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -38,6 +38,8 @@
 ! CHECK-NEXT: -finput-charset= Specify the default character set for source files
 ! CHECK-NEXT: -fintrinsic-modules-path 
 ! CHECK-NEXT:Specify where to find the compiled intrinsic modules
+! CHECK-NEXT: -flang-experimental-exec
+! CHECK-NEXT:Enable support for generating executables (experimental)
 ! CHECK-NEXT: -flarge-sizes  Use INTEGER(KIND=8) for the result type in size-related intrinsics
 ! CHECK-NEXT: -flogical-abbreviations Enable logical abbreviations
 ! CHECK-NEXT: -fno-automatic Implies the SAVE attribute for non-automatic local objects in subprograms unless RECURSIVE
Index: flang/test/CMakeLists.txt
===
--- flang/test/CMakeLists.txt
+++ flang/test/CMakeLists.txt
@@ -58,6 +58,9 @@
   llvm-dis
   llvm-objdump
   split-file
+  FortranRuntime
+  Fortran_main
+  FortranDecimal
 )
 
 if (FLANG_INCLUDE_TESTS)
Index: flang/runtime/FortranMain/Fortran_main.c
===
--- /dev/null
+++ flang/runtime/FortranMain/Fortran_main.c
@@ -0,0 +1,21 @@
+//===-- runtime/FortranMain/Fortran_main.c ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "flang/Runtime/main.h"
+#include "flang/Runtime/stop.h"
+
+/* main entry into PROGRAM */
+void _QQmain();
+
+/* C main stub */
+int main(int argc, const char *argv[], const char *envp[]) {
+  RTNAME(ProgramStart)(argc, argv, envp);
+  _QQmain();
+  RTNAME(ProgramEndStatement)();
+  return 0;
+}
Index: flang/runtime/FortranMain/CMakeLists.txt
===
--- /

[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-19 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

In D122008#3456445 , @clementval 
wrote:

> Do you plan to discuss this again during the next call? Note that today is a 
> holiday in various country in Europe (maybe elsewhere too) so the one on 4/27 
> is probably better.

To be perfectly honest, I wasn't planning to.

The main reason to bring this up in one of our community calls was to increase 
the visibility of this patch. I feel that that goal has been achieved. Keeping 
the discussion here means that even people who are unable to join our calls can 
participate and share their view. As such, discussing on Phabricator is more 
inclusive.

While I appreciate that some people expressed preference for Option 3, it 
seemed to me that Option 2 is a compromise that will work for everyone. It 
hides the new functionality behind a flag and makes it very counter-intuitive 
to use. The flag itself makes it clear that this functionality is experimental. 
At the same time, Option 2 is sufficient to unblock progress in other areas.

If folks disagree and feel that Option 2 is still problematic, could you 
elaborate "why" and suggest an alternative? There's no need to wait for the 
next call to discuss this.

Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122008/new/

https://reviews.llvm.org/D122008

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-20 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Btw, if there are no new comments, I would like to merge this in the coming 
days.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122008/new/

https://reviews.llvm.org/D122008

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-21 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

In D122008#3462665 , @klausler wrote:

> New comments or not, this step remains premature from my perspective.

Let me make `-flang-experimental-exec` a "hidden" option then. This way this 
flag (and the functionality that it enables) will be less discoverable (we 
still will be to use it). We will be removing it at some point anyway.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D122008/new/

https://reviews.llvm.org/D122008

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-04 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski created this revision.
awarzynski added reviewers: rovka, kiranchandramohan, clementval, schweitz.
Herald added subscribers: sdasgup3, wenzhicui, wrengr, Chia-hungDuan, dcaballe, 
cota, teijeong, rdzhabarov, tatianashp, dang, msifontes, jurahul, Kayjukh, 
grosul1, Joonsoo, liufengdb, aartbik, mgester, arpith-jacob, antiagainst, 
shauheen, rriddle, mehdi_amini, mgorny.
Herald added a reviewer: sscalpone.
Herald added a project: Flang.
awarzynski requested review of this revision.
Herald added subscribers: cfe-commits, stephenneuendorffer, nicolasvasilache, 
jdoerfert.
Herald added a project: clang.

This patch adds support for generating MLIR files in Flang's frontend
driver (i.e. `flang-new -fc1`). `-emit-fir` is added as an alias for
`-emit-mlir`. We may want to decide to split the two in the future.

A new parent class for code-gen frontend actions is introduced:
`CodeGenAction`. We will be using this class to encapsulate logic shared
between all code-generation actions, but not required otherwise. For
now, it will:

- run prescanning, parsing and semantic checks,
- lower the input to MLIR.

`EmitObjAction` is updated to inherit from this class. This means that
the behaviour of `flang-new -fc1 -emit-obj` is also updated (previously,
it would just exit immediately). This change required
`flang/test/Driver/syntax-only.f90` to be updated.

For `-emit-fir`, a specialisation of `CodeGenAction` is introduced:
`EmitMLIRAction`. The key logic for this class is implemented in
`EmitMLIRAction::ExecuteAction`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D118985

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-mlir.f90
  flang/test/Driver/syntax-only.f90

Index: flang/test/Driver/syntax-only.f90
===
--- flang/test/Driver/syntax-only.f90
+++ flang/test/Driver/syntax-only.f90
@@ -1,24 +1,28 @@
-! Verify that the compiler driver correctly processes `-fsyntax-only`. By
-! default it will try to run code-generation, but that's not supported yet. We
-! don't need to test the frontend driver here - it runs `-fsyntax-only` by
-! default.
+! Verify that the driver correctly processes `-fsyntax-only`.
+!
+! By default, the compiler driver (`flang`) will create actions/phases to
+! generate machine code (i.e. object files). The `-fsyntax-only` flag is a
+! "phase-control" flag that controls this behavior and makes the driver stop
+! once the semantic checks have been run. The frontend driver (`flang -fc1`)
+! runs `-fsyntax-only` by default (i.e. that's the default action), so the flag
+! can be skipped.
 
 !---
 ! RUN LINES
 !---
-! RUN: not %flang -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=FSYNTAX_ONLY
+! RUN: %flang -fsyntax-only %s 2>&1 | FileCheck %s --allow-empty
+! RUN: %flang_fc1 %s 2>&1 | FileCheck %s --allow-empty
+
 ! RUN: not %flang  %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
+! RUN: not %flang_fc1 -emit-obj %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
 
 !-
 ! EXPECTED OUTPUT
 !-
-! FSYNTAX_ONLY: IF statement is not allowed in IF statement
-! FSYNTAX_ONLY_NEXT: Semantic errors in {{.*}}syntax-only.f90
-
+! CHECK-NOT: error
 ! NO_FSYNTAX_ONLY: error: code-generation is not available yet
 
 !---
 ! INPUT
 !---
-IF (A > 0.0) IF (B < 0.0) A = LOG (A)
-END
+end program
Index: flang/test/Driver/emit-mlir.f90
===
--- /dev/null
+++ flang/test/Driver/emit-mlir.f90
@@ -0,0 +1,21 @@
+! The the `-emit-fir` option
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang_fc1 -emit-mlir %s -o - | FileCheck %s
+! RUN: %flang_fc1 -emit-fir %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: module attributes {
+! CHECK-LABEL: func @_QQmain() {
+! CHECK-NEXT:  return
+! CHECK-NEXT: }
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
 ! HELP-FC1-NEXT: -falternative-parameter-statement
Index: fl

[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-04 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

`fir-dev` PR: https://github.com/flang-compiler/f18-llvm-project/pull/1008. 
I've also incorporated a few small changes from the subsequent PRs.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D118985/new/

https://reviews.llvm.org/D118985

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-04 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski created this revision.
awarzynski added reviewers: rovka, kiranchandramohan, clementval, schweitz.
Herald added a reviewer: sscalpone.
Herald added a subscriber: dang.
Herald added a project: Flang.
awarzynski requested review of this revision.
Herald added subscribers: cfe-commits, jdoerfert.
Herald added a project: clang.

This patch adds support for the `-emit-llvm` option in the frontend
driver (i.e. `flang-new -fc1`). Similarly to Clang, `flang-new -fc1
-emit-llvm file.f` will generate a textual LLVM IR file.

Depends on D118985 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D119012

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm.f90
  flang/unittests/Frontend/FrontendActionTest.cpp

Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -161,4 +161,31 @@
   .contains(
   ":1:14: error: IF statement is not allowed in IF statement\n"));
 }
+
+TEST_F(FrontendActionTest, EmitLLVM) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitLLVM;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
+  .contains("define void @_QQmain()"));
+}
 } // namespace
Index: flang/test/Driver/emit-llvm.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm.f90
@@ -0,0 +1,19 @@
+! The the `-emit-llvm` option
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1 -emit-llvm %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: ; ModuleID = 'FIRModule'
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -35,6 +35,8 @@
 return std::make_unique();
   case EmitMLIR:
 return std::make_unique();
+  case EmitLLVM:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -14,6 +14,7 @@
 #include "flang/Lower/Bridge.h"
 #include "flang/Lower/PFTBuilder.h"
 #include "flang/Lower/Support/Verifier.h"
+#include "flang/Optimizer/Support/FIRContext.h"
 #include "flang/Optimizer/Support/InitFIR.h"
 #include "flang/Optimizer/Support/KindMapping.h"
 #include "flang/Optimizer/Support/Utils.h"
@@ -28,6 +29,7 @@
 
 #include "mlir/IR/Dialect.h"
 #include "mlir/Pass/PassManager.h"
+#include "mlir/Target/LLVMIR/ModuleTranslation.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
@@ -406,6 +408,80 @@
   ci.semantics().DumpSymbolsSources(llvm::outs());
 }
 
+#include "flang/Tools/CLOptions.inc"
+
+// Lower the previously generated MLIR module into an LLVM IR module
+

[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-04 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 406005.
awarzynski added a comment.

Add missing CMake dependency


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D118985/new/

https://reviews.llvm.org/D118985

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-mlir.f90
  flang/test/Driver/syntax-only.f90

Index: flang/test/Driver/syntax-only.f90
===
--- flang/test/Driver/syntax-only.f90
+++ flang/test/Driver/syntax-only.f90
@@ -1,24 +1,28 @@
-! Verify that the compiler driver correctly processes `-fsyntax-only`. By
-! default it will try to run code-generation, but that's not supported yet. We
-! don't need to test the frontend driver here - it runs `-fsyntax-only` by
-! default.
+! Verify that the driver correctly processes `-fsyntax-only`.
+!
+! By default, the compiler driver (`flang`) will create actions/phases to
+! generate machine code (i.e. object files). The `-fsyntax-only` flag is a
+! "phase-control" flag that controls this behavior and makes the driver stop
+! once the semantic checks have been run. The frontend driver (`flang -fc1`)
+! runs `-fsyntax-only` by default (i.e. that's the default action), so the flag
+! can be skipped.
 
 !---
 ! RUN LINES
 !---
-! RUN: not %flang -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=FSYNTAX_ONLY
+! RUN: %flang -fsyntax-only %s 2>&1 | FileCheck %s --allow-empty
+! RUN: %flang_fc1 %s 2>&1 | FileCheck %s --allow-empty
+
 ! RUN: not %flang  %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
+! RUN: not %flang_fc1 -emit-obj %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
 
 !-
 ! EXPECTED OUTPUT
 !-
-! FSYNTAX_ONLY: IF statement is not allowed in IF statement
-! FSYNTAX_ONLY_NEXT: Semantic errors in {{.*}}syntax-only.f90
-
+! CHECK-NOT: error
 ! NO_FSYNTAX_ONLY: error: code-generation is not available yet
 
 !---
 ! INPUT
 !---
-IF (A > 0.0) IF (B < 0.0) A = LOG (A)
-END
+end program
Index: flang/test/Driver/emit-mlir.f90
===
--- /dev/null
+++ flang/test/Driver/emit-mlir.f90
@@ -0,0 +1,21 @@
+! The the `-emit-fir` option
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang_fc1 -emit-mlir %s -o - | FileCheck %s
+! RUN: %flang_fc1 -emit-fir %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: module attributes {
+! CHECK-LABEL: func @_QQmain() {
+! CHECK-NEXT:  return
+! CHECK-NEXT: }
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
 ! HELP-FC1-NEXT: -falternative-parameter-statement
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -33,6 +33,8 @@
 return std::make_unique();
   case ParseSyntaxOnly:
 return std::make_unique();
+  case EmitMLIR:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/FrontendTool/CMakeLists.txt
===
--- flang/lib/FrontendTool/CMakeLists.txt
+++ flang/lib/FrontendTool/CMakeLists.txt
@@ -2,6 +2,9 @@
   ExecuteCompilerInvocation.cpp
 
   DEPENDS
+  # This makes sure that the MLIR dependencies of flangFrontend (which are
+  # transitively required here) are generated before this target is build.
+  flangFrontend
   clangBasic
 
   LINK_LIBS
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -11,7 +11,12 @@
 #include "flang/Frontend/CompilerInstance.h"
 #include "flang/Frontend/FrontendOptions.h"
 #include "flang/Frontend/PreprocessorOptions.h"
+#include "flang/Lower/Bridge.h"
 #include "fla

[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/include/flang/Frontend/FrontendActions.h:150
+//===--===//
+class CodeGenAction : public FrontendAction {
+

schweitz wrote:
> This appears in a header file. Should there be doxygen comments?
Good point, I'll add something here.



Comment at: flang/include/flang/Frontend/FrontendActions.h:160
+  std::unique_ptr mlirModule_;
+  std::unique_ptr mlirCtx_;
+  /// }

schweitz wrote:
> The LLVM coding conventions do not require trailing undescores.
Good point, I'll change this. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D118985/new/

https://reviews.llvm.org/D118985

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 406377.
awarzynski added a comment.

Removed trailing "_" from member variable names, added a comment, updated CMake 
dependencies (needed after https://reviews.llvm.org/D118966)

@schweitz, thank you for reviewing! If there are no new comments, I'll merge 
this today/tomorrow.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D118985/new/

https://reviews.llvm.org/D118985

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-mlir.f90
  flang/test/Driver/syntax-only.f90

Index: flang/test/Driver/syntax-only.f90
===
--- flang/test/Driver/syntax-only.f90
+++ flang/test/Driver/syntax-only.f90
@@ -1,24 +1,28 @@
-! Verify that the compiler driver correctly processes `-fsyntax-only`. By
-! default it will try to run code-generation, but that's not supported yet. We
-! don't need to test the frontend driver here - it runs `-fsyntax-only` by
-! default.
+! Verify that the driver correctly processes `-fsyntax-only`.
+!
+! By default, the compiler driver (`flang`) will create actions/phases to
+! generate machine code (i.e. object files). The `-fsyntax-only` flag is a
+! "phase-control" flag that controls this behavior and makes the driver stop
+! once the semantic checks have been run. The frontend driver (`flang -fc1`)
+! runs `-fsyntax-only` by default (i.e. that's the default action), so the flag
+! can be skipped.
 
 !---
 ! RUN LINES
 !---
-! RUN: not %flang -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=FSYNTAX_ONLY
+! RUN: %flang -fsyntax-only %s 2>&1 | FileCheck %s --allow-empty
+! RUN: %flang_fc1 %s 2>&1 | FileCheck %s --allow-empty
+
 ! RUN: not %flang  %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
+! RUN: not %flang_fc1 -emit-obj %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
 
 !-
 ! EXPECTED OUTPUT
 !-
-! FSYNTAX_ONLY: IF statement is not allowed in IF statement
-! FSYNTAX_ONLY_NEXT: Semantic errors in {{.*}}syntax-only.f90
-
+! CHECK-NOT: error
 ! NO_FSYNTAX_ONLY: error: code-generation is not available yet
 
 !---
 ! INPUT
 !---
-IF (A > 0.0) IF (B < 0.0) A = LOG (A)
-END
+end program
Index: flang/test/Driver/emit-mlir.f90
===
--- /dev/null
+++ flang/test/Driver/emit-mlir.f90
@@ -0,0 +1,21 @@
+! The the `-emit-fir` option
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang_fc1 -emit-mlir %s -o - | FileCheck %s
+! RUN: %flang_fc1 -emit-fir %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: module attributes {
+! CHECK-LABEL: func @_QQmain() {
+! CHECK-NEXT:  return
+! CHECK-NEXT: }
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
 ! HELP-FC1-NEXT: -falternative-parameter-statement
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -33,6 +33,8 @@
 return std::make_unique();
   case ParseSyntaxOnly:
 return std::make_unique();
+  case EmitMLIR:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/FrontendTool/CMakeLists.txt
===
--- flang/lib/FrontendTool/CMakeLists.txt
+++ flang/lib/FrontendTool/CMakeLists.txt
@@ -2,6 +2,9 @@
   ExecuteCompilerInvocation.cpp
 
   DEPENDS
+  # This makes sure that the MLIR dependencies of flangFrontend (which are
+  # transitively required here) are generated before this target is build.
+  flangFrontend
   clangBasic
 
   LINK_LIBS
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActio

[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 406380.
awarzynski added a comment.

Rebase, remove trailing "_" from member variable names


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119012/new/

https://reviews.llvm.org/D119012

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm.f90
  flang/unittests/Frontend/FrontendActionTest.cpp

Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -161,4 +161,31 @@
   .contains(
   ":1:14: error: IF statement is not allowed in IF statement\n"));
 }
+
+TEST_F(FrontendActionTest, EmitLLVM) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitLLVM;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
+  .contains("define void @_QQmain()"));
+}
 } // namespace
Index: flang/test/Driver/emit-llvm.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm.f90
@@ -0,0 +1,19 @@
+! The the `-emit-llvm` option
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1 -emit-llvm %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: ; ModuleID = 'FIRModule'
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -35,6 +35,8 @@
 return std::make_unique();
   case EmitMLIR:
 return std::make_unique();
+  case EmitLLVM:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -14,6 +14,7 @@
 #include "flang/Lower/Bridge.h"
 #include "flang/Lower/PFTBuilder.h"
 #include "flang/Lower/Support/Verifier.h"
+#include "flang/Optimizer/Support/FIRContext.h"
 #include "flang/Optimizer/Support/InitFIR.h"
 #include "flang/Optimizer/Support/KindMapping.h"
 #include "flang/Optimizer/Support/Utils.h"
@@ -28,6 +29,7 @@
 
 #include "mlir/IR/Dialect.h"
 #include "mlir/Pass/PassManager.h"
+#include "mlir/Target/LLVMIR/ModuleTranslation.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
@@ -406,6 +408,80 @@
   ci.semantics().DumpSymbolsSources(llvm::outs());
 }
 
+#include "flang/Tools/CLOptions.inc"
+
+// Lower the previously generated MLIR module into an LLVM IR module
+void CodeGenAction::GenerateLLVMIR() {
+  CompilerInstance &ci = this->instance();
+
+  fir::support::loadDialects(*mlirCtx);
+  fir::support::registerLLVMTranslation(*mlirCtx);
+
+  // Set-up the MLIR pass manager
+  fir::setTargetTriple(*mlirModule, "native");
+  auto &defKinds = ci.invocation().semanticsContext().defaultKinds();
+  fir::KindMapping kindMap(mlirCtx.get(),
+  ll

[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

This has been extracted from `fir-dev`. Original PR: 
https://github.com/flang-compiler/f18-llvm-project/pull/1113


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119012/new/

https://reviews.llvm.org/D119012

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:69
+
+  // Create a LoweringBridge
+  auto &defKinds = ci.invocation().semanticsContext().defaultKinds();

kiranchandramohan wrote:
> Nit: Can we remove the three autos below?
Sure!



Comment at: flang/lib/Frontend/FrontendActions.cpp:419
+
+  // ... otherwise, print to a file.
+  auto os{ci.CreateDefaultOutputFile(

kiranchandramohan wrote:
> Nit: Should we test the existence of such a file?
We do :) Sort of!

To me, "existence" is a low level concept. Files are handled through e.g. 
`llvm::raw_fd_ostream` (and occasionally other streams) and IMO all low level 
details should be dealt with there (and indeed are). `flang-new` should only 
verify that `os` is not a `nullptr`. If the file does not exist, `os` will be a 
`nullptr` and that's checked further down. If the file does exist, then 
everything is fine and we can move to the next step. 



Comment at: flang/lib/Frontend/FrontendActions.cpp:420
+  // ... otherwise, print to a file.
+  auto os{ci.CreateDefaultOutputFile(
+  /*Binary=*/true, /*InFile=*/GetCurrentFileOrBufferName(), "mlir")};

kiranchandramohan wrote:
> Nit: can we remove auto?
Sure!



Comment at: flang/test/Driver/emit-mlir.f90:1
+! The the `-emit-fir` option
+

kiranchandramohan wrote:
> Nit: The the
Thanks :) Also, should be `-emit-mlir` instead of  `-emit-fir`.



Comment at: flang/test/Driver/syntax-only.f90:16
-! FSYNTAX_ONLY: IF statement is not allowed in IF statement
-! FSYNTAX_ONLY_NEXT: Semantic errors in {{.*}}syntax-only.f90
-

kiranchandramohan wrote:
> Nit: Do you have another test for `fsyntax-only`?
No, but there are many tests that use it: 
https://github.com/llvm/llvm-project/blob/main/flang/test/Semantics/call17.f90



Comment at: flang/test/Driver/syntax-only.f90:23
+! CHECK-NOT: error
 ! NO_FSYNTAX_ONLY: error: code-generation is not available yet
 

kiranchandramohan wrote:
> Do we currently run the stages before codegen and then issue this error?
Yes, but this error is here only temporarily. I will be removing it shortly 
(once `-emit-obj` is implemented).


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D118985/new/

https://reviews.llvm.org/D118985

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 406398.
awarzynski added a comment.

Remove `auto`, update comment


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D118985/new/

https://reviews.llvm.org/D118985

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-mlir.f90
  flang/test/Driver/syntax-only.f90

Index: flang/test/Driver/syntax-only.f90
===
--- flang/test/Driver/syntax-only.f90
+++ flang/test/Driver/syntax-only.f90
@@ -1,24 +1,28 @@
-! Verify that the compiler driver correctly processes `-fsyntax-only`. By
-! default it will try to run code-generation, but that's not supported yet. We
-! don't need to test the frontend driver here - it runs `-fsyntax-only` by
-! default.
+! Verify that the driver correctly processes `-fsyntax-only`.
+!
+! By default, the compiler driver (`flang`) will create actions/phases to
+! generate machine code (i.e. object files). The `-fsyntax-only` flag is a
+! "phase-control" flag that controls this behavior and makes the driver stop
+! once the semantic checks have been run. The frontend driver (`flang -fc1`)
+! runs `-fsyntax-only` by default (i.e. that's the default action), so the flag
+! can be skipped.
 
 !---
 ! RUN LINES
 !---
-! RUN: not %flang -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=FSYNTAX_ONLY
+! RUN: %flang -fsyntax-only %s 2>&1 | FileCheck %s --allow-empty
+! RUN: %flang_fc1 %s 2>&1 | FileCheck %s --allow-empty
+
 ! RUN: not %flang  %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
+! RUN: not %flang_fc1 -emit-obj %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
 
 !-
 ! EXPECTED OUTPUT
 !-
-! FSYNTAX_ONLY: IF statement is not allowed in IF statement
-! FSYNTAX_ONLY_NEXT: Semantic errors in {{.*}}syntax-only.f90
-
+! CHECK-NOT: error
 ! NO_FSYNTAX_ONLY: error: code-generation is not available yet
 
 !---
 ! INPUT
 !---
-IF (A > 0.0) IF (B < 0.0) A = LOG (A)
-END
+end program
Index: flang/test/Driver/emit-mlir.f90
===
--- /dev/null
+++ flang/test/Driver/emit-mlir.f90
@@ -0,0 +1,21 @@
+! The `-emit-mlir` option
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang_fc1 -emit-mlir %s -o - | FileCheck %s
+! RUN: %flang_fc1 -emit-fir %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: module attributes {
+! CHECK-LABEL: func @_QQmain() {
+! CHECK-NEXT:  return
+! CHECK-NEXT: }
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
 ! HELP-FC1-NEXT: -falternative-parameter-statement
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -33,6 +33,8 @@
 return std::make_unique();
   case ParseSyntaxOnly:
 return std::make_unique();
+  case EmitMLIR:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/FrontendTool/CMakeLists.txt
===
--- flang/lib/FrontendTool/CMakeLists.txt
+++ flang/lib/FrontendTool/CMakeLists.txt
@@ -2,6 +2,9 @@
   ExecuteCompilerInvocation.cpp
 
   DEPENDS
+  # This makes sure that the MLIR dependencies of flangFrontend (which are
+  # transitively required here) are generated before this target is build.
+  flangFrontend
   clangBasic
 
   LINK_LIBS
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -11,7 +11,12 @@
 #include "flang/Frontend/CompilerInstance.h"
 #include "flang/Frontend/FrontendOptions.h"
 #include "flang/Frontend/PreprocessorOptions.h"
+#include "flang/Lower/Bridge.h"
 #include "flang

[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:421
+  // Set-up the MLIR pass manager
+  fir::setTargetTriple(*mlirModule_, "native");
+  auto &defKinds = ci.invocation().semanticsContext().defaultKinds();

rovka wrote:
> Nit: Should we assert that mlirModule exists?
> Also, why doesn't it already have a triple and a kind mapping?
> Nit: Should we assert that mlirModule exists?

We could do, yes. However, `mlirModule` is created in 
`CodeGenAction::BeginSourceFileAction`. If that method fails, the driver should 
stop immediately. So perhaps that would be a better for place for an assert?

On a related note, `mlirModule` is obtained via [[ 
https://github.com/llvm/llvm-project/blob/79b3fe80707b2eb9a38c1517a829fb58062fb687/flang/include/flang/Lower/Bridge.h#L67
 | LoweringBridge::getModule ]]. But if the corresponding module is `nullptr` 
than that getter should probably assert. See https://reviews.llvm.org/D119133.

>  Also, why doesn't it already have a triple and a kind mapping?
Good catch, this is not needed yet. I didn't notice this when going over `tco`.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119012/new/

https://reviews.llvm.org/D119012

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 406425.
awarzynski marked 2 inline comments as done.
awarzynski added a comment.

Update comments + add an `assert`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119012/new/

https://reviews.llvm.org/D119012

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm.f90
  flang/unittests/Frontend/FrontendActionTest.cpp

Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -161,4 +161,31 @@
   .contains(
   ":1:14: error: IF statement is not allowed in IF statement\n"));
 }
+
+TEST_F(FrontendActionTest, EmitLLVM) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitLLVM;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
+  .contains("define void @_QQmain()"));
+}
 } // namespace
Index: flang/test/Driver/emit-llvm.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm.f90
@@ -0,0 +1,19 @@
+! Test the `-emit-llvm` option
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1 -emit-llvm %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: ; ModuleID = 'FIRModule'
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -35,6 +35,8 @@
 return std::make_unique();
   case EmitMLIR:
 return std::make_unique();
+  case EmitLLVM:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -14,6 +14,7 @@
 #include "flang/Lower/Bridge.h"
 #include "flang/Lower/PFTBuilder.h"
 #include "flang/Lower/Support/Verifier.h"
+#include "flang/Optimizer/Support/FIRContext.h"
 #include "flang/Optimizer/Support/InitFIR.h"
 #include "flang/Optimizer/Support/KindMapping.h"
 #include "flang/Optimizer/Support/Utils.h"
@@ -28,6 +29,7 @@
 
 #include "mlir/IR/Dialect.h"
 #include "mlir/Pass/PassManager.h"
+#include "mlir/Target/LLVMIR/ModuleTranslation.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
@@ -406,6 +408,81 @@
   ci.semantics().DumpSymbolsSources(llvm::outs());
 }
 
+#include "flang/Tools/CLOptions.inc"
+
+// Lower the previously generated MLIR module into an LLVM IR module
+void CodeGenAction::GenerateLLVMIR() {
+  assert(mlirModule && "The MLIR module has not been generated yet.");
+
+  CompilerInstance &ci = this->instance();
+
+  fir::support::loadDialects(*mlirCtx);
+  fir::support::registerLLVMTranslation(*mlirCtx);
+
+  // Set-up the MLIR pass manager
+  fir::setTargetTriple(*mlirModule, "native");
+  auto &defKinds = ci.i

[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 406428.
awarzynski added a comment.

Remove the calls to `setTargetTriple` and `setKindMapping`.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119012/new/

https://reviews.llvm.org/D119012

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm.f90
  flang/unittests/Frontend/FrontendActionTest.cpp

Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -161,4 +161,31 @@
   .contains(
   ":1:14: error: IF statement is not allowed in IF statement\n"));
 }
+
+TEST_F(FrontendActionTest, EmitLLVM) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitLLVM;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
+  .contains("define void @_QQmain()"));
+}
 } // namespace
Index: flang/test/Driver/emit-llvm.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm.f90
@@ -0,0 +1,19 @@
+! Test the `-emit-llvm` option
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1 -emit-llvm %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: ; ModuleID = 'FIRModule'
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -35,6 +35,8 @@
 return std::make_unique();
   case EmitMLIR:
 return std::make_unique();
+  case EmitLLVM:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -14,6 +14,7 @@
 #include "flang/Lower/Bridge.h"
 #include "flang/Lower/PFTBuilder.h"
 #include "flang/Lower/Support/Verifier.h"
+#include "flang/Optimizer/Support/FIRContext.h"
 #include "flang/Optimizer/Support/InitFIR.h"
 #include "flang/Optimizer/Support/KindMapping.h"
 #include "flang/Optimizer/Support/Utils.h"
@@ -28,6 +29,7 @@
 
 #include "mlir/IR/Dialect.h"
 #include "mlir/Pass/PassManager.h"
+#include "mlir/Target/LLVMIR/ModuleTranslation.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
@@ -406,6 +408,76 @@
   ci.semantics().DumpSymbolsSources(llvm::outs());
 }
 
+#include "flang/Tools/CLOptions.inc"
+
+// Lower the previously generated MLIR module into an LLVM IR module
+void CodeGenAction::GenerateLLVMIR() {
+  assert(mlirModule && "The MLIR module has not been generated yet.");
+
+  CompilerInstance &ci = this->instance();
+
+  fir::support::loadDialects(*mlirCtx);
+  fir::support::registerLLVMTranslation(*mlirCtx);
+
+  // Set-up the MLIR pass manager
+  mlir::PassManager pm(mlirCtx.get(), mlir::OpPassManager::Nesting::Implicit);
+
+  pm.add

[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-08 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:419
+
+  // ... otherwise, print to a file.
+  auto os{ci.CreateDefaultOutputFile(

kiranchandramohan wrote:
> awarzynski wrote:
> > kiranchandramohan wrote:
> > > Nit: Should we test the existence of such a file?
> > We do :) Sort of!
> > 
> > To me, "existence" is a low level concept. Files are handled through e.g. 
> > `llvm::raw_fd_ostream` (and occasionally other streams) and IMO all low 
> > level details should be dealt with there (and indeed are). `flang-new` 
> > should only verify that `os` is not a `nullptr`. If the file does not 
> > exist, `os` will be a `nullptr` and that's checked further down. If the 
> > file does exist, then everything is fine and we can move to the next step. 
> OK, that was sounds fine. I was also meaning to ask whether we should have a 
> test that a *.mlir file is generated in a test.
I can add one, yes!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D118985/new/

https://reviews.llvm.org/D118985

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-08 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 406828.
awarzynski added a comment.

- Add a test to verify that an `.mlir` file is created
- Set the target triple to `native` (as opposed to relying on it being set 
elsewhere, e.g. 
https://github.com/llvm/llvm-project/blob/81cde474e2c5a6280cb693b777ddcf473825ae8a/flang/lib/Optimizer/Support/FIRContext.cpp#L53-L62
 )


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D118985/new/

https://reviews.llvm.org/D118985

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-mlir.f90
  flang/test/Driver/syntax-only.f90

Index: flang/test/Driver/syntax-only.f90
===
--- flang/test/Driver/syntax-only.f90
+++ flang/test/Driver/syntax-only.f90
@@ -1,24 +1,28 @@
-! Verify that the compiler driver correctly processes `-fsyntax-only`. By
-! default it will try to run code-generation, but that's not supported yet. We
-! don't need to test the frontend driver here - it runs `-fsyntax-only` by
-! default.
+! Verify that the driver correctly processes `-fsyntax-only`.
+!
+! By default, the compiler driver (`flang`) will create actions/phases to
+! generate machine code (i.e. object files). The `-fsyntax-only` flag is a
+! "phase-control" flag that controls this behavior and makes the driver stop
+! once the semantic checks have been run. The frontend driver (`flang -fc1`)
+! runs `-fsyntax-only` by default (i.e. that's the default action), so the flag
+! can be skipped.
 
 !---
 ! RUN LINES
 !---
-! RUN: not %flang -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=FSYNTAX_ONLY
+! RUN: %flang -fsyntax-only %s 2>&1 | FileCheck %s --allow-empty
+! RUN: %flang_fc1 %s 2>&1 | FileCheck %s --allow-empty
+
 ! RUN: not %flang  %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
+! RUN: not %flang_fc1 -emit-obj %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
 
 !-
 ! EXPECTED OUTPUT
 !-
-! FSYNTAX_ONLY: IF statement is not allowed in IF statement
-! FSYNTAX_ONLY_NEXT: Semantic errors in {{.*}}syntax-only.f90
-
+! CHECK-NOT: error
 ! NO_FSYNTAX_ONLY: error: code-generation is not available yet
 
 !---
 ! INPUT
 !---
-IF (A > 0.0) IF (B < 0.0) A = LOG (A)
-END
+end program
Index: flang/test/Driver/emit-mlir.f90
===
--- /dev/null
+++ flang/test/Driver/emit-mlir.f90
@@ -0,0 +1,27 @@
+! Test the `-emit-mlir` option
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang_fc1 -emit-mlir %s -o - | FileCheck %s
+! RUN: %flang_fc1 -emit-fir %s -o - | FileCheck %s
+
+! Verify that an `.mlir` file is created when `-emit-mlir` is used. Do it in a temporary directory, which will be cleaned up by the
+! LIT runner.
+! RUN: rm -rf %t-dir && mkdir -p %t-dir && cd %t-dir
+! RUN: cp %s .
+! RUN: %flang_fc1 -emit-mlir emit-mlir.f90 && ls emit-mlir.mlir
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: module attributes {
+! CHECK-LABEL: func @_QQmain() {
+! CHECK-NEXT:  return
+! CHECK-NEXT: }
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
 ! HELP-FC1-NEXT: -falternative-parameter-statement
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -33,6 +33,8 @@
 return std::make_unique();
   case ParseSyntaxOnly:
 return std::make_unique();
+  case EmitMLIR:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/FrontendTool/CMakeLists.txt
===
--- flang/lib/FrontendTool/CMakeLists.txt
+++ flang/lib/FrontendTool/CMakeLists.txt
@@ -2,6 +2,9 @@
   ExecuteCompilerInvocation.cpp
 
   DEPENDS
+  # This makes sure that the MLIR dependencies of flangFront

[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-08 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

I believe that Windows failures are due to the missing support here: 
https://github.com/llvm/llvm-project/blob/81cde474e2c5a6280cb693b777ddcf473825ae8a/flang/lib/Optimizer/CodeGen/Target.cpp#L290.
 I can disable the LIT test on Windows, but I'm not sure how to do it for unit 
tests.




Comment at: flang/lib/Frontend/FrontendActions.cpp:421
+  // Set-up the MLIR pass manager
+  fir::setTargetTriple(*mlirModule_, "native");
+  auto &defKinds = ci.invocation().semanticsContext().defaultKinds();

kiranchandramohan wrote:
> awarzynski wrote:
> > rovka wrote:
> > > Nit: Should we assert that mlirModule exists?
> > > Also, why doesn't it already have a triple and a kind mapping?
> > > Nit: Should we assert that mlirModule exists?
> > 
> > We could do, yes. However, `mlirModule` is created in 
> > `CodeGenAction::BeginSourceFileAction`. If that method fails, the driver 
> > should stop immediately. So perhaps that would be a better for place for an 
> > assert?
> > 
> > On a related note, `mlirModule` is obtained via [[ 
> > https://github.com/llvm/llvm-project/blob/79b3fe80707b2eb9a38c1517a829fb58062fb687/flang/include/flang/Lower/Bridge.h#L67
> >  | LoweringBridge::getModule ]]. But if the corresponding module is 
> > `nullptr` than that getter should probably assert. See 
> > https://reviews.llvm.org/D119133.
> > 
> > >  Also, why doesn't it already have a triple and a kind mapping?
> > Good catch, this is not needed yet. I didn't notice this when going over 
> > `tco`.
>  D118985 creates a bridge with an empty triple. The patch here was switching 
> it to "native". Please cross-check what the expected behaviour.
> 
> ```
>   lower::LoweringBridge lb = Fortran::lower::LoweringBridge::create(*mlirCtx,
>   defKinds, ci.invocation().semanticsContext().intrinsics(),
>   ci.parsing().allCooked(), "", kindMap);
> ```
> Please cross-check what the expected behaviour.
That's a good point, Kiran! Thanks :) 

The constructor for `LoweringBridge` will call [[ 
https://github.com/llvm/llvm-project/blob/81cde474e2c5a6280cb693b777ddcf473825ae8a/flang/lib/Optimizer/Support/FIRContext.cpp#L21-L24
 | fir::setTargetTriple ]]. This, in turn, will call [[ 
https://github.com/llvm/llvm-project/blob/81cde474e2c5a6280cb693b777ddcf473825ae8a/flang/lib/Optimizer/Support/FIRContext.cpp#L53-L62
 | fir::determineTargetTriple ]], which (for an empty triple) selects the 
target as follows:
```lang=cpp
  if (triple.empty() || triple == "default")
return llvm::sys::getDefaultTargetTriple()
```
AFAIK, `native` and `default` are compatible (I couldn't find any indication 
otherwise). So, empty triple above and "native" will lead to the same thing. So 
we are still just using `native` here.

This made me realise though that we should be explicit in D118985  and set the 
triple there. I'll update it shortly.



Comment at: flang/lib/Frontend/FrontendActions.cpp:440
+  // Translate to LLVM IR
+  auto optName = mlirModule->getName();
+  llvmCtx = std::make_unique();

kiranchandramohan wrote:
> Nit: Remove auto.
Sure! I will also rename this as `moduleName`.



Comment at: flang/lib/Frontend/FrontendActions.cpp:471
+
+  if (!ci.IsOutputStreamNull()) {
+llvmModule->print(

rovka wrote:
> Nit: Can this be folded into the above if? (I.e. just write to os if you 
> managed to create it, and add an else branch for the other case)
Good suggestion, thanks!

I recall having a good reason to write it like this, but don't remember what it 
was. Let me simplify!



Comment at: flang/unittests/Frontend/FrontendActionTest.cpp:176
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(

kiranchandramohan wrote:
> Nit: Is the size important?
No, thanks for noting this!

In fact, the generated output is larger than 256 characters.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119012/new/

https://reviews.llvm.org/D119012

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-08 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 406832.
awarzynski added a comment.

Disable the LIT test on Windows, simplify how output is dumped in 
`EmitLLVMAction::ExecuteAction`, remove `auto`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119012/new/

https://reviews.llvm.org/D119012

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm.f90
  flang/unittests/Frontend/FrontendActionTest.cpp

Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -161,4 +161,31 @@
   .contains(
   ":1:14: error: IF statement is not allowed in IF statement\n"));
 }
+
+TEST_F(FrontendActionTest, EmitLLVM) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitLLVM;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
+  .contains("define void @_QQmain()"));
+}
 } // namespace
Index: flang/test/Driver/emit-llvm.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm.f90
@@ -0,0 +1,22 @@
+! Test the `-emit-llvm` option
+
+! UNSUPPORTED: system-windows
+! Windows is currently not supported in flang/lib/Optimizer/CodeGen/Target.cpp
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1 -emit-llvm %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: ; ModuleID = 'FIRModule'
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -35,6 +35,8 @@
 return std::make_unique();
   case EmitMLIR:
 return std::make_unique();
+  case EmitLLVM:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -14,6 +14,7 @@
 #include "flang/Lower/Bridge.h"
 #include "flang/Lower/PFTBuilder.h"
 #include "flang/Lower/Support/Verifier.h"
+#include "flang/Optimizer/Support/FIRContext.h"
 #include "flang/Optimizer/Support/InitFIR.h"
 #include "flang/Optimizer/Support/KindMapping.h"
 #include "flang/Optimizer/Support/Utils.h"
@@ -28,6 +29,7 @@
 
 #include "mlir/IR/Dialect.h"
 #include "mlir/Pass/PassManager.h"
+#include "mlir/Target/LLVMIR/ModuleTranslation.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
@@ -407,6 +409,72 @@
   ci.semantics().DumpSymbolsSources(llvm::outs());
 }
 
+#include "flang/Tools/CLOptions.inc"
+
+// Lower the previously generated MLIR module into an LLVM IR module
+void CodeGenAction::GenerateLLVMIR() {
+  assert(mlirModule && "The MLIR module has not been generated yet.");
+
+  CompilerInstance &ci = this->instance();
+
+  fir::support::loadDialects(*mlirCtx);
+  fir::suppo

[PATCH] D118985: [flang][driver] Add support for `-emit-mlir`

2022-02-09 Thread Andrzej Warzynski via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG69c3309d4545: [flang][driver] Add support for `-emit-mlir` 
(authored by awarzynski).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D118985/new/

https://reviews.llvm.org/D118985

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/CMakeLists.txt
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-mlir.f90
  flang/test/Driver/syntax-only.f90

Index: flang/test/Driver/syntax-only.f90
===
--- flang/test/Driver/syntax-only.f90
+++ flang/test/Driver/syntax-only.f90
@@ -1,24 +1,28 @@
-! Verify that the compiler driver correctly processes `-fsyntax-only`. By
-! default it will try to run code-generation, but that's not supported yet. We
-! don't need to test the frontend driver here - it runs `-fsyntax-only` by
-! default.
+! Verify that the driver correctly processes `-fsyntax-only`.
+!
+! By default, the compiler driver (`flang`) will create actions/phases to
+! generate machine code (i.e. object files). The `-fsyntax-only` flag is a
+! "phase-control" flag that controls this behavior and makes the driver stop
+! once the semantic checks have been run. The frontend driver (`flang -fc1`)
+! runs `-fsyntax-only` by default (i.e. that's the default action), so the flag
+! can be skipped.
 
 !---
 ! RUN LINES
 !---
-! RUN: not %flang -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=FSYNTAX_ONLY
+! RUN: %flang -fsyntax-only %s 2>&1 | FileCheck %s --allow-empty
+! RUN: %flang_fc1 %s 2>&1 | FileCheck %s --allow-empty
+
 ! RUN: not %flang  %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
+! RUN: not %flang_fc1 -emit-obj %s 2>&1 | FileCheck %s --check-prefix=NO_FSYNTAX_ONLY
 
 !-
 ! EXPECTED OUTPUT
 !-
-! FSYNTAX_ONLY: IF statement is not allowed in IF statement
-! FSYNTAX_ONLY_NEXT: Semantic errors in {{.*}}syntax-only.f90
-
+! CHECK-NOT: error
 ! NO_FSYNTAX_ONLY: error: code-generation is not available yet
 
 !---
 ! INPUT
 !---
-IF (A > 0.0) IF (B < 0.0) A = LOG (A)
-END
+end program
Index: flang/test/Driver/emit-mlir.f90
===
--- /dev/null
+++ flang/test/Driver/emit-mlir.f90
@@ -0,0 +1,27 @@
+! Test the `-emit-mlir` option
+
+!-
+! RUN COMMANDS
+!-
+! RUN: %flang_fc1 -emit-mlir %s -o - | FileCheck %s
+! RUN: %flang_fc1 -emit-fir %s -o - | FileCheck %s
+
+! Verify that an `.mlir` file is created when `-emit-mlir` is used. Do it in a temporary directory, which will be cleaned up by the
+! LIT runner.
+! RUN: rm -rf %t-dir && mkdir -p %t-dir && cd %t-dir
+! RUN: cp %s .
+! RUN: %flang_fc1 -emit-mlir emit-mlir.f90 && ls emit-mlir.mlir
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: module attributes {
+! CHECK-LABEL: func @_QQmain() {
+! CHECK-NEXT:  return
+! CHECK-NEXT: }
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
 ! HELP-FC1-NEXT: -falternative-parameter-statement
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -33,6 +33,8 @@
 return std::make_unique();
   case ParseSyntaxOnly:
 return std::make_unique();
+  case EmitMLIR:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/FrontendTool/CMakeLists.txt
===
--- flang/lib/FrontendTool/CMakeLists.txt
+++ flang/lib/FrontendTool/CMakeLists.txt
@@ -2,6 +2,9 @@
   ExecuteCompilerInvocation.cpp
 
   DEPENDS
+  # This makes sure that the MLIR dependencies of flangFrontend (which are
+  # transitively required here) are generated before this target is build.
+  flangFrontend
   clangBasic
 
   LINK_LIBS
Index: flang/lib/Frontend/FrontendActions.cpp
==

[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-09 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 407070.
awarzynski added a comment.

Rebase on top of main


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119012/new/

https://reviews.llvm.org/D119012

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm.f90
  flang/unittests/Frontend/FrontendActionTest.cpp

Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -161,4 +161,31 @@
   .contains(
   ":1:14: error: IF statement is not allowed in IF statement\n"));
 }
+
+TEST_F(FrontendActionTest, EmitLLVM) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitLLVM;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
+  .contains("define void @_QQmain()"));
+}
 } // namespace
Index: flang/test/Driver/emit-llvm.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm.f90
@@ -0,0 +1,22 @@
+! Test the `-emit-llvm` option
+
+! UNSUPPORTED: system-windows
+! Windows is currently not supported in flang/lib/Optimizer/CodeGen/Target.cpp
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1 -emit-llvm %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: ; ModuleID = 'FIRModule'
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -35,6 +35,8 @@
 return std::make_unique();
   case EmitMLIR:
 return std::make_unique();
+  case EmitLLVM:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -14,6 +14,7 @@
 #include "flang/Lower/Bridge.h"
 #include "flang/Lower/PFTBuilder.h"
 #include "flang/Lower/Support/Verifier.h"
+#include "flang/Optimizer/Support/FIRContext.h"
 #include "flang/Optimizer/Support/InitFIR.h"
 #include "flang/Optimizer/Support/KindMapping.h"
 #include "flang/Optimizer/Support/Utils.h"
@@ -28,6 +29,7 @@
 
 #include "mlir/IR/Dialect.h"
 #include "mlir/Pass/PassManager.h"
+#include "mlir/Target/LLVMIR/ModuleTranslation.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
@@ -407,6 +409,72 @@
   ci.semantics().DumpSymbolsSources(llvm::outs());
 }
 
+#include "flang/Tools/CLOptions.inc"
+
+// Lower the previously generated MLIR module into an LLVM IR module
+void CodeGenAction::GenerateLLVMIR() {
+  assert(mlirModule && "The MLIR module has not been generated yet.");
+
+  CompilerInstance &ci = this->instance();
+
+  fir::support::loadDialects(*mlirCtx);
+  fir::support::registerLLVMTranslation(*mlirCtx);
+
+  // Set-up the MLIR pass manager
+  mlir::PassMan

[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-09 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 407130.
awarzynski added a comment.
Herald added a subscriber: mehdi_amini.

Updated `fir::CodeGenSpecifics::get` to see whether the unit tests pass on 
Windows. If they do, I'll create a seperate patch with this change.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119012/new/

https://reviews.llvm.org/D119012

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/lib/Optimizer/CodeGen/Target.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm.f90
  flang/unittests/Frontend/FrontendActionTest.cpp

Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -161,4 +161,31 @@
   .contains(
   ":1:14: error: IF statement is not allowed in IF statement\n"));
 }
+
+TEST_F(FrontendActionTest, EmitLLVM) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitLLVM;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
+  .contains("define void @_QQmain()"));
+}
 } // namespace
Index: flang/test/Driver/emit-llvm.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm.f90
@@ -0,0 +1,22 @@
+! Test the `-emit-llvm` option
+
+! UNSUPPORTED: system-windows
+! Windows is currently not supported in flang/lib/Optimizer/CodeGen/Target.cpp
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1 -emit-llvm %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: ; ModuleID = 'FIRModule'
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
Index: flang/lib/Optimizer/CodeGen/Target.cpp
===
--- flang/lib/Optimizer/CodeGen/Target.cpp
+++ flang/lib/Optimizer/CodeGen/Target.cpp
@@ -238,9 +238,7 @@
 } // namespace
 
 // Instantiate the overloaded target instance based on the triple value.
-// Currently, the implementation only instantiates `i386-unknown-linux-gnu`,
-// `x86_64-unknown-linux-gnu`, aarch64 and ppc64le like triples. Other targets
-// should be added to this file as needed.
+// TODO: Add other target to this file as needed.
 std::unique_ptr
 fir::CodeGenSpecifics::get(mlir::MLIRContext *ctx, llvm::Triple &&trp,
KindMapping &&kindMap) {
@@ -253,6 +251,7 @@
   break;
 case llvm::Triple::OSType::Linux:
 case llvm::Triple::OSType::Darwin:
+case llvm::Triple::OSType::Win32:
   return std::make_unique(ctx, std::move(trp),
   std::move(kindMap));
 }
@@ -263,6 +262,7 @@
   break;
 case llvm::Triple::OSType::Linux:
 case llvm::Triple::OSType::Darwin:
+case llvm::Triple::OSType::Win32:
   return std::make_unique(ctx, std::move(trp),
 std::move(kindMap));
 }
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation

[PATCH] D119012: [flang][driver] Add support for the `-emit-llvm` option

2022-02-09 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 407139.
awarzynski added a comment.

Remove the change from `fir::CodeGenSpecifics::get` (this was uploaded as a
seperate patch: https://reviews.llvm.org/D119332)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D119012/new/

https://reviews.llvm.org/D119012

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-llvm.f90
  flang/unittests/Frontend/FrontendActionTest.cpp

Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -161,4 +161,31 @@
   .contains(
   ":1:14: error: IF statement is not allowed in IF statement\n"));
 }
+
+TEST_F(FrontendActionTest, EmitLLVM) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitLLVM;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
+  .contains("define void @_QQmain()"));
+}
 } // namespace
Index: flang/test/Driver/emit-llvm.f90
===
--- /dev/null
+++ flang/test/Driver/emit-llvm.f90
@@ -0,0 +1,22 @@
+! Test the `-emit-llvm` option
+
+! UNSUPPORTED: system-windows
+! Windows is currently not supported in flang/lib/Optimizer/CodeGen/Target.cpp
+
+!
+! RUN COMMAND
+!
+! RUN: %flang_fc1 -emit-llvm %s -o - | FileCheck %s
+
+!
+! EXPECTED OUTPUT
+!
+! CHECK: ; ModuleID = 'FIRModule'
+! CHECK: define void @_QQmain()
+! CHECK-NEXT:  ret void
+! CHECK-NEXT: }
+
+!--
+! INPUT
+!--
+end program
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -65,6 +65,7 @@
 ! HELP-FC1-NEXT:OPTIONS:
 ! HELP-FC1-NEXT: -cpp   Enable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
+! HELP-FC1-NEXT: -emit-llvm Use the LLVM representation for assembler and object files
 ! HELP-FC1-NEXT: -emit-mlir Build the parse tree, then lower it to MLIR
 ! HELP-FC1-NEXT: -emit-obj Emit native object files
 ! HELP-FC1-NEXT: -E Only run the preprocessor
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -35,6 +35,8 @@
 return std::make_unique();
   case EmitMLIR:
 return std::make_unique();
+  case EmitLLVM:
+return std::make_unique();
   case EmitObj:
 return std::make_unique();
   case DebugUnparse:
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -14,6 +14,7 @@
 #include "flang/Lower/Bridge.h"
 #include "flang/Lower/PFTBuilder.h"
 #include "flang/Lower/Support/Verifier.h"
+#include "flang/Optimizer/Support/FIRContext.h"
 #include "flang/Optimizer/Support/InitFIR.h"
 #include "flang/Optimizer/Support/KindMapping.h"
 #include "flang/Optimizer/Support/Utils.h"
@@ -28,6 +29,7 @@
 
 #include "mlir/IR/Dialect.h"
 #include "mlir/Pass/PassManager.h"
+#include "mlir/Target/LLVMIR/ModuleTranslation.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
@@ -407,6 +409,72 @@
   ci.semantics().DumpSymbolsSources(llvm::outs());
 }
 
+#include "flang/Tools/CLOptions.inc"
+
+// Lower the previously generated MLIR module into an LLVM IR module
+void CodeGenAction::GenerateLLVMIR() {
+  assert(mlirModule && "The MLIR module has not been generated yet.");
+
+  CompilerInstance &ci = this->instance();
+
+  fir::support::loadDialects(*mlirCtx);
+

  1   2   3   4   5   6   7   >