r372814 - [Driver] Always use -z separate-loadable-segments with lld on Fuchsia

2019-09-25 Thread Fangrui Song via cfe-commits
Author: maskray
Date: Wed Sep 25 00:06:50 2019
New Revision: 372814

URL: http://llvm.org/viewvc/llvm-project?rev=372814&view=rev
Log:
[Driver] Always use -z separate-loadable-segments with lld on Fuchsia

The option was added to lld in D67481/372807.

Reviewed By: phosek

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

Modified:
cfe/trunk/lib/Driver/ToolChains/Fuchsia.cpp
cfe/trunk/test/Driver/fuchsia.c

Modified: cfe/trunk/lib/Driver/ToolChains/Fuchsia.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Fuchsia.cpp?rev=372814&r1=372813&r2=372814&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Fuchsia.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Fuchsia.cpp Wed Sep 25 00:06:50 2019
@@ -52,7 +52,7 @@ void fuchsia::Linker::ConstructJob(Compi
 CmdArgs.push_back("-z");
 CmdArgs.push_back("rodynamic");
 CmdArgs.push_back("-z");
-CmdArgs.push_back("separate-code");
+CmdArgs.push_back("separate-loadable-segments");
   }
 
   if (!D.SysRoot.empty())

Modified: cfe/trunk/test/Driver/fuchsia.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/fuchsia.c?rev=372814&r1=372813&r2=372814&view=diff
==
--- cfe/trunk/test/Driver/fuchsia.c (original)
+++ cfe/trunk/test/Driver/fuchsia.c Wed Sep 25 00:06:50 2019
@@ -16,7 +16,7 @@
 // CHECK: "-fsanitize=safe-stack"
 // CHECK: "-stack-protector" "2"
 // CHECK: "-fno-common"
-// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic" "-z" "separate-code"
+// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic" "-z" 
"separate-loadable-segments"
 // CHECK: "--sysroot=[[SYSROOT]]"
 // CHECK: "-pie"
 // CHECK: "--build-id"


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


[PATCH] D68009: [Driver] Always use -z separate-loadable-segments with lld on Fuchsia

2019-09-25 Thread Fangrui Song via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL372814: [Driver] Always use -z separate-loadable-segments 
with lld on Fuchsia (authored by MaskRay, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D68009

Files:
  cfe/trunk/lib/Driver/ToolChains/Fuchsia.cpp
  cfe/trunk/test/Driver/fuchsia.c


Index: cfe/trunk/test/Driver/fuchsia.c
===
--- cfe/trunk/test/Driver/fuchsia.c
+++ cfe/trunk/test/Driver/fuchsia.c
@@ -16,7 +16,7 @@
 // CHECK: "-fsanitize=safe-stack"
 // CHECK: "-stack-protector" "2"
 // CHECK: "-fno-common"
-// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic" "-z" "separate-code"
+// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic" "-z" 
"separate-loadable-segments"
 // CHECK: "--sysroot=[[SYSROOT]]"
 // CHECK: "-pie"
 // CHECK: "--build-id"
Index: cfe/trunk/lib/Driver/ToolChains/Fuchsia.cpp
===
--- cfe/trunk/lib/Driver/ToolChains/Fuchsia.cpp
+++ cfe/trunk/lib/Driver/ToolChains/Fuchsia.cpp
@@ -52,7 +52,7 @@
 CmdArgs.push_back("-z");
 CmdArgs.push_back("rodynamic");
 CmdArgs.push_back("-z");
-CmdArgs.push_back("separate-code");
+CmdArgs.push_back("separate-loadable-segments");
   }
 
   if (!D.SysRoot.empty())


Index: cfe/trunk/test/Driver/fuchsia.c
===
--- cfe/trunk/test/Driver/fuchsia.c
+++ cfe/trunk/test/Driver/fuchsia.c
@@ -16,7 +16,7 @@
 // CHECK: "-fsanitize=safe-stack"
 // CHECK: "-stack-protector" "2"
 // CHECK: "-fno-common"
-// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic" "-z" "separate-code"
+// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic" "-z" "separate-loadable-segments"
 // CHECK: "--sysroot=[[SYSROOT]]"
 // CHECK: "-pie"
 // CHECK: "--build-id"
Index: cfe/trunk/lib/Driver/ToolChains/Fuchsia.cpp
===
--- cfe/trunk/lib/Driver/ToolChains/Fuchsia.cpp
+++ cfe/trunk/lib/Driver/ToolChains/Fuchsia.cpp
@@ -52,7 +52,7 @@
 CmdArgs.push_back("-z");
 CmdArgs.push_back("rodynamic");
 CmdArgs.push_back("-z");
-CmdArgs.push_back("separate-code");
+CmdArgs.push_back("separate-loadable-segments");
   }
 
   if (!D.SysRoot.empty())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44609: [Clang-Format] New option BeforeLambdaBody to manage lambda line break inside function parameter call (in Allman style)

2019-09-25 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Thanks for the patch, so sorry its taking a long time, its patches like this 
why I'm about to make a phabricator project for #clang-format alone so that we 
can ensure all clang-format patches can be see in isolation.

I think we need to get this patches rebased to the current trunk and then take 
a final look. if you are still interested, I'll be happy to review it.




Comment at: lib/Format/ContinuationIndenter.cpp:1179
+   Current.is(TT_LambdaLSquare;
   }
 

oh boy... I have to say.. that I don't like these kinds of massive if 
statements without some sort of comment.. as to what it's doing, it's so hard, 
later on, to read through the various clauses and understand which bit of 
functionality this section covers



Comment at: lib/Format/Format.cpp:651
 Expanded.BraceWrapping = {true, true, true, true, true, true, true, true,
   true, true, true, true, true, true, true, true};
 break;

if we are adding new options to BraceWrapping structure wouldn't these 
structures need to change too or wouldn't it potentially become unintialized



Comment at: lib/Format/TokenAnnotator.cpp:2920
+
+// Returns 'true' if 'Tok' is an function argument.
+static bool IsFunctionArgument(const FormatToken &Tok) {

I really like this style of pulling out the clauses into separate functions 
because it helps to describe what its doing without the need for a comment at 
all.


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

https://reviews.llvm.org/D44609



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


[PATCH] D67826: [clangd] A helper to find explicit references and their names

2019-09-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!




Comment at: clang-tools-extra/clangd/FindTarget.h:103
+llvm::function_ref Out);
+void findExplicitReferences(Decl *S,
+llvm::function_ref Out);

nit: s/Decl *S/Decl *D/


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67826



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


[PATCH] D66937: [clangd] Fix the stale documentation about background indexing.

2019-09-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks, lgtm!




Comment at: clang-tools-extra/docs/clangd/Installation.rst:364
+  amount of cores by passing the `-j=` flag;
+- the index is saved to the ``.clangd/index`` in the project root; index 
shareds
+  for common headers e.g. STL will be stored in `$HOME/.clangd/index`;

s/shareds/shards


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66937



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


[PATCH] D67960: [clangd] Move the existing heder-source-switch implemenation out of clangdServer.

2019-09-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks, lgtm!




Comment at: clang-tools-extra/clangd/HeaderSourceSwitch.cpp:21
+llvm::IntrusiveRefCntPtr VFS) {
+  // FIXME: move the file heuristic to HeaderSourceSwitch.h.
+  llvm::StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",

this patch is fixing it ?



Comment at: clang-tools-extra/clangd/HeaderSourceSwitch.h:15
 
+/// Given a header file, returns a best matching source file, and vice visa.
+/// It only uses the filename heuristics to do the inference.

nit: s/a best/the best



Comment at: clang-tools-extra/clangd/HeaderSourceSwitch.h:21
+
 /// Given a header file, returns a best matching source file, and vice visa.
 /// The heuristics incorporate with the AST and the index (if provided).

nit: s/a best/the best


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67960



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


[clang-tools-extra] r372825 - [clangd] Fix the stale documentation about background indexing.

2019-09-25 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Sep 25 01:26:32 2019
New Revision: 372825

URL: http://llvm.org/viewvc/llvm-project?rev=372825&view=rev
Log:
[clangd] Fix the stale documentation about background indexing.

Reviewers: kadircet

Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/docs/clangd/Installation.rst

Modified: clang-tools-extra/trunk/docs/clangd/Installation.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clangd/Installation.rst?rev=372825&r1=372824&r2=372825&view=diff
==
--- clang-tools-extra/trunk/docs/clangd/Installation.rst (original)
+++ clang-tools-extra/trunk/docs/clangd/Installation.rst Wed Sep 25 01:26:32 
2019
@@ -352,20 +352,28 @@ Clangd will assume the compile command i
 Creating this file by hand is a reasonable place to start if your project is
 quite simple.
 
-Project-wide Index
-==
+Background Indexing
+===
 
-By default clangd only has a view on symbols coming from files you are
-currently editing. You can extend this view to whole project by providing a
-project-wide index to clangd.  There are two ways to do this.
-
-- Pass an experimental `-background-index` command line argument.  With
-  this feature enabled, clangd incrementally builds an index of projects
-  that you work on and uses the just-built index automatically.
-
-- Generate an index file using `clangd-indexer
-  
`__
-  Then you can pass generated index file to clangd using
-  `-index-file=/path/to/index_file`.  *Note that clangd-indexer isn't
-  included alongside clangd in the Debian clang-tools package. You will
-  likely have to build it from source to use this option.*
+clangd builds an incremental index of your project (all files listed in the
+compilation database). The index improves code navigation features 
(go-to-definition,
+find-references) and code completion.
+
+- clangd only uses idle cores to build the index, you can limit the total
+  amount of cores by passing the `-j=` flag;
+- the index is saved to the ``.clangd/index`` in the project root; index shards
+  for common headers e.g. STL will be stored in `$HOME/.clangd/index`;
+- background indexing can be disabled by the ``--background-index=false`` flag;
+  Note that, disabling background-index will limit clangd's knowledge about 
your
+  codebase to files you are currently editing.
+
+Build Index Manually
+
+
+**DISCLAIMER: This is mainly for clangd developers.**
+
+There is a `clangd-indexer 
`__
+which generates an index file for your project. To use the index, pass the flag
+`-index=file=/path/to/index_file` to clangd. *Note that clangd-indexer isn't
+included alongside clangd in the Debian clang-tools package. You will likely
+have to build it from source to use this option.*


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


[PATCH] D66937: [clangd] Fix the stale documentation about background indexing.

2019-09-25 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 221687.
hokein marked an inline comment as done.
hokein added a comment.

Fix a typo.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66937

Files:
  clang-tools-extra/docs/clangd/Installation.rst


Index: clang-tools-extra/docs/clangd/Installation.rst
===
--- clang-tools-extra/docs/clangd/Installation.rst
+++ clang-tools-extra/docs/clangd/Installation.rst
@@ -352,20 +352,28 @@
 Creating this file by hand is a reasonable place to start if your project is
 quite simple.
 
-Project-wide Index
-==
-
-By default clangd only has a view on symbols coming from files you are
-currently editing. You can extend this view to whole project by providing a
-project-wide index to clangd.  There are two ways to do this.
-
-- Pass an experimental `-background-index` command line argument.  With
-  this feature enabled, clangd incrementally builds an index of projects
-  that you work on and uses the just-built index automatically.
-
-- Generate an index file using `clangd-indexer
-  
`__
-  Then you can pass generated index file to clangd using
-  `-index-file=/path/to/index_file`.  *Note that clangd-indexer isn't
-  included alongside clangd in the Debian clang-tools package. You will
-  likely have to build it from source to use this option.*
+Background Indexing
+===
+
+clangd builds an incremental index of your project (all files listed in the
+compilation database). The index improves code navigation features 
(go-to-definition,
+find-references) and code completion.
+
+- clangd only uses idle cores to build the index, you can limit the total
+  amount of cores by passing the `-j=` flag;
+- the index is saved to the ``.clangd/index`` in the project root; index shards
+  for common headers e.g. STL will be stored in `$HOME/.clangd/index`;
+- background indexing can be disabled by the ``--background-index=false`` flag;
+  Note that, disabling background-index will limit clangd's knowledge about 
your
+  codebase to files you are currently editing.
+
+Build Index Manually
+
+
+**DISCLAIMER: This is mainly for clangd developers.**
+
+There is a `clangd-indexer 
`__
+which generates an index file for your project. To use the index, pass the flag
+`-index=file=/path/to/index_file` to clangd. *Note that clangd-indexer isn't
+included alongside clangd in the Debian clang-tools package. You will likely
+have to build it from source to use this option.*


Index: clang-tools-extra/docs/clangd/Installation.rst
===
--- clang-tools-extra/docs/clangd/Installation.rst
+++ clang-tools-extra/docs/clangd/Installation.rst
@@ -352,20 +352,28 @@
 Creating this file by hand is a reasonable place to start if your project is
 quite simple.
 
-Project-wide Index
-==
-
-By default clangd only has a view on symbols coming from files you are
-currently editing. You can extend this view to whole project by providing a
-project-wide index to clangd.  There are two ways to do this.
-
-- Pass an experimental `-background-index` command line argument.  With
-  this feature enabled, clangd incrementally builds an index of projects
-  that you work on and uses the just-built index automatically.
-
-- Generate an index file using `clangd-indexer
-  `__
-  Then you can pass generated index file to clangd using
-  `-index-file=/path/to/index_file`.  *Note that clangd-indexer isn't
-  included alongside clangd in the Debian clang-tools package. You will
-  likely have to build it from source to use this option.*
+Background Indexing
+===
+
+clangd builds an incremental index of your project (all files listed in the
+compilation database). The index improves code navigation features (go-to-definition,
+find-references) and code completion.
+
+- clangd only uses idle cores to build the index, you can limit the total
+  amount of cores by passing the `-j=` flag;
+- the index is saved to the ``.clangd/index`` in the project root; index shards
+  for common headers e.g. STL will be stored in `$HOME/.clangd/index`;
+- background indexing can be disabled by the ``--background-index=false`` flag;
+  Note that, disabling background-index will limit clangd's knowledge about your
+  codebase to files you are currently editing.
+
+Build Index Manually
+
+
+**DISCLAIMER: This is mainly for clangd developers.**
+
+There is a `clangd-indexer 

[PATCH] D66937: [clangd] Fix the stale documentation about background indexing.

2019-09-25 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL372825: [clangd] Fix the stale documentation about 
background indexing. (authored by hokein, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D66937?vs=221687&id=221688#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D66937

Files:
  clang-tools-extra/trunk/docs/clangd/Installation.rst


Index: clang-tools-extra/trunk/docs/clangd/Installation.rst
===
--- clang-tools-extra/trunk/docs/clangd/Installation.rst
+++ clang-tools-extra/trunk/docs/clangd/Installation.rst
@@ -352,20 +352,28 @@
 Creating this file by hand is a reasonable place to start if your project is
 quite simple.
 
-Project-wide Index
-==
+Background Indexing
+===
 
-By default clangd only has a view on symbols coming from files you are
-currently editing. You can extend this view to whole project by providing a
-project-wide index to clangd.  There are two ways to do this.
-
-- Pass an experimental `-background-index` command line argument.  With
-  this feature enabled, clangd incrementally builds an index of projects
-  that you work on and uses the just-built index automatically.
-
-- Generate an index file using `clangd-indexer
-  
`__
-  Then you can pass generated index file to clangd using
-  `-index-file=/path/to/index_file`.  *Note that clangd-indexer isn't
-  included alongside clangd in the Debian clang-tools package. You will
-  likely have to build it from source to use this option.*
+clangd builds an incremental index of your project (all files listed in the
+compilation database). The index improves code navigation features 
(go-to-definition,
+find-references) and code completion.
+
+- clangd only uses idle cores to build the index, you can limit the total
+  amount of cores by passing the `-j=` flag;
+- the index is saved to the ``.clangd/index`` in the project root; index shards
+  for common headers e.g. STL will be stored in `$HOME/.clangd/index`;
+- background indexing can be disabled by the ``--background-index=false`` flag;
+  Note that, disabling background-index will limit clangd's knowledge about 
your
+  codebase to files you are currently editing.
+
+Build Index Manually
+
+
+**DISCLAIMER: This is mainly for clangd developers.**
+
+There is a `clangd-indexer 
`__
+which generates an index file for your project. To use the index, pass the flag
+`-index=file=/path/to/index_file` to clangd. *Note that clangd-indexer isn't
+included alongside clangd in the Debian clang-tools package. You will likely
+have to build it from source to use this option.*


Index: clang-tools-extra/trunk/docs/clangd/Installation.rst
===
--- clang-tools-extra/trunk/docs/clangd/Installation.rst
+++ clang-tools-extra/trunk/docs/clangd/Installation.rst
@@ -352,20 +352,28 @@
 Creating this file by hand is a reasonable place to start if your project is
 quite simple.
 
-Project-wide Index
-==
+Background Indexing
+===
 
-By default clangd only has a view on symbols coming from files you are
-currently editing. You can extend this view to whole project by providing a
-project-wide index to clangd.  There are two ways to do this.
-
-- Pass an experimental `-background-index` command line argument.  With
-  this feature enabled, clangd incrementally builds an index of projects
-  that you work on and uses the just-built index automatically.
-
-- Generate an index file using `clangd-indexer
-  `__
-  Then you can pass generated index file to clangd using
-  `-index-file=/path/to/index_file`.  *Note that clangd-indexer isn't
-  included alongside clangd in the Debian clang-tools package. You will
-  likely have to build it from source to use this option.*
+clangd builds an incremental index of your project (all files listed in the
+compilation database). The index improves code navigation features (go-to-definition,
+find-references) and code completion.
+
+- clangd only uses idle cores to build the index, you can limit the total
+  amount of cores by passing the `-j=` flag;
+- the index is saved to the ``.clangd/index`` in the project root; index shards
+  for common headers e.g. STL will be stored in `$HOME/.clangd/index`;
+- background indexing can be disabled by the ``--background-index=false`` flag;
+  Note that, disabling background-index will limit clangd's knowledge about your
+  codebase to fil

[PATCH] D60199: [clang-format] Do not emit replacements while regrouping if Cpp includes are OK

2019-09-25 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Possible fix for PR43372 (https://bugs.llvm.org/show_bug.cgi?id=43372)


Repository:
  rC Clang

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

https://reviews.llvm.org/D60199



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


[PATCH] D67901: [clangd] Improve semantic highlighting in dependent contexts (fixes #154)

2019-09-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:181
+  addToken(E->getMemberLoc(), E->getQualifier()
+  ? HighlightingKind::StaticField
+  : HighlightingKind::Field);

nridge wrote:
> hokein wrote:
> > This could be member functions, a case is like
> > 
> > ```
> > template
> > class Foo {
> > public:
> >   void foo() {
> > this->foo();
> >   }
> > };
> > ```
> Thanks for the example.
> 
> Do you have a suggestion for how to discriminate this case? To me, it would 
> seem logical to do it based on syntax (highlight as a member function if the 
> expression forms the function name of a function call expression). That would 
> require navigating from the expression to its parent node. Is there a way to 
> do that?
There is no way to do this in C++.
Even if the name is followed by a pair of parenthese, this could either be a 
field with overloaded `operator()` (e.g. a `std::function field`) or a 
function with the same name.

It's much better to pick a separate highlighting kind for dependent names, this 
follows the actual semantics of C++.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67901



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


[PATCH] D67973: [libTooling][NFC] Switch StencilTest.cpp to use EXPECT_THAT_EXPECTED

2019-09-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67973



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


[PATCH] D67774: [Mangle] Add flag to asm labels to disable '\01' prefixing

2019-09-25 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

Thanks. One last and minor request: please mention in the comment on 
IsLiteralLabel that non-literal labels are used by some external AST sources 
like LLDB.


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

https://reviews.llvm.org/D67774



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


[PATCH] D67774: [Mangle] Add flag to asm labels to disable '\01' prefixing

2019-09-25 Thread Raphael Isemann via Phabricator via cfe-commits
teemperor resigned from this revision.
teemperor added a comment.

This LGTM modulo rjmccall's comment.


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

https://reviews.llvm.org/D67774



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


r372833 - [OpenCL] Add image query builtin functions

2019-09-25 Thread Sven van Haastregt via cfe-commits
Author: svenvh
Date: Wed Sep 25 02:12:59 2019
New Revision: 372833

URL: http://llvm.org/viewvc/llvm-project?rev=372833&view=rev
Log:
[OpenCL] Add image query builtin functions

Add the image query builtin functions from the OpenCL C specification.

Patch by Pierre Gondois and Sven van Haastregt.

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

Modified:
cfe/trunk/lib/Sema/OpenCLBuiltins.td
cfe/trunk/test/SemaOpenCL/fdeclare-opencl-builtins.cl

Modified: cfe/trunk/lib/Sema/OpenCLBuiltins.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/OpenCLBuiltins.td?rev=372833&r1=372832&r2=372833&view=diff
==
--- cfe/trunk/lib/Sema/OpenCLBuiltins.td (original)
+++ cfe/trunk/lib/Sema/OpenCLBuiltins.td Wed Sep 25 02:12:59 2019
@@ -593,6 +593,31 @@ foreach aQual = ["WO", "RW"] in {
   def : Builtin<"write_imagef", [Void, ImageType, 
VectorType, Float]>;
 }
 
+// --- Table 25: Image Query Functions ---
+foreach aQual = ["RO", "WO", "RW"] in {
+  foreach imgTy = [Image1d, Image1dBuffer, Image2d, Image3d,
+   Image1dArray, Image2dArray, Image2dDepth,
+   Image2dArrayDepth] in {
+foreach name = ["get_image_width", "get_image_channel_data_type",
+"get_image_channel_order"] in {
+  def : Builtin]>;
+}
+  }
+  foreach imgTy = [Image2d, Image3d, Image2dArray, Image2dDepth,
+   Image2dArrayDepth] in {
+def : Builtin<"get_image_height", [Int, ImageType]>;
+  }
+  def : Builtin<"get_image_depth", [Int, ImageType]>;
+  foreach imgTy = [Image2d, Image2dArray, Image2dDepth,
+   Image2dArrayDepth] in {
+def : Builtin<"get_image_dim", [VectorType, ImageType]>;
+  }
+  def : Builtin<"get_image_dim", [VectorType, ImageType]>;
+  foreach imgTy = [Image1dArray, Image2dArray, Image2dArrayDepth] in {
+def : Builtin<"get_image_array_size", [Size, ImageType]>;
+  }
+}
+
 // OpenCL extension v2.0 s5.1.9: Built-in Image Read Functions
 // --- Table 8 ---
 foreach aQual = ["RO"] in {

Modified: cfe/trunk/test/SemaOpenCL/fdeclare-opencl-builtins.cl
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaOpenCL/fdeclare-opencl-builtins.cl?rev=372833&r1=372832&r2=372833&view=diff
==
--- cfe/trunk/test/SemaOpenCL/fdeclare-opencl-builtins.cl (original)
+++ cfe/trunk/test/SemaOpenCL/fdeclare-opencl-builtins.cl Wed Sep 25 02:12:59 
2019
@@ -71,6 +71,8 @@ kernel void basic_image_readonly(read_on
   resf = read_imagef(image_read_only_image2d, i2);
   res = read_imageh(image_read_only_image2d, i2);
   res = read_imageh(image_read_only_image2d, sampler, i2);
+
+  int imgWidth = get_image_width(image_read_only_image2d);
 }
 
 #if __OPENCL_C_VERSION__ >= CL_VERSION_2_0
@@ -79,6 +81,8 @@ kernel void basic_image_readwrite(read_w
   int4 i4;
 
   write_imageh(image_read_write_image3d, i4, h4);
+
+  int imgDepth = get_image_depth(image_read_write_image3d);
 }
 #endif // __OPENCL_C_VERSION__ >= CL_VERSION_2_0
 


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


[PATCH] D67713: [OpenCL] Add image query builtin functions

2019-09-25 Thread Sven van Haastregt via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL372833: [OpenCL] Add image query builtin functions (authored 
by svenvh, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D67713?vs=220683&id=221691#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D67713

Files:
  cfe/trunk/lib/Sema/OpenCLBuiltins.td
  cfe/trunk/test/SemaOpenCL/fdeclare-opencl-builtins.cl


Index: cfe/trunk/lib/Sema/OpenCLBuiltins.td
===
--- cfe/trunk/lib/Sema/OpenCLBuiltins.td
+++ cfe/trunk/lib/Sema/OpenCLBuiltins.td
@@ -593,6 +593,31 @@
   def : Builtin<"write_imagef", [Void, ImageType, 
VectorType, Float]>;
 }
 
+// --- Table 25: Image Query Functions ---
+foreach aQual = ["RO", "WO", "RW"] in {
+  foreach imgTy = [Image1d, Image1dBuffer, Image2d, Image3d,
+   Image1dArray, Image2dArray, Image2dDepth,
+   Image2dArrayDepth] in {
+foreach name = ["get_image_width", "get_image_channel_data_type",
+"get_image_channel_order"] in {
+  def : Builtin]>;
+}
+  }
+  foreach imgTy = [Image2d, Image3d, Image2dArray, Image2dDepth,
+   Image2dArrayDepth] in {
+def : Builtin<"get_image_height", [Int, ImageType]>;
+  }
+  def : Builtin<"get_image_depth", [Int, ImageType]>;
+  foreach imgTy = [Image2d, Image2dArray, Image2dDepth,
+   Image2dArrayDepth] in {
+def : Builtin<"get_image_dim", [VectorType, ImageType]>;
+  }
+  def : Builtin<"get_image_dim", [VectorType, ImageType]>;
+  foreach imgTy = [Image1dArray, Image2dArray, Image2dArrayDepth] in {
+def : Builtin<"get_image_array_size", [Size, ImageType]>;
+  }
+}
+
 // OpenCL extension v2.0 s5.1.9: Built-in Image Read Functions
 // --- Table 8 ---
 foreach aQual = ["RO"] in {
Index: cfe/trunk/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- cfe/trunk/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ cfe/trunk/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -71,6 +71,8 @@
   resf = read_imagef(image_read_only_image2d, i2);
   res = read_imageh(image_read_only_image2d, i2);
   res = read_imageh(image_read_only_image2d, sampler, i2);
+
+  int imgWidth = get_image_width(image_read_only_image2d);
 }
 
 #if __OPENCL_C_VERSION__ >= CL_VERSION_2_0
@@ -79,6 +81,8 @@
   int4 i4;
 
   write_imageh(image_read_write_image3d, i4, h4);
+
+  int imgDepth = get_image_depth(image_read_write_image3d);
 }
 #endif // __OPENCL_C_VERSION__ >= CL_VERSION_2_0
 


Index: cfe/trunk/lib/Sema/OpenCLBuiltins.td
===
--- cfe/trunk/lib/Sema/OpenCLBuiltins.td
+++ cfe/trunk/lib/Sema/OpenCLBuiltins.td
@@ -593,6 +593,31 @@
   def : Builtin<"write_imagef", [Void, ImageType, VectorType, Float]>;
 }
 
+// --- Table 25: Image Query Functions ---
+foreach aQual = ["RO", "WO", "RW"] in {
+  foreach imgTy = [Image1d, Image1dBuffer, Image2d, Image3d,
+   Image1dArray, Image2dArray, Image2dDepth,
+   Image2dArrayDepth] in {
+foreach name = ["get_image_width", "get_image_channel_data_type",
+"get_image_channel_order"] in {
+  def : Builtin]>;
+}
+  }
+  foreach imgTy = [Image2d, Image3d, Image2dArray, Image2dDepth,
+   Image2dArrayDepth] in {
+def : Builtin<"get_image_height", [Int, ImageType]>;
+  }
+  def : Builtin<"get_image_depth", [Int, ImageType]>;
+  foreach imgTy = [Image2d, Image2dArray, Image2dDepth,
+   Image2dArrayDepth] in {
+def : Builtin<"get_image_dim", [VectorType, ImageType]>;
+  }
+  def : Builtin<"get_image_dim", [VectorType, ImageType]>;
+  foreach imgTy = [Image1dArray, Image2dArray, Image2dArrayDepth] in {
+def : Builtin<"get_image_array_size", [Size, ImageType]>;
+  }
+}
+
 // OpenCL extension v2.0 s5.1.9: Built-in Image Read Functions
 // --- Table 8 ---
 foreach aQual = ["RO"] in {
Index: cfe/trunk/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- cfe/trunk/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ cfe/trunk/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -71,6 +71,8 @@
   resf = read_imagef(image_read_only_image2d, i2);
   res = read_imageh(image_read_only_image2d, i2);
   res = read_imageh(image_read_only_image2d, sampler, i2);
+
+  int imgWidth = get_image_width(image_read_only_image2d);
 }
 
 #if __OPENCL_C_VERSION__ >= CL_VERSION_2_0
@@ -79,6 +81,8 @@
   int4 i4;
 
   write_imageh(image_read_write_image3d, i4, h4);
+
+  int imgDepth = get_image_depth(image_read_write_image3d);
 }
 #endif // __OPENCL_C_VERSION__ >= CL_VERSION_2_0
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm

[PATCH] D67992: [Sema] Add FunctionTypeUnwrapper

2019-09-25 Thread Dimitry Andric via Phabricator via cfe-commits
dim added a comment.

This works for me, and also for the original test case from 
https://bugs.freebsd.org/240764.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67992



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


[PATCH] D67901: [clangd] Improve semantic highlighting in dependent contexts (fixes #154)

2019-09-25 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:181
+  addToken(E->getMemberLoc(), E->getQualifier()
+  ? HighlightingKind::StaticField
+  : HighlightingKind::Field);

ilya-biryukov wrote:
> nridge wrote:
> > hokein wrote:
> > > This could be member functions, a case is like
> > > 
> > > ```
> > > template
> > > class Foo {
> > > public:
> > >   void foo() {
> > > this->foo();
> > >   }
> > > };
> > > ```
> > Thanks for the example.
> > 
> > Do you have a suggestion for how to discriminate this case? To me, it would 
> > seem logical to do it based on syntax (highlight as a member function if 
> > the expression forms the function name of a function call expression). That 
> > would require navigating from the expression to its parent node. Is there a 
> > way to do that?
> There is no way to do this in C++.
> Even if the name is followed by a pair of parenthese, this could either be a 
> field with overloaded `operator()` (e.g. a `std::function field`) or 
> a function with the same name.
> 
> It's much better to pick a separate highlighting kind for dependent names, 
> this follows the actual semantics of C++.
+1, I think we should just highlight them as a dependent type.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:159
+  addToken(E->getNameLoc(), E->getNamingClass()
+? HighlightingKind::StaticMethod
+: HighlightingKind::Function);

I'm doubting we will encounter other exceptions.

```
struct X {
template
static T t;
};

template
void f() {
  X::t; // this is a `UnresolvedLookupExpr`.
}
```



Comment at: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp:54
   {HighlightingKind::StaticMethod, "StaticMethod"},
+  {HighlightingKind::Typedef, "Typedef"},
+  {HighlightingKind::DependentType, "DependentType"},

thanks for catching this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67901



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


[PATCH] D67960: [clangd] Move the existing heder-source-switch implemenation out of clangdServer.

2019-09-25 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 221703.
hokein marked 3 inline comments as done.
hokein added a comment.
Herald added a subscriber: mgorny.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67960

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/HeaderSourceSwitch.cpp
  clang-tools-extra/clangd/HeaderSourceSwitch.h
  clang-tools-extra/clangd/unittests/CMakeLists.txt
  clang-tools-extra/clangd/unittests/ClangdTests.cpp
  clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp

Index: clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
@@ -0,0 +1,76 @@
+//===--- HeaderSourceSwitchTests.cpp - ---*- 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 "HeaderSourceSwitch.h"
+
+#include "TestFS.h"
+#include "TestTU.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+TEST(HeaderSourceSwitchTest, FileHeuristic) {
+  MockFSProvider FS;
+  auto FooCpp = testPath("foo.cpp");
+  auto FooH = testPath("foo.h");
+  auto Invalid = testPath("main.cpp");
+
+  FS.Files[FooCpp];
+  FS.Files[FooH];
+  FS.Files[Invalid];
+  Optional PathResult =
+  getCorrespondingHeaderOrSource(FooCpp, FS.getFileSystem());
+  EXPECT_TRUE(PathResult.hasValue());
+  ASSERT_EQ(PathResult.getValue(), FooH);
+
+  PathResult = getCorrespondingHeaderOrSource(FooH, FS.getFileSystem());
+  EXPECT_TRUE(PathResult.hasValue());
+  ASSERT_EQ(PathResult.getValue(), FooCpp);
+
+  // Test with header file in capital letters and different extension, source
+  // file with different extension
+  auto FooC = testPath("bar.c");
+  auto FooHH = testPath("bar.HH");
+
+  FS.Files[FooC];
+  FS.Files[FooHH];
+  PathResult = getCorrespondingHeaderOrSource(FooC, FS.getFileSystem());
+  EXPECT_TRUE(PathResult.hasValue());
+  ASSERT_EQ(PathResult.getValue(), FooHH);
+
+  // Test with both capital letters
+  auto Foo2C = testPath("foo2.C");
+  auto Foo2HH = testPath("foo2.HH");
+  FS.Files[Foo2C];
+  FS.Files[Foo2HH];
+  PathResult = getCorrespondingHeaderOrSource(Foo2C, FS.getFileSystem());
+  EXPECT_TRUE(PathResult.hasValue());
+  ASSERT_EQ(PathResult.getValue(), Foo2HH);
+
+  // Test with source file as capital letter and .hxx header file
+  auto Foo3C = testPath("foo3.C");
+  auto Foo3HXX = testPath("foo3.hxx");
+
+  FS.Files[Foo3C];
+  FS.Files[Foo3HXX];
+  PathResult = getCorrespondingHeaderOrSource(Foo3C, FS.getFileSystem());
+  EXPECT_TRUE(PathResult.hasValue());
+  ASSERT_EQ(PathResult.getValue(), Foo3HXX);
+
+  // Test if asking for a corresponding file that doesn't exist returns an empty
+  // string.
+  PathResult = getCorrespondingHeaderOrSource(Invalid, FS.getFileSystem());
+  EXPECT_FALSE(PathResult.hasValue());
+}
+
+} // namespace
+} // namespace clangd
+} // namespace clang
Index: clang-tools-extra/clangd/unittests/ClangdTests.cpp
===
--- clang-tools-extra/clangd/unittests/ClangdTests.cpp
+++ clang-tools-extra/clangd/unittests/ClangdTests.cpp
@@ -765,82 +765,6 @@
   }
 }
 
-TEST_F(ClangdVFSTest, CheckSourceHeaderSwitch) {
-  MockFSProvider FS;
-  ErrorCheckingDiagConsumer DiagConsumer;
-  MockCompilationDatabase CDB;
-  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
-
-  auto SourceContents = R"cpp(
-  #include "foo.h"
-  int b = a;
-  )cpp";
-
-  auto FooCpp = testPath("foo.cpp");
-  auto FooH = testPath("foo.h");
-  auto Invalid = testPath("main.cpp");
-
-  FS.Files[FooCpp] = SourceContents;
-  FS.Files[FooH] = "int a;";
-  FS.Files[Invalid] = "int main() { \n return 0; \n }";
-
-  Optional PathResult = Server.switchSourceHeader(FooCpp);
-  EXPECT_TRUE(PathResult.hasValue());
-  ASSERT_EQ(PathResult.getValue(), FooH);
-
-  PathResult = Server.switchSourceHeader(FooH);
-  EXPECT_TRUE(PathResult.hasValue());
-  ASSERT_EQ(PathResult.getValue(), FooCpp);
-
-  SourceContents = R"c(
-  #include "foo.HH"
-  int b = a;
-  )c";
-
-  // Test with header file in capital letters and different extension, source
-  // file with different extension
-  auto FooC = testPath("bar.c");
-  auto FooHH = testPath("bar.HH");
-
-  FS.Files[FooC] = SourceContents;
-  FS.Files[FooHH] = "int a;";
-
-  PathResult = Server.switchSourceHeader(FooC);
-  EXPECT_TRUE(PathResult.hasValue());
-  ASSERT_EQ(PathResult.getValue(), FooHH);
-
-  // Test with both capital letters
-  auto Foo2C = testPath("foo2.C");
-  a

[clang-tools-extra] r372841 - [clangd] Move the existing heder-source-switch implemenation out of clangdServer.

2019-09-25 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Sep 25 03:30:22 2019
New Revision: 372841

URL: http://llvm.org/viewvc/llvm-project?rev=372841&view=rev
Log:
[clangd] Move the existing heder-source-switch implemenation out of 
clangdServer.

Summary: This is a NFC change.

Reviewers: kadircet

Reviewed By: kadircet

Subscribers: ilya-biryukov, MaskRay, jkorous, arphaman, usaxena95, cfe-commits

Tags: #clang

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

Added:
clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp
clang-tools-extra/trunk/clangd/HeaderSourceSwitch.h
clang-tools-extra/trunk/clangd/unittests/HeaderSourceSwitchTests.cpp
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/clangd/unittests/CMakeLists.txt
clang-tools-extra/trunk/clangd/unittests/ClangdTests.cpp

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=372841&r1=372840&r2=372841&view=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Wed Sep 25 03:30:22 2019
@@ -56,6 +56,7 @@ add_clang_library(clangDaemon
   FuzzyMatch.cpp
   GlobalCompilationDatabase.cpp
   Headers.cpp
+  HeaderSourceSwitch.cpp
   IncludeFixer.cpp
   JSONTransport.cpp
   Logger.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=372841&r1=372840&r2=372841&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Wed Sep 25 03:30:22 2019
@@ -11,6 +11,7 @@
 #include "FindSymbols.h"
 #include "Format.h"
 #include "FormattedString.h"
+#include "HeaderSourceSwitch.h"
 #include "Headers.h"
 #include "Logger.h"
 #include "ParsedAST.h"
@@ -449,60 +450,7 @@ void ClangdServer::locateSymbolAt(PathRe
 }
 
 llvm::Optional ClangdServer::switchSourceHeader(PathRef Path) {
-
-  llvm::StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
-".c++", ".m", ".mm"};
-  llvm::StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
-
-  llvm::StringRef PathExt = llvm::sys::path::extension(Path);
-
-  // Lookup in a list of known extensions.
-  auto SourceIter =
-  llvm::find_if(SourceExtensions, [&PathExt](PathRef SourceExt) {
-return SourceExt.equals_lower(PathExt);
-  });
-  bool IsSource = SourceIter != std::end(SourceExtensions);
-
-  auto HeaderIter =
-  llvm::find_if(HeaderExtensions, [&PathExt](PathRef HeaderExt) {
-return HeaderExt.equals_lower(PathExt);
-  });
-
-  bool IsHeader = HeaderIter != std::end(HeaderExtensions);
-
-  // We can only switch between the known extensions.
-  if (!IsSource && !IsHeader)
-return None;
-
-  // Array to lookup extensions for the switch. An opposite of where original
-  // extension was found.
-  llvm::ArrayRef NewExts;
-  if (IsSource)
-NewExts = HeaderExtensions;
-  else
-NewExts = SourceExtensions;
-
-  // Storage for the new path.
-  llvm::SmallString<128> NewPath = llvm::StringRef(Path);
-
-  // Instance of vfs::FileSystem, used for file existence checks.
-  auto FS = FSProvider.getFileSystem();
-
-  // Loop through switched extension candidates.
-  for (llvm::StringRef NewExt : NewExts) {
-llvm::sys::path::replace_extension(NewPath, NewExt);
-if (FS->exists(NewPath))
-  return NewPath.str().str(); // First str() to convert from SmallString to
-  // StringRef, second to convert from 
StringRef
-  // to std::string
-
-// Also check NewExt in upper-case, just in case.
-llvm::sys::path::replace_extension(NewPath, NewExt.upper());
-if (FS->exists(NewPath))
-  return NewPath.str().str();
-  }
-
-  return None;
+  return getCorrespondingHeaderOrSource(Path, FSProvider.getFileSystem());
 }
 
 llvm::Expected

Added: clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp?rev=372841&view=auto
==
--- clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp (added)
+++ clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp Wed Sep 25 03:30:22 
2019
@@ -0,0 +1,68 @@
+//===--- HeaderSourceSwitch.cpp - *- 
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
+//
+//===--

[PATCH] D67960: [clangd] Move the existing heder-source-switch implemenation out of clangdServer.

2019-09-25 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL372841: [clangd] Move the existing heder-source-switch 
implemenation out of… (authored by hokein, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D67960?vs=221703&id=221704#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D67960

Files:
  clang-tools-extra/trunk/clangd/CMakeLists.txt
  clang-tools-extra/trunk/clangd/ClangdServer.cpp
  clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp
  clang-tools-extra/trunk/clangd/HeaderSourceSwitch.h
  clang-tools-extra/trunk/clangd/unittests/CMakeLists.txt
  clang-tools-extra/trunk/clangd/unittests/ClangdTests.cpp
  clang-tools-extra/trunk/clangd/unittests/HeaderSourceSwitchTests.cpp

Index: clang-tools-extra/trunk/clangd/ClangdServer.cpp
===
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp
@@ -11,6 +11,7 @@
 #include "FindSymbols.h"
 #include "Format.h"
 #include "FormattedString.h"
+#include "HeaderSourceSwitch.h"
 #include "Headers.h"
 #include "Logger.h"
 #include "ParsedAST.h"
@@ -449,60 +450,7 @@
 }
 
 llvm::Optional ClangdServer::switchSourceHeader(PathRef Path) {
-
-  llvm::StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
-".c++", ".m", ".mm"};
-  llvm::StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
-
-  llvm::StringRef PathExt = llvm::sys::path::extension(Path);
-
-  // Lookup in a list of known extensions.
-  auto SourceIter =
-  llvm::find_if(SourceExtensions, [&PathExt](PathRef SourceExt) {
-return SourceExt.equals_lower(PathExt);
-  });
-  bool IsSource = SourceIter != std::end(SourceExtensions);
-
-  auto HeaderIter =
-  llvm::find_if(HeaderExtensions, [&PathExt](PathRef HeaderExt) {
-return HeaderExt.equals_lower(PathExt);
-  });
-
-  bool IsHeader = HeaderIter != std::end(HeaderExtensions);
-
-  // We can only switch between the known extensions.
-  if (!IsSource && !IsHeader)
-return None;
-
-  // Array to lookup extensions for the switch. An opposite of where original
-  // extension was found.
-  llvm::ArrayRef NewExts;
-  if (IsSource)
-NewExts = HeaderExtensions;
-  else
-NewExts = SourceExtensions;
-
-  // Storage for the new path.
-  llvm::SmallString<128> NewPath = llvm::StringRef(Path);
-
-  // Instance of vfs::FileSystem, used for file existence checks.
-  auto FS = FSProvider.getFileSystem();
-
-  // Loop through switched extension candidates.
-  for (llvm::StringRef NewExt : NewExts) {
-llvm::sys::path::replace_extension(NewPath, NewExt);
-if (FS->exists(NewPath))
-  return NewPath.str().str(); // First str() to convert from SmallString to
-  // StringRef, second to convert from StringRef
-  // to std::string
-
-// Also check NewExt in upper-case, just in case.
-llvm::sys::path::replace_extension(NewPath, NewExt.upper());
-if (FS->exists(NewPath))
-  return NewPath.str().str();
-  }
-
-  return None;
+  return getCorrespondingHeaderOrSource(Path, FSProvider.getFileSystem());
 }
 
 llvm::Expected
Index: clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp
===
--- clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp
+++ clang-tools-extra/trunk/clangd/HeaderSourceSwitch.cpp
@@ -0,0 +1,68 @@
+//===--- HeaderSourceSwitch.cpp - *- 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 "HeaderSourceSwitch.h"
+
+namespace clang {
+namespace clangd {
+
+llvm::Optional getCorrespondingHeaderOrSource(
+const Path &OriginalFile,
+llvm::IntrusiveRefCntPtr VFS) {
+  llvm::StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
+".c++", ".m", ".mm"};
+  llvm::StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
+
+  llvm::StringRef PathExt = llvm::sys::path::extension(OriginalFile);
+
+  // Lookup in a list of known extensions.
+  auto SourceIter =
+  llvm::find_if(SourceExtensions, [&PathExt](PathRef SourceExt) {
+return SourceExt.equals_lower(PathExt);
+  });
+  bool IsSource = SourceIter != std::end(SourceExtensions);
+
+  auto HeaderIter =
+  llvm::find_if(HeaderExtensions, [&PathExt](PathRef HeaderExt) {
+return HeaderExt.equals_lower(PathExt);
+  });
+  bool IsHeader = HeaderIter != std::end(HeaderExtensions);
+
+  //

r372844 - Revert r370850 "Re-commit r363191 "[MS] Pretend constexpr variable template specializations are inline""

2019-09-25 Thread Hans Wennborg via cfe-commits
Author: hans
Date: Wed Sep 25 04:09:46 2019
New Revision: 372844

URL: http://llvm.org/viewvc/llvm-project?rev=372844&view=rev
Log:
Revert r370850 "Re-commit r363191 "[MS] Pretend constexpr variable template 
specializations are inline""

This work-around was necessary to handle standard library headers in
Visual Studio 2019 16.2. Now that 16.3 has shipped to stable, we can
remove it.

> Re-commit r363191 "[MS] Pretend constexpr variable template specializations 
> are inline"
>
> While the next Visual Studio update (16.3) will fix this issue, that hasn't
> shipped yet. Until then Clang wouldn't work with MSVC's headers which seems
> unfortunate. Let's keep this in until VS 16.3 ships. (See also PR42843.)
>
>> Fixes link errors with clang and the latest Visual C++ 14.21.27702
>> headers, which was reported as PR42027.
>>
>> I chose to intentionally make these things linkonce_odr, i.e.
>> discardable, so that we don't emit definitions of these things in every
>> translation unit that includes STL headers.
>>
>> Note that this is *not* what MSVC does: MSVC has not yet implemented C++
>> DR2387, so they emit fully specialized constexpr variable templates with
>> static / internal linkage.
>>
>> Reviewers: rsmith
>>
>> Differential Revision: https://reviews.llvm.org/D63175

Removed:
cfe/trunk/test/CodeGenCXX/ms-constexpr-var-template.cpp
Modified:
cfe/trunk/lib/AST/ASTContext.cpp

Modified: cfe/trunk/lib/AST/ASTContext.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTContext.cpp?rev=372844&r1=372843&r2=372844&view=diff
==
--- cfe/trunk/lib/AST/ASTContext.cpp (original)
+++ cfe/trunk/lib/AST/ASTContext.cpp Wed Sep 25 04:09:46 2019
@@ -9915,25 +9915,10 @@ static GVALinkage basicGVALinkageForVari
 return StrongLinkage;
 
   case TSK_ExplicitSpecialization:
-if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
-  // If this is a fully specialized constexpr variable template, pretend it
-  // was marked inline. MSVC 14.21.27702 headers define _Is_integral in a
-  // header this way, and we don't want to emit non-discardable definitions
-  // of these variables in every TU that includes . This
-  // behavior is non-conforming, since another TU could use an extern
-  // template declaration for this variable, but for constexpr variables,
-  // it's unlikely for a user to want to do that. This behavior can be
-  // removed if the headers change to explicitly mark such variable 
template
-  // specializations inline.
-  if (isa(VD) && VD->isConstexpr())
-return GVA_DiscardableODR;
-
-  // Use ODR linkage for static data members of fully specialized templates
-  // to prevent duplicate definition errors with MSVC.
-  if (VD->isStaticDataMember())
-return GVA_StrongODR;
-}
-return StrongLinkage;
+return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
+   VD->isStaticDataMember()
+   ? GVA_StrongODR
+   : StrongLinkage;
 
   case TSK_ExplicitInstantiationDefinition:
 return GVA_StrongODR;

Removed: cfe/trunk/test/CodeGenCXX/ms-constexpr-var-template.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/ms-constexpr-var-template.cpp?rev=372843&view=auto
==
--- cfe/trunk/test/CodeGenCXX/ms-constexpr-var-template.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/ms-constexpr-var-template.cpp (removed)
@@ -1,11 +0,0 @@
-// RUN: %clang_cc1 -emit-llvm -triple=x86_64-windows-msvc -fms-compatibility 
%s -o - | FileCheck %s
-
-template  constexpr bool _Is_integer = false;
-template <> constexpr bool _Is_integer = true;
-template <> constexpr bool _Is_integer = false;
-extern "C" const bool *escape = &_Is_integer;
-
-// CHECK: @"??$_Is_integer@H@@3_NB" = linkonce_odr dso_local constant i8 1, 
comdat, align 1
-//   Should not emit _Is_integer, since it's not referenced.
-// CHECK-NOT: @"??$_Is_integer@D@@3_NB"
-// CHECK: @escape = dso_local global i8* @"??$_Is_integer@H@@3_NB", align 8


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


[PATCH] D63082: [Diagnostics] Added support for -Wint-in-bool-context

2019-09-25 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

It looks like bits of this landed recently. I don't know which of the commits 
it was, so I'm commenting here: The -Wint-in-bool context that clang emits are 
very useful and have found several bugs in Chromium, with just one false 
positive (which was in confusing code, so we changed that one too). Thank you 
for this useful warning :)

(https://crbug.com/1007367 lists what this founds, if you're curious.)


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

https://reviews.llvm.org/D63082



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


r372846 - Add a release note for r372844

2019-09-25 Thread Hans Wennborg via cfe-commits
Author: hans
Date: Wed Sep 25 04:53:17 2019
New Revision: 372846

URL: http://llvm.org/viewvc/llvm-project?rev=372846&view=rev
Log:
Add a release note for r372844

Modified:
cfe/trunk/docs/ReleaseNotes.rst

Modified: cfe/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ReleaseNotes.rst?rev=372846&r1=372845&r2=372846&view=diff
==
--- cfe/trunk/docs/ReleaseNotes.rst (original)
+++ cfe/trunk/docs/ReleaseNotes.rst Wed Sep 25 04:53:17 2019
@@ -102,7 +102,18 @@ Attribute Changes in Clang
 Windows Support
 ---
 
-- ...
+- Previous Clang versions contained a work-around to avoid an issue with the
+  standard library headers in Visual Studio 2019 versions prior to 16.3. This
+  work-around has now been removed, and users of Visual Studio 2019 are
+  encouraged to upgrade to 16.3 or later, otherwise they may see link errors as
+  below:
+
+  .. code-block:: console
+
+error LNK2005: "bool const std::_Is_integral" 
(??$_Is_integral@H@std@@3_NB) already defined
+
+
+
 
 C Language Changes in Clang
 ---


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


[PATCH] D67907: [clangd] Implement a smart version of HeaderSource switch.

2019-09-25 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 221724.
hokein added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67907

Files:
  clang-tools-extra/clangd/HeaderSourceSwitch.cpp
  clang-tools-extra/clangd/HeaderSourceSwitch.h
  clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp

Index: clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
+++ clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp
@@ -10,6 +10,7 @@
 
 #include "TestFS.h"
 #include "TestTU.h"
+#include "index/MemIndex.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
@@ -71,6 +72,157 @@
   EXPECT_FALSE(PathResult.hasValue());
 }
 
+MATCHER_P(DeclNamed, Name, "") {
+  if (const NamedDecl *ND = dyn_cast(arg))
+if (ND->getQualifiedNameAsString() == Name)
+  return true;
+  return false;
+}
+
+TEST(HeaderSourceSwitchTest, GetLocalDecls) {
+  TestTU TU;
+  TU.HeaderCode = R"cpp(
+  void HeaderOnly();
+  )cpp";
+  TU.Code = R"cpp(
+  void MainF1();
+  class Foo {};
+  namespace ns {
+  class Foo {
+void method();
+int field;
+  };
+  } // namespace ns
+
+  // Non-indexable symbols
+  namespace {
+  void Ignore1() {}
+  }
+
+  )cpp";
+
+  auto AST = TU.build();
+  EXPECT_THAT(getIndexableLocalDecls(AST),
+  testing::UnorderedElementsAre(
+  DeclNamed("MainF1"), DeclNamed("Foo"), DeclNamed("ns::Foo"),
+  DeclNamed("ns::Foo::method"), DeclNamed("ns::Foo::field")));
+}
+
+TEST(HeaderSourceSwitchTest, FromHeaderToSource) {
+  // build a proper index, which contains symbols:
+  //   A_Sym1, declared in TestTU.h, defined in a.cpp
+  //   B_Sym[1-2], declared in TestTU.h, defined in b.cpp
+  SymbolSlab::Builder AllSymbols;
+  TestTU Testing;
+  Testing.HeaderFilename = "TestTU.h";
+  Testing.HeaderCode = "void A_Sym1();";
+  Testing.Filename = "a.cpp";
+  Testing.Code = "void A_Sym1() {};";
+  for (auto &Sym : Testing.headerSymbols())
+AllSymbols.insert(Sym);
+
+  Testing.HeaderCode = R"cpp(
+  void B_Sym1();
+  void B_Sym2();
+  )cpp";
+  Testing.Filename = "b.cpp";
+  Testing.Code = R"cpp(
+  void B_Sym1() {}
+  void B_Sym2() {}
+  )cpp";
+  for (auto &Sym : Testing.headerSymbols())
+AllSymbols.insert(Sym);
+  auto Index = MemIndex::build(std::move(AllSymbols).build(), {}, {});
+
+  // Test for swtich from .h header to .cc source
+  struct {
+llvm::StringRef HeaderCode;
+llvm::Optional ExpectedSource;
+  } TestCases[] = {{R"cpp(// empty, no header found)cpp", llvm::None},
+   {R"cpp(
+   // no definition found in the index.
+   void NonDefinition();
+)cpp",
+llvm::None},
+   {R"cpp(
+   void A_Sym1();
+  )cpp",
+testPath("a.cpp")},
+   {R"cpp(
+   // b.cpp wins.
+   void A_Sym1();
+   void B_Sym1();
+   void B_Sym2();
+)cpp",
+testPath("b.cpp")}};
+  const std::string &TestFilePath = testPath("TestTU.h");
+  for (const auto &Case : TestCases) {
+TestTU TU = TestTU::withCode(Case.HeaderCode);
+TU.ExtraArgs.push_back("-xc++-header"); // inform clang this is a header.
+auto HeaderAST = TU.build();
+EXPECT_EQ(Case.ExpectedSource, getCorrespondingHeaderOrSource(
+   TestFilePath, HeaderAST, Index.get()));
+  }
+}
+
+TEST(HeaderSourceSwitchTest, FromSourceToHeader) {
+  // build a proper index, which contains symbols:
+  //   A_Sym1, declared in a.h, defined in TestTU.cpp
+  //   B_Sym[1-2], declared in b.h, defined in TestTU.cpp
+  TestTU TUForIndex = TestTU::withCode(R"cpp(
+  #include "a.h"
+  #include "b.h"
+
+  void A_Sym1() {}
+
+  void B_Sym1() {}
+  void B_Sym2() {}
+  )cpp");
+  TUForIndex.AdditionalFiles["a.h"] = R"cpp(
+  void A_Sym1();
+  )cpp";
+  TUForIndex.AdditionalFiles["b.h"] = R"cpp(
+  void B_Sym1();
+  void B_Sym2();
+  )cpp";
+  TUForIndex.Filename = "TestTU.cpp";
+  auto Index = TUForIndex.index();
+
+  // Test for switching from .cc source file to .h header.
+  struct {
+llvm::StringRef SourceCode;
+llvm::Optional ExpectedResult;
+  } TestCases[] = {
+  {R"cpp(// empty, no header found)cpp", llvm::None},
+  {R"cpp(
+ // symbol not in index, no header found
+ void Local() {}
+   )cpp",
+   llvm::None},
+
+  {R"cpp(
+ // a.h wins.
+ void A_Sym1() {}
+   )cpp",
+   testPath("a.h")},
+
+  {R"cpp(
+ // b.h wins.
+ void A_Sym1() {}
+ void B_Sym1() {}
+ void B_Sym2() {}
+   )cpp",
+   testPath("b.h")},
+  };
+  const std::string &TestFilePath = testPath("TestTU.cpp");
+  for (const auto &Case : TestCases) {
+TestTU TU = TestTU::withCode(Case.SourceCode);
+auto AST = TU.build();
+EXPECT_EQ

[PATCH] D67961: [libTooling] Introduce the MatchConsumer abstraction

2019-09-25 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr accepted this revision.
gribozavr added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/include/clang/Tooling/Refactoring/MatchConsumer.h:9
+///
+/// /file This file defines the *MatchConsumer* abstraction: a computation over
+/// match results, specifically the `ast_matchers::MatchFinder::MatchResult`

\file



Comment at: clang/include/clang/Tooling/Refactoring/MatchConsumer.h:27
+
+/// A central abstraction of the Transformer framework is computation over the
+/// results of a match (represented by \c MatchFinder::MatchResult). We

The comment seems to be a mix of documentation and design justification. How 
about this?

```
A failable computation over nodes bound by AST matchers.

It is a central abstraction of the Transformer framework.

The computation should report any errors though its return value (rather than 
terminating the program) to enable usage in interactive scenarios like 
clang-query.
```



Comment at: clang/include/clang/Tooling/Refactoring/MatchConsumer.h:39
+
+/// Convenience function for a common error generated by `MatchConsumer`s.
+inline llvm::Error notBoundError(llvm::StringRef Id) {

"Creates an error that signals that a `MatchConsumer` expected a certain node 
to be bound by AST matchers, but is was not actually bound."


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67961



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


[PATCH] D67826: [clangd] A helper to find explicit references and their names

2019-09-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 221728.
ilya-biryukov marked an inline comment as done.
ilya-biryukov added a comment.

- s/Decl* S/Decl* D/g


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67826

Files:
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/FindTarget.h
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp

Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -9,6 +9,9 @@
 
 #include "Selection.h"
 #include "TestTU.h"
+#include "clang/AST/Decl.h"
+#include "clang/Basic/SourceLocation.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Testing/Support/Annotations.h"
 #include "gmock/gmock.h"
@@ -464,6 +467,223 @@
   EXPECT_DECLS("ObjCObjectTypeLoc");
 }
 
+class FindExplicitReferencesTest : public ::testing::Test {
+protected:
+  struct AllRefs {
+std::string AnnotatedCode;
+std::string DumpedReferences;
+  };
+
+  /// Parses \p Code, finds function '::foo' and annotates its body with results
+  /// of findExplicitReferecnces.
+  /// See actual tests for examples of annotation format.
+  AllRefs annotateReferencesInFoo(llvm::StringRef Code) {
+TestTU TU;
+TU.Code = Code;
+
+auto AST = TU.build();
+auto &Func = llvm::cast(findDecl(AST, "foo"));
+
+std::vector Refs;
+findExplicitReferences(Func.getBody(), [&Refs](ReferenceLoc R) {
+  Refs.push_back(std::move(R));
+});
+
+auto &SM = AST.getSourceManager();
+llvm::sort(Refs, [&](const ReferenceLoc &L, const ReferenceLoc &R) {
+  return SM.isBeforeInTranslationUnit(L.NameLoc, R.NameLoc);
+});
+
+std::string AnnotatedCode;
+unsigned NextCodeChar = 0;
+for (unsigned I = 0; I < Refs.size(); ++I) {
+  auto &R = Refs[I];
+
+  SourceLocation Pos = R.NameLoc;
+  assert(Pos.isValid());
+  if (Pos.isMacroID()) // FIXME: figure out how to show macro locations.
+Pos = SM.getExpansionLoc(Pos);
+  assert(Pos.isFileID());
+
+  FileID File;
+  unsigned Offset;
+  std::tie(File, Offset) = SM.getDecomposedLoc(Pos);
+  if (File == SM.getMainFileID()) {
+// Print the reference in a source code.
+assert(NextCodeChar <= Offset);
+AnnotatedCode += Code.substr(NextCodeChar, Offset - NextCodeChar);
+AnnotatedCode += "$" + std::to_string(I) + "^";
+
+NextCodeChar = Offset;
+  }
+}
+AnnotatedCode += Code.substr(NextCodeChar);
+
+std::string DumpedReferences;
+for (unsigned I = 0; I < Refs.size(); ++I)
+  DumpedReferences += llvm::formatv("{0}: {1}\n", I, Refs[I]);
+
+return AllRefs{std::move(AnnotatedCode), std::move(DumpedReferences)};
+  }
+};
+
+TEST_F(FindExplicitReferencesTest, All) {
+  std::pair Cases[] =
+  {
+  // Simple expressions.
+  {R"cpp(
+int global;
+int func();
+void foo(int param) {
+  $0^global = $1^param + $2^func();
+}
+)cpp",
+   "0: targets = {global}\n"
+   "1: targets = {param}\n"
+   "2: targets = {func}\n"},
+  {R"cpp(
+struct X { int a; };
+void foo(X x) {
+  $0^x.$1^a = 10;
+}
+)cpp",
+   "0: targets = {x}\n"
+   "1: targets = {X::a}\n"},
+  // Namespaces and aliases.
+  {R"cpp(
+  namespace ns {}
+  namespace alias = ns;
+  void foo() {
+using namespace $0^ns;
+using namespace $1^alias;
+  }
+)cpp",
+   "0: targets = {ns}\n"
+   "1: targets = {alias}\n"},
+  // Using declarations.
+  {R"cpp(
+  namespace ns { int global; }
+  void foo() {
+using $0^ns::$1^global;
+  }
+)cpp",
+   "0: targets = {ns}\n"
+   "1: targets = {ns::global}, qualifier = 'ns::'\n"},
+  // Simple types.
+  {R"cpp(
+ struct Struct { int a; };
+ using Typedef = int;
+ void foo() {
+   $0^Struct x;
+   $1^Typedef y;
+   static_cast<$2^Struct*>(0);
+ }
+   )cpp",
+   "0: targets = {Struct}\n"
+   "1: targets = {Typedef}\n"
+   "2: targets = {Struct}\n"},
+  // Name qualifiers.
+  {R"cpp(
+ namespace a { namespace b { struct S { typedef int type; }; } }
+ void foo() {
+   $0^a::$1^b::$2^S x;
+   using namespace $3^a::$4^b;
+   $5^S::$6^type y;
+ }
+)cpp",
+   "0: targets = {a}\n"
+   "1: targets = {a::b}, qualifier = 'a::'\n"
+   "2: targets = {a::b::S}, qualifier = 'a::b::'\n"
+   "3: targets = {a}\n"
+   "4: targets = {

[clang-tools-extra] r372859 - [clangd] A helper to find explicit references and their names

2019-09-25 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Sep 25 05:40:22 2019
New Revision: 372859

URL: http://llvm.org/viewvc/llvm-project?rev=372859&view=rev
Log:
[clangd] A helper to find explicit references and their names

Summary:
Allows to simplify pending code tweaks:
  - the upcoming DefineInline tweak (D66647)
  - remove using declaration (D56612)
  - qualify name under cursor (D56610)

Another potential future application is simplifying semantic highlighting.

Reviewers: kadircet

Reviewed By: kadircet

Subscribers: mgrang, jfb, MaskRay, jkorous, arphaman, usaxena95, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/FindTarget.cpp
clang-tools-extra/trunk/clangd/FindTarget.h
clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp

Modified: clang-tools-extra/trunk/clangd/FindTarget.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FindTarget.cpp?rev=372859&r1=372858&r2=372859&view=diff
==
--- clang-tools-extra/trunk/clangd/FindTarget.cpp (original)
+++ clang-tools-extra/trunk/clangd/FindTarget.cpp Wed Sep 25 05:40:22 2019
@@ -10,22 +10,33 @@
 #include "AST.h"
 #include "Logger.h"
 #include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/DeclVisitor.h"
 #include "clang/AST/DeclarationName.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/ExprObjC.h"
+#include "clang/AST/NestedNameSpecifier.h"
+#include "clang/AST/PrettyPrinter.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/AST/Type.h"
+#include "clang/AST/TypeLoc.h"
 #include "clang/AST/TypeLocVisitor.h"
+#include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
 
 namespace clang {
 namespace clangd {
 namespace {
+using ast_type_traits::DynTypedNode;
 
 LLVM_ATTRIBUTE_UNUSED std::string
 nodeToString(const ast_type_traits::DynTypedNode &N) {
@@ -348,12 +359,274 @@ allTargetDecls(const ast_type_traits::Dy
 llvm::SmallVector
 targetDecl(const ast_type_traits::DynTypedNode &N, DeclRelationSet Mask) {
   llvm::SmallVector Result;
-  for (const auto &Entry : allTargetDecls(N))
+  for (const auto &Entry : allTargetDecls(N)) {
 if (!(Entry.second & ~Mask))
   Result.push_back(Entry.first);
+  }
   return Result;
 }
 
+namespace {
+/// Find declarations explicitly referenced in the source code defined by \p N.
+/// For templates, will prefer to return a template instantiation whenever
+/// possible. However, can also return a template pattern if the specialization
+/// cannot be picked, e.g. in dependent code or when there is no corresponding
+/// Decl for a template instantitation, e.g. for templated using decls:
+///template  using Ptr = T*;
+///Ptr x;
+///^~~ there is no Decl for 'Ptr', so we return the template pattern.
+llvm::SmallVector
+explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask = {}) {
+  assert(!(Mask & (DeclRelation::TemplatePattern |
+   DeclRelation::TemplateInstantiation)) &&
+ "explicitRefenceTargets handles templates on its own");
+  auto Decls = allTargetDecls(N);
+
+  // We prefer to return template instantiation, but fallback to template
+  // pattern if instantiation is not available.
+  Mask |= DeclRelation::TemplatePattern | DeclRelation::TemplateInstantiation;
+
+  llvm::SmallVector TemplatePatterns;
+  llvm::SmallVector Targets;
+  bool SeenTemplateInstantiations = false;
+  for (auto &D : Decls) {
+if (D.second & ~Mask)
+  continue;
+if (D.second & DeclRelation::TemplatePattern) {
+  TemplatePatterns.push_back(llvm::cast(D.first));
+  continue;
+}
+if (D.second & DeclRelation::TemplateInstantiation)
+  SeenTemplateInstantiations = true;
+Targets.push_back(llvm::cast(D.first));
+  }
+  if (!SeenTemplateInstantiations)
+Targets.insert(Targets.end(), TemplatePatterns.begin(),
+   TemplatePatterns.end());
+  return Targets;
+}
+
+Optional refInDecl(const Decl *D) {
+  struct Visitor : ConstDeclVisitor {
+llvm::Optional Ref;
+
+void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
+  Ref = ReferenceLoc{D->getQualifierLoc(),
+ D->getIdentLocation(),
+ {D->getNominatedNamespaceAsWritten()}};
+}
+
+void VisitUsingDecl(const UsingDecl *D) {
+  Ref = ReferenceLoc{D->getQualifierLoc(), D->getLocation(),
+ explicitReferenceTargets(DynTypedNode::create(*D),
+  DeclRelation::Underlying)};
+}
+
+void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) 

[PATCH] D67826: [clangd] A helper to find explicit references and their names

2019-09-25 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL372859: [clangd] A helper to find explicit references and 
their names (authored by ibiryukov, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D67826?vs=221728&id=221730#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D67826

Files:
  clang-tools-extra/trunk/clangd/FindTarget.cpp
  clang-tools-extra/trunk/clangd/FindTarget.h
  clang-tools-extra/trunk/clangd/unittests/FindTargetTests.cpp

Index: clang-tools-extra/trunk/clangd/FindTarget.cpp
===
--- clang-tools-extra/trunk/clangd/FindTarget.cpp
+++ clang-tools-extra/trunk/clangd/FindTarget.cpp
@@ -10,22 +10,33 @@
 #include "AST.h"
 #include "Logger.h"
 #include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/DeclVisitor.h"
 #include "clang/AST/DeclarationName.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/ExprObjC.h"
+#include "clang/AST/NestedNameSpecifier.h"
+#include "clang/AST/PrettyPrinter.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/AST/Type.h"
+#include "clang/AST/TypeLoc.h"
 #include "clang/AST/TypeLocVisitor.h"
+#include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
 
 namespace clang {
 namespace clangd {
 namespace {
+using ast_type_traits::DynTypedNode;
 
 LLVM_ATTRIBUTE_UNUSED std::string
 nodeToString(const ast_type_traits::DynTypedNode &N) {
@@ -348,12 +359,274 @@
 llvm::SmallVector
 targetDecl(const ast_type_traits::DynTypedNode &N, DeclRelationSet Mask) {
   llvm::SmallVector Result;
-  for (const auto &Entry : allTargetDecls(N))
+  for (const auto &Entry : allTargetDecls(N)) {
 if (!(Entry.second & ~Mask))
   Result.push_back(Entry.first);
+  }
   return Result;
 }
 
+namespace {
+/// Find declarations explicitly referenced in the source code defined by \p N.
+/// For templates, will prefer to return a template instantiation whenever
+/// possible. However, can also return a template pattern if the specialization
+/// cannot be picked, e.g. in dependent code or when there is no corresponding
+/// Decl for a template instantitation, e.g. for templated using decls:
+///template  using Ptr = T*;
+///Ptr x;
+///^~~ there is no Decl for 'Ptr', so we return the template pattern.
+llvm::SmallVector
+explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask = {}) {
+  assert(!(Mask & (DeclRelation::TemplatePattern |
+   DeclRelation::TemplateInstantiation)) &&
+ "explicitRefenceTargets handles templates on its own");
+  auto Decls = allTargetDecls(N);
+
+  // We prefer to return template instantiation, but fallback to template
+  // pattern if instantiation is not available.
+  Mask |= DeclRelation::TemplatePattern | DeclRelation::TemplateInstantiation;
+
+  llvm::SmallVector TemplatePatterns;
+  llvm::SmallVector Targets;
+  bool SeenTemplateInstantiations = false;
+  for (auto &D : Decls) {
+if (D.second & ~Mask)
+  continue;
+if (D.second & DeclRelation::TemplatePattern) {
+  TemplatePatterns.push_back(llvm::cast(D.first));
+  continue;
+}
+if (D.second & DeclRelation::TemplateInstantiation)
+  SeenTemplateInstantiations = true;
+Targets.push_back(llvm::cast(D.first));
+  }
+  if (!SeenTemplateInstantiations)
+Targets.insert(Targets.end(), TemplatePatterns.begin(),
+   TemplatePatterns.end());
+  return Targets;
+}
+
+Optional refInDecl(const Decl *D) {
+  struct Visitor : ConstDeclVisitor {
+llvm::Optional Ref;
+
+void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
+  Ref = ReferenceLoc{D->getQualifierLoc(),
+ D->getIdentLocation(),
+ {D->getNominatedNamespaceAsWritten()}};
+}
+
+void VisitUsingDecl(const UsingDecl *D) {
+  Ref = ReferenceLoc{D->getQualifierLoc(), D->getLocation(),
+ explicitReferenceTargets(DynTypedNode::create(*D),
+  DeclRelation::Underlying)};
+}
+
+void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
+  Ref = ReferenceLoc{D->getQualifierLoc(),
+ D->getTargetNameLoc(),
+ {D->getAliasedNamespace()}};
+}
+  };
+
+  Visitor V;
+  V.Visit(D);
+  return V.Ref;
+}
+
+Optional refInExpr(const Expr *E) {
+  struct Visitor : ConstStmtVisitor {
+// FIXME: handle more complicated cases, e.g. ObjC, designated initializers.
+llvm

[PATCH] D63607: [clang][driver] Add basic --driver-mode=flang support for fortran

2019-09-25 Thread Peter Waller via Phabricator via cfe-commits
peterwaller-arm added a comment.

Hi All, I'm going on leave for two weeks, returning October 14th. I can 
plausibly respond to comments until 14:00 UTC tomorrow (Thu 25th Sept).

As a quick note, another piece of the puzzle has been submitted for review at 
https://github.com/flang-compiler/f18/pull/759, which is the flang-side binary 
which will link to this code and default to running the driver in flang mode.


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

https://reviews.llvm.org/D63607



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


[PATCH] D67969: [libTooling] Add `run` combinator to Stencils.

2019-09-25 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr added inline comments.



Comment at: clang/include/clang/Tooling/Refactoring/Stencil.h:181
+/// This supports user-defined extensions to the Stencil language.
+StencilPart run(MatchConsumer C);
+

We could reimplement all other stencils through `run()` and eliminate 
`StencilPartInterface`. 

The idea is to make `StencilPart` contain a 
`std::shared_ptr>`. Then `run()` can be implemented 
as creating a `StencilPart` directly, and everything else can be implemented in 
terms of `run()`.

WDYT?



Comment at: clang/lib/Tooling/Refactoring/Stencil.cpp:107
+// Equality is not defined over MatchConsumers, which are opaque.
+bool isEqualData(const MatchConsumer &A,
+ const MatchConsumer &B) {

Not very appropriate for this review -- but why do Stencils support equality 
comparison? As you note, with things like `run` it makes little sense to 
support it as an API. However, since a user does not know whether a Stencil can 
contain `run` or not, it is not very meaningful to compare them at all.

So if equality is not used for anything important, consider removing it?

Not to even mention that as implemented, equality is not reflexive.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67969



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


[clang-tools-extra] r372860 - [clangd] Add missing header guard, NFC.

2019-09-25 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Sep 25 05:54:53 2019
New Revision: 372860

URL: http://llvm.org/viewvc/llvm-project?rev=372860&view=rev
Log:
[clangd] Add missing header guard, NFC.

Modified:
clang-tools-extra/trunk/clangd/FindTarget.h
clang-tools-extra/trunk/clangd/HeaderSourceSwitch.h

Modified: clang-tools-extra/trunk/clangd/FindTarget.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FindTarget.h?rev=372860&r1=372859&r2=372860&view=diff
==
--- clang-tools-extra/trunk/clangd/FindTarget.h (original)
+++ clang-tools-extra/trunk/clangd/FindTarget.h Wed Sep 25 05:54:53 2019
@@ -19,6 +19,9 @@
 //
 
//===--===//
 
+#ifndef LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_FINDTARGET_H
+#define LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_FINDTARGET_H
+
 #include "clang/AST/ASTTypeTraits.h"
 #include "clang/AST/NestedNameSpecifier.h"
 #include "clang/AST/Stmt.h"
@@ -176,3 +179,5 @@ llvm::raw_ostream &operator<<(llvm::raw_
 
 } // namespace clangd
 } // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_FINDTARGET_H

Modified: clang-tools-extra/trunk/clangd/HeaderSourceSwitch.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/HeaderSourceSwitch.h?rev=372860&r1=372859&r2=372860&view=diff
==
--- clang-tools-extra/trunk/clangd/HeaderSourceSwitch.h (original)
+++ clang-tools-extra/trunk/clangd/HeaderSourceSwitch.h Wed Sep 25 05:54:53 2019
@@ -6,6 +6,9 @@
 //
 
//===--===//
 
+#ifndef LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_HEADERSOURCESWITCH_H
+#define LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_HEADERSOURCESWITCH_H
+
 #include "ParsedAST.h"
 #include "llvm/ADT/Optional.h"
 
@@ -20,3 +23,5 @@ llvm::Optional getCorrespondingHea
 
 } // namespace clangd
 } // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_HEADERSOURCESWITCH_H


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


[PATCH] D67969: [libTooling] Add `run` combinator to Stencils.

2019-09-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked an inline comment as done.
ymandel added inline comments.



Comment at: clang/include/clang/Tooling/Refactoring/Stencil.h:181
+/// This supports user-defined extensions to the Stencil language.
+StencilPart run(MatchConsumer C);
+

gribozavr wrote:
> We could reimplement all other stencils through `run()` and eliminate 
> `StencilPartInterface`. 
> 
> The idea is to make `StencilPart` contain a 
> `std::shared_ptr>`. Then `run()` can be 
> implemented as creating a `StencilPart` directly, and everything else can be 
> implemented in terms of `run()`.
> 
> WDYT?
Answering both questions together: the equality function is designed to make 
testing of the format-string parser feasible (or, at least, reasonable).  As 
is, the only reason not to do what you suggest above is exactly the equality 
function -- otherwise, StencilPart is just 
`std::shared_ptr>`.

I can also plausibly imagine that we'll extend the interface to include a 
"print" function as well at some point.  

However, currently the parser hasn't been upstreamed and the print function is 
only an idea, so it would be reasonable to drop `StencilPartInterface` and all 
the associated baggage and we could reinstate it later as needed.  Or, if you 
can think of a good way to test the parser that doesn't require an equality 
function, that too would be convincing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67969



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


[PATCH] D67961: [libTooling] Introduce the MatchConsumer abstraction

2019-09-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 221733.
ymandel marked 3 inline comments as done.
ymandel added a comment.

addressed comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67961

Files:
  clang/include/clang/Tooling/Refactoring/MatchConsumer.h
  clang/include/clang/Tooling/Refactoring/RangeSelector.h
  clang/include/clang/Tooling/Refactoring/Transformer.h
  clang/lib/Tooling/Refactoring/RangeSelector.cpp

Index: clang/lib/Tooling/Refactoring/RangeSelector.cpp
===
--- clang/lib/Tooling/Refactoring/RangeSelector.cpp
+++ clang/lib/Tooling/Refactoring/RangeSelector.cpp
@@ -310,11 +310,3 @@
 return Result.SourceManager->getExpansionRange(*SRange);
   };
 }
-
-RangeSelector tooling::ifBound(std::string ID, RangeSelector TrueSelector,
-   RangeSelector FalseSelector) {
-  return [=](const MatchResult &Result) {
-auto &Map = Result.Nodes.getMap();
-return (Map.find(ID) != Map.end() ? TrueSelector : FalseSelector)(Result);
-  };
-}
Index: clang/include/clang/Tooling/Refactoring/Transformer.h
===
--- clang/include/clang/Tooling/Refactoring/Transformer.h
+++ clang/include/clang/Tooling/Refactoring/Transformer.h
@@ -19,6 +19,7 @@
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/ASTMatchers/ASTMatchersInternal.h"
 #include "clang/Tooling/Refactoring/AtomicChange.h"
+#include "clang/Tooling/Refactoring/MatchConsumer.h"
 #include "clang/Tooling/Refactoring/RangeSelector.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
@@ -32,11 +33,7 @@
 namespace clang {
 namespace tooling {
 
-// Note that \p TextGenerator is allowed to fail, e.g. when trying to access a
-// matched node that was not bound.  Allowing this to fail simplifies error
-// handling for interactive tools like clang-query.
-using TextGenerator = std::function(
-const ast_matchers::MatchFinder::MatchResult &)>;
+using TextGenerator = MatchConsumer;
 
 /// Wraps a string as a TextGenerator.
 inline TextGenerator text(std::string M) {
Index: clang/include/clang/Tooling/Refactoring/RangeSelector.h
===
--- clang/include/clang/Tooling/Refactoring/RangeSelector.h
+++ clang/include/clang/Tooling/Refactoring/RangeSelector.h
@@ -17,14 +17,14 @@
 
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Tooling/Refactoring/MatchConsumer.h"
 #include "llvm/Support/Error.h"
 #include 
 #include 
 
 namespace clang {
 namespace tooling {
-using RangeSelector = std::function(
-const ast_matchers::MatchFinder::MatchResult &)>;
+using RangeSelector = MatchConsumer;
 
 inline RangeSelector charRange(CharSourceRange R) {
   return [R](const ast_matchers::MatchFinder::MatchResult &)
@@ -87,11 +87,6 @@
 /// source), if `S` is an expansion, and `S` itself, otherwise.  Corresponds to
 /// `SourceManager::getExpansionRange`.
 RangeSelector expansion(RangeSelector S);
-
-/// Chooses between the two selectors, based on whether \p ID is bound in the
-/// match.
-RangeSelector ifBound(std::string ID, RangeSelector TrueSelector,
-  RangeSelector FalseSelector);
 } // namespace tooling
 } // namespace clang
 
Index: clang/include/clang/Tooling/Refactoring/MatchConsumer.h
===
--- /dev/null
+++ clang/include/clang/Tooling/Refactoring/MatchConsumer.h
@@ -0,0 +1,58 @@
+//===--- MatchConsumer.h - MatchConsumer abstraction *- 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
+//
+//===--===//
+///
+/// \file This file defines the *MatchConsumer* abstraction: a computation over
+/// match results, specifically the `ast_matchers::MatchFinder::MatchResult`
+/// class.
+///
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLING_REFACTOR_MATCH_CONSUMER_H_
+#define LLVM_CLANG_TOOLING_REFACTOR_MATCH_CONSUMER_H_
+
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Errc.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+namespace tooling {
+
+/// A failable computation over nodes bound by AST matchers.
+///
+/// The computation should report any errors though its return value (rather
+/// than terminating the program) to enable usage in interactive scenarios like
+/// clang-query.
+///
+/// This is a central abstraction of the Transformer framework.
+template 
+using MatchConsumer =
+std::function(const ast_mat

[PATCH] D67961: [libTooling] Introduce the MatchConsumer abstraction

2019-09-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked an inline comment as done.
ymandel added inline comments.



Comment at: clang/include/clang/Tooling/Refactoring/MatchConsumer.h:27
+
+/// A central abstraction of the Transformer framework is computation over the
+/// results of a match (represented by \c MatchFinder::MatchResult). We

gribozavr wrote:
> The comment seems to be a mix of documentation and design justification. How 
> about this?
> 
> ```
> A failable computation over nodes bound by AST matchers.
> 
> It is a central abstraction of the Transformer framework.
> 
> The computation should report any errors though its return value (rather than 
> terminating the program) to enable usage in interactive scenarios like 
> clang-query.
> ```
Much better, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67961



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


r372863 - [AST] Extract Decl::printNestedNameSpecifier helper from Decl::printQualifiedName

2019-09-25 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Sep 25 06:09:10 2019
New Revision: 372863

URL: http://llvm.org/viewvc/llvm-project?rev=372863&view=rev
Log:
[AST] Extract Decl::printNestedNameSpecifier helper from 
Decl::printQualifiedName

Summary:
To be used in clangd, e.g. in D66647.
Currently the alternative to this function is doing string manipulation on 
results of `printQualifiedName`, which is
hard-to-impossible to get right in presence of template arguments.

Reviewers: kadircet, aaron.ballman

Reviewed By: kadircet, aaron.ballman

Subscribers: aaron.ballman, usaxena95, cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/include/clang/AST/Decl.h
cfe/trunk/lib/AST/Decl.cpp
cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp

Modified: cfe/trunk/include/clang/AST/Decl.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Decl.h?rev=372863&r1=372862&r2=372863&view=diff
==
--- cfe/trunk/include/clang/AST/Decl.h (original)
+++ cfe/trunk/include/clang/AST/Decl.h Wed Sep 25 06:09:10 2019
@@ -310,6 +310,14 @@ public:
   void printQualifiedName(raw_ostream &OS) const;
   void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
 
+  /// Print only the nested name specifier part of a fully-qualified name,
+  /// including the '::' at the end. E.g.
+  ///when `printQualifiedName(D)` prints "A::B::i",
+  ///this function prints "A::B::".
+  void printNestedNameSpecifier(raw_ostream &OS) const;
+  void printNestedNameSpecifier(raw_ostream &OS,
+const PrintingPolicy &Policy) const;
+
   // FIXME: Remove string version.
   std::string getQualifiedNameAsString() const;
 

Modified: cfe/trunk/lib/AST/Decl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=372863&r1=372862&r2=372863&view=diff
==
--- cfe/trunk/lib/AST/Decl.cpp (original)
+++ cfe/trunk/lib/AST/Decl.cpp Wed Sep 25 06:09:10 2019
@@ -1558,6 +1558,19 @@ void NamedDecl::printQualifiedName(raw_o
 
 void NamedDecl::printQualifiedName(raw_ostream &OS,
const PrintingPolicy &P) const {
+  printNestedNameSpecifier(OS, P);
+  if (getDeclName() || isa(this))
+OS << *this;
+  else
+OS << "(anonymous)";
+}
+
+void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
+  printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
+}
+
+void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
+ const PrintingPolicy &P) const {
   const DeclContext *Ctx = getDeclContext();
 
   // For ObjC methods and properties, look through categories and use the
@@ -1571,10 +1584,8 @@ void NamedDecl::printQualifiedName(raw_o
 Ctx = ID;
   }
 
-  if (Ctx->isFunctionOrMethod()) {
-printName(OS);
+  if (Ctx->isFunctionOrMethod())
 return;
-  }
 
   using ContextsTy = SmallVector;
   ContextsTy Contexts;
@@ -1644,11 +1655,6 @@ void NamedDecl::printQualifiedName(raw_o
 }
 OS << "::";
   }
-
-  if (getDeclName() || isa(this))
-OS << *this;
-  else
-OS << "(anonymous)";
 }
 
 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,

Modified: cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp?rev=372863&r1=372862&r2=372863&view=diff
==
--- cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp (original)
+++ cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp Wed Sep 25 06:09:10 2019
@@ -16,9 +16,12 @@
 
//===--===//
 
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/PrettyPrinter.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/Support/raw_ostream.h"
 #include "gtest/gtest.h"
 
 using namespace clang;
@@ -30,11 +33,12 @@ namespace {
 class PrintMatch : public MatchFinder::MatchCallback {
   SmallString<1024> Printed;
   unsigned NumFoundDecls;
-  bool SuppressUnwrittenScope;
+  std::function Printer;
 
 public:
-  explicit PrintMatch(bool suppressUnwrittenScope)
-: NumFoundDecls(0), SuppressUnwrittenScope(suppressUnwrittenScope) {}
+  explicit PrintMatch(
+  std::function Printer)
+  : NumFoundDecls(0), Printer(std::move(Printer)) {}
 
   void run(const MatchFinder::MatchResult &Result) override {
 const NamedDecl *ND = Result.Nodes.getNodeAs("id");
@@ -45,9 +49,7 @@ public:
   return;
 
 llvm::raw_svector_ostream Out(Printed);
-PrintingPolicy Policy = Result.Context->getPrintingPolicy();
-Policy.SuppressUnwrittenScope = SuppressUnwrittenScope;
-ND->printQualifiedName(Out, Policy);
+Printer

[PATCH] D67825: [AST] Extract Decl::printNestedNameSpecifier helper from Decl::printQualifiedName

2019-09-25 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL372863: [AST] Extract Decl::printNestedNameSpecifier helper 
from Decl… (authored by ibiryukov, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D67825?vs=221002&id=221736#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D67825

Files:
  cfe/trunk/include/clang/AST/Decl.h
  cfe/trunk/lib/AST/Decl.cpp
  cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp

Index: cfe/trunk/lib/AST/Decl.cpp
===
--- cfe/trunk/lib/AST/Decl.cpp
+++ cfe/trunk/lib/AST/Decl.cpp
@@ -1558,6 +1558,19 @@
 
 void NamedDecl::printQualifiedName(raw_ostream &OS,
const PrintingPolicy &P) const {
+  printNestedNameSpecifier(OS, P);
+  if (getDeclName() || isa(this))
+OS << *this;
+  else
+OS << "(anonymous)";
+}
+
+void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
+  printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
+}
+
+void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
+ const PrintingPolicy &P) const {
   const DeclContext *Ctx = getDeclContext();
 
   // For ObjC methods and properties, look through categories and use the
@@ -1571,10 +1584,8 @@
 Ctx = ID;
   }
 
-  if (Ctx->isFunctionOrMethod()) {
-printName(OS);
+  if (Ctx->isFunctionOrMethod())
 return;
-  }
 
   using ContextsTy = SmallVector;
   ContextsTy Contexts;
@@ -1644,11 +1655,6 @@
 }
 OS << "::";
   }
-
-  if (getDeclName() || isa(this))
-OS << *this;
-  else
-OS << "(anonymous)";
 }
 
 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
Index: cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp
===
--- cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp
+++ cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp
@@ -16,9 +16,12 @@
 //===--===//
 
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/PrettyPrinter.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/Support/raw_ostream.h"
 #include "gtest/gtest.h"
 
 using namespace clang;
@@ -30,11 +33,12 @@
 class PrintMatch : public MatchFinder::MatchCallback {
   SmallString<1024> Printed;
   unsigned NumFoundDecls;
-  bool SuppressUnwrittenScope;
+  std::function Printer;
 
 public:
-  explicit PrintMatch(bool suppressUnwrittenScope)
-: NumFoundDecls(0), SuppressUnwrittenScope(suppressUnwrittenScope) {}
+  explicit PrintMatch(
+  std::function Printer)
+  : NumFoundDecls(0), Printer(std::move(Printer)) {}
 
   void run(const MatchFinder::MatchResult &Result) override {
 const NamedDecl *ND = Result.Nodes.getNodeAs("id");
@@ -45,9 +49,7 @@
   return;
 
 llvm::raw_svector_ostream Out(Printed);
-PrintingPolicy Policy = Result.Context->getPrintingPolicy();
-Policy.SuppressUnwrittenScope = SuppressUnwrittenScope;
-ND->printQualifiedName(Out, Policy);
+Printer(Out, ND);
   }
 
   StringRef getPrinted() const {
@@ -59,12 +61,12 @@
   }
 };
 
-::testing::AssertionResult
-PrintedNamedDeclMatches(StringRef Code, const std::vector &Args,
-bool SuppressUnwrittenScope,
-const DeclarationMatcher &NodeMatch,
-StringRef ExpectedPrinted, StringRef FileName) {
-  PrintMatch Printer(SuppressUnwrittenScope);
+::testing::AssertionResult PrintedDeclMatches(
+StringRef Code, const std::vector &Args,
+const DeclarationMatcher &NodeMatch, StringRef ExpectedPrinted,
+StringRef FileName,
+std::function Print) {
+  PrintMatch Printer(std::move(Print));
   MatchFinder Finder;
   Finder.addMatcher(NodeMatch, &Printer);
   std::unique_ptr Factory =
@@ -92,6 +94,21 @@
 }
 
 ::testing::AssertionResult
+PrintedNamedDeclMatches(StringRef Code, const std::vector &Args,
+bool SuppressUnwrittenScope,
+const DeclarationMatcher &NodeMatch,
+StringRef ExpectedPrinted, StringRef FileName) {
+  return PrintedDeclMatches(Code, Args, NodeMatch, ExpectedPrinted, FileName,
+[=](llvm::raw_ostream &Out, const NamedDecl *ND) {
+  auto Policy =
+  ND->getASTContext().getPrintingPolicy();
+  Policy.SuppressUnwrittenScope =
+  SuppressUnwrittenScope;
+  ND->printQualifiedName(Out, Policy);
+});
+}
+
+::testing::AssertionResult
 PrintedNamedDeclCXX98Matches(StringRef Code, StringRef 

[PATCH] D64943: [Clang][OpenMP offload] Eliminate use of OpenMP linker script

2019-09-25 Thread Hal Finkel via Phabricator via cfe-commits
hfinkel added a comment.

This LGTM. I'm happy that this is a design improvement over the current scheme. 
@JonChesterfield , @ABataev , any further comments?


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

https://reviews.llvm.org/D64943



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


r372870 - [libTooling] Introduce the MatchConsumer abstraction

2019-09-25 Thread Yitzhak Mandelbaum via cfe-commits
Author: ymandel
Date: Wed Sep 25 06:34:04 2019
New Revision: 372870

URL: http://llvm.org/viewvc/llvm-project?rev=372870&view=rev
Log:
[libTooling] Introduce the MatchConsumer abstraction

Summary:
This revision introduces a separate (small) library for the `MatchConsumer`
abstraction: computations over AST match results.  This abstraction is central
to the Transformer framework, and there deserves being defined explicitly.

Reviewers: gribozavr

Subscribers: cfe-commits

Tags: #clang

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

Added:
cfe/trunk/include/clang/Tooling/Refactoring/MatchConsumer.h
Modified:
cfe/trunk/include/clang/Tooling/Refactoring/RangeSelector.h
cfe/trunk/include/clang/Tooling/Refactoring/Transformer.h
cfe/trunk/lib/Tooling/Refactoring/RangeSelector.cpp

Added: cfe/trunk/include/clang/Tooling/Refactoring/MatchConsumer.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Refactoring/MatchConsumer.h?rev=372870&view=auto
==
--- cfe/trunk/include/clang/Tooling/Refactoring/MatchConsumer.h (added)
+++ cfe/trunk/include/clang/Tooling/Refactoring/MatchConsumer.h Wed Sep 25 
06:34:04 2019
@@ -0,0 +1,58 @@
+//===--- MatchConsumer.h - MatchConsumer abstraction *- 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
+//
+//===--===//
+///
+/// \file This file defines the *MatchConsumer* abstraction: a computation over
+/// match results, specifically the `ast_matchers::MatchFinder::MatchResult`
+/// class.
+///
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLING_REFACTOR_MATCH_CONSUMER_H_
+#define LLVM_CLANG_TOOLING_REFACTOR_MATCH_CONSUMER_H_
+
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Errc.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+namespace tooling {
+
+/// A failable computation over nodes bound by AST matchers.
+///
+/// The computation should report any errors though its return value (rather
+/// than terminating the program) to enable usage in interactive scenarios like
+/// clang-query.
+///
+/// This is a central abstraction of the Transformer framework.
+template 
+using MatchConsumer =
+std::function(const ast_matchers::MatchFinder::MatchResult &)>;
+
+/// Creates an error that signals that a `MatchConsumer` expected a certain 
node
+/// to be bound by AST matchers, but it was not actually bound.
+inline llvm::Error notBoundError(llvm::StringRef Id) {
+  return llvm::make_error(llvm::errc::invalid_argument,
+ "Id not bound: " + Id);
+}
+
+/// Chooses between the two consumers, based on whether \p ID is bound in the
+/// match.
+template 
+MatchConsumer ifBound(std::string ID, MatchConsumer TrueC,
+ MatchConsumer FalseC) {
+  return [=](const ast_matchers::MatchFinder::MatchResult &Result) {
+auto &Map = Result.Nodes.getMap();
+return (Map.find(ID) != Map.end() ? TrueC : FalseC)(Result);
+  };
+}
+
+} // namespace tooling
+} // namespace clang
+#endif // LLVM_CLANG_TOOLING_REFACTOR_MATCH_CONSUMER_H_

Modified: cfe/trunk/include/clang/Tooling/Refactoring/RangeSelector.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Refactoring/RangeSelector.h?rev=372870&r1=372869&r2=372870&view=diff
==
--- cfe/trunk/include/clang/Tooling/Refactoring/RangeSelector.h (original)
+++ cfe/trunk/include/clang/Tooling/Refactoring/RangeSelector.h Wed Sep 25 
06:34:04 2019
@@ -17,14 +17,14 @@
 
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Tooling/Refactoring/MatchConsumer.h"
 #include "llvm/Support/Error.h"
 #include 
 #include 
 
 namespace clang {
 namespace tooling {
-using RangeSelector = std::function(
-const ast_matchers::MatchFinder::MatchResult &)>;
+using RangeSelector = MatchConsumer;
 
 inline RangeSelector charRange(CharSourceRange R) {
   return [R](const ast_matchers::MatchFinder::MatchResult &)
@@ -87,11 +87,6 @@ RangeSelector elseBranch(std::string ID)
 /// source), if `S` is an expansion, and `S` itself, otherwise.  Corresponds to
 /// `SourceManager::getExpansionRange`.
 RangeSelector expansion(RangeSelector S);
-
-/// Chooses between the two selectors, based on whether \p ID is bound in the
-/// match.
-RangeSelector ifBound(std::string ID, RangeSelector TrueSelector,
-  RangeSelector FalseSelector);
 } // namespace tooling
 } // namespace clang
 

Modified: cfe/trunk/include/clang/Tooling/Refac

[PATCH] D67961: [libTooling] Introduce the MatchConsumer abstraction

2019-09-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL372870: [libTooling] Introduce the MatchConsumer abstraction 
(authored by ymandel, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D67961?vs=221733&id=221746#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D67961

Files:
  cfe/trunk/include/clang/Tooling/Refactoring/MatchConsumer.h
  cfe/trunk/include/clang/Tooling/Refactoring/RangeSelector.h
  cfe/trunk/include/clang/Tooling/Refactoring/Transformer.h
  cfe/trunk/lib/Tooling/Refactoring/RangeSelector.cpp

Index: cfe/trunk/lib/Tooling/Refactoring/RangeSelector.cpp
===
--- cfe/trunk/lib/Tooling/Refactoring/RangeSelector.cpp
+++ cfe/trunk/lib/Tooling/Refactoring/RangeSelector.cpp
@@ -310,11 +310,3 @@
 return Result.SourceManager->getExpansionRange(*SRange);
   };
 }
-
-RangeSelector tooling::ifBound(std::string ID, RangeSelector TrueSelector,
-   RangeSelector FalseSelector) {
-  return [=](const MatchResult &Result) {
-auto &Map = Result.Nodes.getMap();
-return (Map.find(ID) != Map.end() ? TrueSelector : FalseSelector)(Result);
-  };
-}
Index: cfe/trunk/include/clang/Tooling/Refactoring/Transformer.h
===
--- cfe/trunk/include/clang/Tooling/Refactoring/Transformer.h
+++ cfe/trunk/include/clang/Tooling/Refactoring/Transformer.h
@@ -19,6 +19,7 @@
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/ASTMatchers/ASTMatchersInternal.h"
 #include "clang/Tooling/Refactoring/AtomicChange.h"
+#include "clang/Tooling/Refactoring/MatchConsumer.h"
 #include "clang/Tooling/Refactoring/RangeSelector.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
@@ -32,11 +33,7 @@
 namespace clang {
 namespace tooling {
 
-// Note that \p TextGenerator is allowed to fail, e.g. when trying to access a
-// matched node that was not bound.  Allowing this to fail simplifies error
-// handling for interactive tools like clang-query.
-using TextGenerator = std::function(
-const ast_matchers::MatchFinder::MatchResult &)>;
+using TextGenerator = MatchConsumer;
 
 /// Wraps a string as a TextGenerator.
 inline TextGenerator text(std::string M) {
Index: cfe/trunk/include/clang/Tooling/Refactoring/RangeSelector.h
===
--- cfe/trunk/include/clang/Tooling/Refactoring/RangeSelector.h
+++ cfe/trunk/include/clang/Tooling/Refactoring/RangeSelector.h
@@ -17,14 +17,14 @@
 
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Tooling/Refactoring/MatchConsumer.h"
 #include "llvm/Support/Error.h"
 #include 
 #include 
 
 namespace clang {
 namespace tooling {
-using RangeSelector = std::function(
-const ast_matchers::MatchFinder::MatchResult &)>;
+using RangeSelector = MatchConsumer;
 
 inline RangeSelector charRange(CharSourceRange R) {
   return [R](const ast_matchers::MatchFinder::MatchResult &)
@@ -87,11 +87,6 @@
 /// source), if `S` is an expansion, and `S` itself, otherwise.  Corresponds to
 /// `SourceManager::getExpansionRange`.
 RangeSelector expansion(RangeSelector S);
-
-/// Chooses between the two selectors, based on whether \p ID is bound in the
-/// match.
-RangeSelector ifBound(std::string ID, RangeSelector TrueSelector,
-  RangeSelector FalseSelector);
 } // namespace tooling
 } // namespace clang
 
Index: cfe/trunk/include/clang/Tooling/Refactoring/MatchConsumer.h
===
--- cfe/trunk/include/clang/Tooling/Refactoring/MatchConsumer.h
+++ cfe/trunk/include/clang/Tooling/Refactoring/MatchConsumer.h
@@ -0,0 +1,58 @@
+//===--- MatchConsumer.h - MatchConsumer abstraction *- 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
+//
+//===--===//
+///
+/// \file This file defines the *MatchConsumer* abstraction: a computation over
+/// match results, specifically the `ast_matchers::MatchFinder::MatchResult`
+/// class.
+///
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLING_REFACTOR_MATCH_CONSUMER_H_
+#define LLVM_CLANG_TOOLING_REFACTOR_MATCH_CONSUMER_H_
+
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Errc.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+namespace tooling {
+
+/// A failable computation over nodes bound by AST matchers.
+///
+/// T

[PATCH] D64943: [Clang][OpenMP offload] Eliminate use of OpenMP linker script

2019-09-25 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

In D64943#1682452 , @hfinkel wrote:

> This LGTM. I'm happy that this is a design improvement over the current 
> scheme. @JonChesterfield , @ABataev , any further comments?


This patch mixes two concerns. 
1/ Remove the linker script
2/ Change generation of offload registration code

These should be separate patches. I think the linker script removal would then 
be uncontentious.

It'll be easier to consider the offload registration changes without the linker 
script changes. That's a more complicated design space. In particular, this 
change is motivated by supporting additional platforms, and I don't see how 
offload registration is related to that.


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

https://reviews.llvm.org/D64943



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


[PATCH] D64943: [Clang][OpenMP offload] Eliminate use of OpenMP linker script

2019-09-25 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/Driver/Driver.cpp:3125
+ActionList DeviceAL;
+for (auto *SB : SpecializedBuilders) {
+  if (!SB->isValid())

User real type instead of `auto *`



Comment at: clang/lib/Driver/Driver.cpp:3434
   if (!LinkerInputs.empty()) {
+if (auto *Wrapper = OffloadBuilder.makeHostLinkAction())
+  LinkerInputs.push_back(Wrapper);

`auto *`->real type



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6478
+
+  const auto &Triple = getToolChain().getEffectiveTriple();
+

`auto`->real type



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6490
+  // Add inputs.
+  for (const auto &I : Inputs) {
+assert(I.isFilename() && "Invalid input.");

`auto`->real type



Comment at: clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp:72
+private:
+  IntegerType *getSizeTTy() {
+switch (M.getDataLayout().getPointerTypeSize(Type::getInt8PtrTy(C))) {

Maybe better to get the size of `size_t` type from command line option rather 
than rely on some non-stable assumptions?



Comment at: clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp:203
+ImagesInits.reserve(Bufs.size());
+for (const ArrayRef &Buf : Bufs) {
+  auto *Data = ConstantDataArray::get(C, Buf);

Just `ArrayRef`, no need to make it `const ArrayRef &`


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

https://reviews.llvm.org/D64943



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


[PATCH] D68020: [clangd] Fix parseNamespaceEvents to parse the last token

2019-09-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added reviewers: hokein, ilya-biryukov.
Herald added subscribers: cfe-commits, usaxena95, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68020

Files:
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/unittests/SourceCodeTests.cpp


Index: clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
===
--- clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
+++ clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
@@ -423,6 +423,12 @@
   )cpp",
   {"bar", ""},
   },
+  {
+  R"cpp(
+// Parse until EOF
+namespace bar{})cpp",
+  {""},
+  },
   {
   R"cpp(
 // Namespaces with multiple chunks.
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -659,6 +659,9 @@
 
   while (!Lex.LexFromRawLexer(Tok))
 A(Tok);
+  // LexFromRawLexer returns true after it lexes last token, so we still have
+  // one more token to report.
+  A(Tok);
 }
 
 llvm::StringMap collectIdentifiers(llvm::StringRef Content,


Index: clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
===
--- clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
+++ clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
@@ -423,6 +423,12 @@
   )cpp",
   {"bar", ""},
   },
+  {
+  R"cpp(
+// Parse until EOF
+namespace bar{})cpp",
+  {""},
+  },
   {
   R"cpp(
 // Namespaces with multiple chunks.
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -659,6 +659,9 @@
 
   while (!Lex.LexFromRawLexer(Tok))
 A(Tok);
+  // LexFromRawLexer returns true after it lexes last token, so we still have
+  // one more token to report.
+  A(Tok);
 }
 
 llvm::StringMap collectIdentifiers(llvm::StringRef Content,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D63082: [Diagnostics] Added support for -Wint-in-bool-context

2019-09-25 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

Happy to hear :)


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

https://reviews.llvm.org/D63082



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


[PATCH] D68020: [clangd] Fix parseNamespaceEvents to parse the last token

2019-09-25 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/unittests/SourceCodeTests.cpp:429
+// Parse until EOF
+namespace bar{})cpp",
+  {""},

could you also add an "empty string" test case?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68020



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


[PATCH] D68021: [IntrinsicEmitter] Add overloaded type VecOfBitcastsToInt for SVE intrinsics

2019-09-25 Thread Kerry McLaughlin via Phabricator via cfe-commits
kmclaughlin created this revision.
kmclaughlin added reviewers: c-rhodes, sdesmalen, rovka.
Herald added subscribers: jdoerfert, hiraditya, tschuett.
Herald added a project: LLVM.

This allows intrinsics such as the following to be defined:

- declare  @llvm.something.nxv4f32(, , )

...where  is derived from , but
the element needs bitcasting to int.


https://reviews.llvm.org/D68021

Files:
  llvm/include/llvm/IR/Intrinsics.h
  llvm/include/llvm/IR/Intrinsics.td
  llvm/lib/IR/Function.cpp
  llvm/utils/TableGen/IntrinsicEmitter.cpp

Index: llvm/utils/TableGen/IntrinsicEmitter.cpp
===
--- llvm/utils/TableGen/IntrinsicEmitter.cpp
+++ llvm/utils/TableGen/IntrinsicEmitter.cpp
@@ -223,7 +223,8 @@
   IIT_VEC_ELEMENT = 42,
   IIT_SCALABLE_VEC = 43,
   IIT_SUBDIVIDE2_ARG = 44,
-  IIT_SUBDIVIDE4_ARG = 45
+  IIT_SUBDIVIDE4_ARG = 45,
+  IIT_VEC_OF_BITCASTS_TO_INT = 46
 };
 
 static void EncodeFixedValueType(MVT::SimpleValueType VT,
@@ -299,6 +300,8 @@
   Sig.push_back(IIT_SUBDIVIDE2_ARG);
 else if (R->isSubClassOf("LLVMSubdivide4VectorType"))
   Sig.push_back(IIT_SUBDIVIDE4_ARG);
+else if (R->isSubClassOf("LLVMVectorOfBitcastsToInt"))
+  Sig.push_back(IIT_VEC_OF_BITCASTS_TO_INT);
 else
   Sig.push_back(IIT_ARG);
 return Sig.push_back((Number << 3) | 7 /*IITDescriptor::AK_MatchType*/);
Index: llvm/lib/IR/Function.cpp
===
--- llvm/lib/IR/Function.cpp
+++ llvm/lib/IR/Function.cpp
@@ -706,7 +706,8 @@
   IIT_VEC_ELEMENT = 42,
   IIT_SCALABLE_VEC = 43,
   IIT_SUBDIVIDE2_ARG = 44,
-  IIT_SUBDIVIDE4_ARG = 45
+  IIT_SUBDIVIDE4_ARG = 45,
+  IIT_VEC_OF_BITCASTS_TO_INT = 46
 };
 
 static void DecodeIITType(unsigned &NextElt, ArrayRef Infos,
@@ -895,6 +896,12 @@
 DecodeIITType(NextElt, Infos, OutputTable);
 return;
   }
+  case IIT_VEC_OF_BITCASTS_TO_INT: {
+unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
+OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt,
+ ArgInfo));
+return;
+  }
   }
   llvm_unreachable("unhandled");
 }
@@ -1021,6 +1028,12 @@
   return VTy->getElementType();
 llvm_unreachable("Expected an argument of Vector Type");
   }
+  case IITDescriptor::VecOfBitcastsToInt: {
+Type *Ty = Tys[D.getArgumentNumber()];
+VectorType *VTy = dyn_cast(Ty);
+assert(VTy && "Expected an argument of Vector Type");
+return VectorType::getInteger(VTy);
+  }
   case IITDescriptor::VecOfAnyPtrsToElt:
 // Return the overloaded type (which determines the pointers address space)
 return Tys[D.getOverloadArgNumber()];
@@ -1313,6 +1326,15 @@
   return matchIntrinsicType(VTy, Infos, ArgTys, DeferredChecks,
 IsDeferredCheck);
 }
+case IITDescriptor::VecOfBitcastsToInt: {
+  if (D.getArgumentNumber() >= ArgTys.size())
+return IsDeferredCheck || DeferCheck(Ty);
+  auto *ReferenceType = dyn_cast(ArgTys[D.getArgumentNumber()]);
+  auto *ThisArgVecTy = dyn_cast(Ty);
+  if (!ThisArgVecTy || !ReferenceType)
+return true;
+  return ThisArgVecTy != VectorType::getInteger(ReferenceType);
+}
   }
   llvm_unreachable("unhandled");
 }
Index: llvm/include/llvm/IR/Intrinsics.td
===
--- llvm/include/llvm/IR/Intrinsics.td
+++ llvm/include/llvm/IR/Intrinsics.td
@@ -193,6 +193,10 @@
 class LLVMSubdivide2VectorType : LLVMMatchType;
 class LLVMSubdivide4VectorType : LLVMMatchType;
 
+// Match the element count and bit width of another intrinsic parameter, but
+// change the element type to an integer.
+class LLVMVectorOfBitcastsToInt : LLVMMatchType;
+
 def llvm_void_ty   : LLVMType;
 let isAny = 1 in {
   def llvm_any_ty: LLVMType;
Index: llvm/include/llvm/IR/Intrinsics.h
===
--- llvm/include/llvm/IR/Intrinsics.h
+++ llvm/include/llvm/IR/Intrinsics.h
@@ -101,7 +101,7 @@
   Argument, ExtendArgument, TruncArgument, HalfVecArgument,
   SameVecWidthArgument, PtrToArgument, PtrToElt, VecOfAnyPtrsToElt,
   VecElementArgument, ScalableVecArgument, Subdivide2Argument,
-  Subdivide4Argument
+  Subdivide4Argument, VecOfBitcastsToInt
 } Kind;
 
 union {
@@ -127,7 +127,8 @@
  Kind == TruncArgument || Kind == HalfVecArgument ||
  Kind == SameVecWidthArgument || Kind == PtrToArgument ||
  Kind == PtrToElt || Kind == VecElementArgument ||
- Kind == Subdivide2Argument || Kind == Subdivide4Argument);
+ Kind == Subdivide2Argument || Kind == Subdivide4Argument ||
+ Kind == VecOfBitcastsToInt);
   return Argument_Info >> 3;
 }
 ArgKind getArgumentKind() const {
@@ -135,7 +136,7 @@
  Kind == TruncArgument || Kind == HalfVecArgument ||

[PATCH] D68020: [clangd] Fix parseNamespaceEvents to parse the last token

2019-09-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 221759.
kadircet added a comment.

- Add empty string testcase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68020

Files:
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/unittests/SourceCodeTests.cpp


Index: clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
===
--- clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
+++ clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
@@ -441,6 +441,16 @@
   "c::d",
   },
   },
+  {
+  "",
+  {""},
+  },
+  {
+  R"cpp(
+// Parse until EOF
+namespace bar{})cpp",
+  {""},
+  },
   };
   for (const auto& Case : Cases) {
 EXPECT_EQ(Case.second,
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -659,6 +659,9 @@
 
   while (!Lex.LexFromRawLexer(Tok))
 A(Tok);
+  // LexFromRawLexer returns true after it lexes last token, so we still have
+  // one more token to report.
+  A(Tok);
 }
 
 llvm::StringMap collectIdentifiers(llvm::StringRef Content,


Index: clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
===
--- clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
+++ clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
@@ -441,6 +441,16 @@
   "c::d",
   },
   },
+  {
+  "",
+  {""},
+  },
+  {
+  R"cpp(
+// Parse until EOF
+namespace bar{})cpp",
+  {""},
+  },
   };
   for (const auto& Case : Cases) {
 EXPECT_EQ(Case.second,
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -659,6 +659,9 @@
 
   while (!Lex.LexFromRawLexer(Tok))
 A(Tok);
+  // LexFromRawLexer returns true after it lexes last token, so we still have
+  // one more token to report.
+  A(Tok);
 }
 
 llvm::StringMap collectIdentifiers(llvm::StringRef Content,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r372875 - [clangd] Fix parseNamespaceEvents to parse the last token

2019-09-25 Thread Kadir Cetinkaya via cfe-commits
Author: kadircet
Date: Wed Sep 25 07:12:05 2019
New Revision: 372875

URL: http://llvm.org/viewvc/llvm-project?rev=372875&view=rev
Log:
[clangd] Fix parseNamespaceEvents to parse the last token

Reviewers: hokein, ilya-biryukov

Subscribers: MaskRay, jkorous, arphaman, usaxena95, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/SourceCode.cpp
clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp

Modified: clang-tools-extra/trunk/clangd/SourceCode.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/SourceCode.cpp?rev=372875&r1=372874&r2=372875&view=diff
==
--- clang-tools-extra/trunk/clangd/SourceCode.cpp (original)
+++ clang-tools-extra/trunk/clangd/SourceCode.cpp Wed Sep 25 07:12:05 2019
@@ -659,6 +659,9 @@ static void lex(llvm::StringRef Code, co
 
   while (!Lex.LexFromRawLexer(Tok))
 A(Tok);
+  // LexFromRawLexer returns true after it lexes last token, so we still have
+  // one more token to report.
+  A(Tok);
 }
 
 llvm::StringMap collectIdentifiers(llvm::StringRef Content,

Modified: clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp?rev=372875&r1=372874&r2=372875&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp (original)
+++ clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp Wed Sep 25 
07:12:05 2019
@@ -441,6 +441,16 @@ TEST(SourceCodeTests, VisibleNamespaces)
   "c::d",
   },
   },
+  {
+  "",
+  {""},
+  },
+  {
+  R"cpp(
+// Parse until EOF
+namespace bar{})cpp",
+  {""},
+  },
   };
   for (const auto& Case : Cases) {
 EXPECT_EQ(Case.second,


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


[PATCH] D68020: [clangd] Fix parseNamespaceEvents to parse the last token

2019-09-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL372875: [clangd] Fix parseNamespaceEvents to parse the last 
token (authored by kadircet, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D68020?vs=221759&id=221760#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D68020

Files:
  clang-tools-extra/trunk/clangd/SourceCode.cpp
  clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp


Index: clang-tools-extra/trunk/clangd/SourceCode.cpp
===
--- clang-tools-extra/trunk/clangd/SourceCode.cpp
+++ clang-tools-extra/trunk/clangd/SourceCode.cpp
@@ -659,6 +659,9 @@
 
   while (!Lex.LexFromRawLexer(Tok))
 A(Tok);
+  // LexFromRawLexer returns true after it lexes last token, so we still have
+  // one more token to report.
+  A(Tok);
 }
 
 llvm::StringMap collectIdentifiers(llvm::StringRef Content,
Index: clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp
===
--- clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp
+++ clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp
@@ -441,6 +441,16 @@
   "c::d",
   },
   },
+  {
+  "",
+  {""},
+  },
+  {
+  R"cpp(
+// Parse until EOF
+namespace bar{})cpp",
+  {""},
+  },
   };
   for (const auto& Case : Cases) {
 EXPECT_EQ(Case.second,


Index: clang-tools-extra/trunk/clangd/SourceCode.cpp
===
--- clang-tools-extra/trunk/clangd/SourceCode.cpp
+++ clang-tools-extra/trunk/clangd/SourceCode.cpp
@@ -659,6 +659,9 @@
 
   while (!Lex.LexFromRawLexer(Tok))
 A(Tok);
+  // LexFromRawLexer returns true after it lexes last token, so we still have
+  // one more token to report.
+  A(Tok);
 }
 
 llvm::StringMap collectIdentifiers(llvm::StringRef Content,
Index: clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp
===
--- clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp
+++ clang-tools-extra/trunk/clangd/unittests/SourceCodeTests.cpp
@@ -441,6 +441,16 @@
   "c::d",
   },
   },
+  {
+  "",
+  {""},
+  },
+  {
+  R"cpp(
+// Parse until EOF
+namespace bar{})cpp",
+  {""},
+  },
   };
   for (const auto& Case : Cases) {
 EXPECT_EQ(Case.second,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68023: [AArch64][SVE] Implement int_aarch64_sve_cnt intrinsic

2019-09-25 Thread Kerry McLaughlin via Phabricator via cfe-commits
kmclaughlin created this revision.
kmclaughlin added reviewers: c-rhodes, sdesmalen, rovka.
Herald added subscribers: psnobl, rkruppe, hiraditya, kristof.beyls, tschuett.
Herald added a project: LLVM.
kmclaughlin added a parent revision: D68021: [IntrinsicEmitter] Add overloaded 
type VecOfBitcastsToInt for SVE intrinsics.

This patch includes tests for the VecOfBitcastsToInt type added by D68021 



https://reviews.llvm.org/D68023

Files:
  llvm/include/llvm/IR/IntrinsicsAArch64.td
  llvm/lib/Target/AArch64/AArch64SVEInstrInfo.td
  llvm/lib/Target/AArch64/SVEInstrFormats.td
  llvm/test/CodeGen/AArch64/sve-intrinsics-counting-bits.ll

Index: llvm/test/CodeGen/AArch64/sve-intrinsics-counting-bits.ll
===
--- /dev/null
+++ llvm/test/CodeGen/AArch64/sve-intrinsics-counting-bits.ll
@@ -0,0 +1,83 @@
+; RUN: llc -mtriple=aarch64-linux-gnu -mattr=+sve < %s | FileCheck %s
+
+;
+; CNT
+;
+
+define  @cnt_i8( %a,  %pg,  %b) {
+; CHECK-LABEL: cnt_i8:
+; CHECK: cnt z0.b, p0/m, z1.b
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.cnt.nxv16i8( %a,
+%pg,
+%b)
+  ret  %out
+}
+
+define  @cnt_i16( %a,  %pg,  %b) {
+; CHECK-LABEL: cnt_i16:
+; CHECK: cnt z0.h, p0/m, z1.h
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.cnt.nxv8i16( %a,
+%pg,
+%b)
+  ret  %out
+}
+
+define  @cnt_i32( %a,  %pg,  %b) {
+; CHECK-LABEL: cnt_i32:
+; CHECK: cnt z0.s, p0/m, z1.s
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.cnt.nxv4i32( %a,
+%pg,
+%b)
+  ret  %out
+}
+
+define  @cnt_i64( %a,  %pg,  %b) {
+; CHECK-LABEL: cnt_i64:
+; CHECK: cnt z0.d, p0/m, z1.d
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.cnt.nxv2i64( %a,
+%pg,
+%b)
+  ret  %out
+}
+
+define  @cnt_f16( %a,  %pg,  %b) {
+; CHECK-LABEL: cnt_f16:
+; CHECK: cnt z0.h, p0/m, z1.h
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.cnt.nxv8f16( %a,
+%pg,
+%b)
+  ret  %out
+}
+
+define  @cnt_f32( %a,  %pg,  %b) {
+; CHECK-LABEL: cnt_f32:
+; CHECK: cnt z0.s, p0/m, z1.s
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.cnt.nxv4f32( %a,
+%pg,
+%b)
+  ret  %out
+}
+
+define  @cnt_f64( %a,  %pg,  %b) {
+; CHECK-LABEL: cnt_f64:
+; CHECK: cnt z0.d, p0/m, z1.d
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.cnt.nxv2f64( %a,
+%pg,
+%b)
+  ret  %out
+}
+
+declare  @llvm.aarch64.sve.cnt.nxv16i8(, , )
+declare  @llvm.aarch64.sve.cnt.nxv8i16(, , )
+declare  @llvm.aarch64.sve.cnt.nxv4i32(, , )
+declare  @llvm.aarch64.sve.cnt.nxv2i64(, , )
+declare  @llvm.aarch64.sve.cnt.nxv8f16(, , )
+declare  @llvm.aarch64.sve.cnt.nxv4f32(, , )
+declare  @llvm.aarch64.sve.cnt.nxv2f64(, , )
Index: llvm/lib/Target/AArch64/SVEInstrFormats.td
===
--- llvm/lib/Target/AArch64/SVEInstrFormats.td
+++ llvm/lib/Target/AArch64/SVEInstrFormats.td
@@ -2871,11 +2871,21 @@
   def _D : sve_int_un_pred_arit<0b11, { opc, 0b0 }, asm, ZPR64>;
 }
 
-multiclass sve_int_un_pred_arit_1 opc, string asm> {
+multiclass sve_int_un_pred_arit_1 opc, string asm,
+  SDPatternOperator op> {
   def _B : sve_int_un_pred_arit<0b00, { opc, 0b1 }, asm, ZPR8>;
   def _H : sve_int_un_pred_arit<0b01, { opc, 0b1 }, asm, ZPR16>;
   def _S : sve_int_un_pred_arit<0b10, { opc, 0b1 }, asm, ZPR32>;
   def _D : sve_int_un_pred_arit<0b11, { opc, 0b1 }, asm, ZPR64>;
+
+  def : SVE_3_Op_Pat(NAME # _B)>;
+  def : SVE_3_Op_Pat(NAME # _H)>;
+  def : SVE_3_Op_Pat(NAME # _S)>;
+  def : SVE_3_Op_Pat(NAME # _D)>;
+
+  def : SVE_3_Op_Pat(NAME # _H)>;
+  def : SVE_3_Op_Pat(NAME # _S)>;
+  def : SVE_3_Op_Pat(NAME # _D)>;
 }
 
 multiclass sve_int_un_pred_arit_1_fp opc, string asm> {
Index: llvm/lib/Target/AArch64/AArch64SVEInstrInfo.td
===
--- llvm/lib/Target/AArch64/AArch64SVEInstrInfo.td
+++ llvm/lib/Target/AArch64/AArch64SVEInstrInfo.td
@@ -97,11 +97,11 @@
   defm ABS_ZPmZ  : sve_int_un_pred_arit_0<  0b110, "abs", int_aarch64_sve_abs>;
   defm NEG_ZPmZ  : sve_int_un_pred_arit_0<  0b111, "neg", int_aarch64_sve_neg>;
 
- 

Re: r372863 - [AST] Extract Decl::printNestedNameSpecifier helper from Decl::printQualifiedName

2019-09-25 Thread Nico Weber via cfe-commits
Is it possible that this broke Tooling/clang-diff-ast.cpp
http://lab.llvm.org:8011/builders/clang-cmake-x86_64-avx2-linux/builds/11395/steps/ninja%20check%201/logs/FAIL%3A%20Clang%3A%3Aclang-diff-ast.cpp
?

On Wed, Sep 25, 2019 at 9:07 AM Ilya Biryukov via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: ibiryukov
> Date: Wed Sep 25 06:09:10 2019
> New Revision: 372863
>
> URL: http://llvm.org/viewvc/llvm-project?rev=372863&view=rev
> Log:
> [AST] Extract Decl::printNestedNameSpecifier helper from
> Decl::printQualifiedName
>
> Summary:
> To be used in clangd, e.g. in D66647.
> Currently the alternative to this function is doing string manipulation on
> results of `printQualifiedName`, which is
> hard-to-impossible to get right in presence of template arguments.
>
> Reviewers: kadircet, aaron.ballman
>
> Reviewed By: kadircet, aaron.ballman
>
> Subscribers: aaron.ballman, usaxena95, cfe-commits
>
> Tags: #clang
>
> Differential Revision: https://reviews.llvm.org/D67825
>
> Modified:
> cfe/trunk/include/clang/AST/Decl.h
> cfe/trunk/lib/AST/Decl.cpp
> cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp
>
> Modified: cfe/trunk/include/clang/AST/Decl.h
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Decl.h?rev=372863&r1=372862&r2=372863&view=diff
>
> ==
> --- cfe/trunk/include/clang/AST/Decl.h (original)
> +++ cfe/trunk/include/clang/AST/Decl.h Wed Sep 25 06:09:10 2019
> @@ -310,6 +310,14 @@ public:
>void printQualifiedName(raw_ostream &OS) const;
>void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy)
> const;
>
> +  /// Print only the nested name specifier part of a fully-qualified name,
> +  /// including the '::' at the end. E.g.
> +  ///when `printQualifiedName(D)` prints "A::B::i",
> +  ///this function prints "A::B::".
> +  void printNestedNameSpecifier(raw_ostream &OS) const;
> +  void printNestedNameSpecifier(raw_ostream &OS,
> +const PrintingPolicy &Policy) const;
> +
>// FIXME: Remove string version.
>std::string getQualifiedNameAsString() const;
>
>
> Modified: cfe/trunk/lib/AST/Decl.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=372863&r1=372862&r2=372863&view=diff
>
> ==
> --- cfe/trunk/lib/AST/Decl.cpp (original)
> +++ cfe/trunk/lib/AST/Decl.cpp Wed Sep 25 06:09:10 2019
> @@ -1558,6 +1558,19 @@ void NamedDecl::printQualifiedName(raw_o
>
>  void NamedDecl::printQualifiedName(raw_ostream &OS,
> const PrintingPolicy &P) const {
> +  printNestedNameSpecifier(OS, P);
> +  if (getDeclName() || isa(this))
> +OS << *this;
> +  else
> +OS << "(anonymous)";
> +}
> +
> +void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
> +  printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
> +}
> +
> +void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
> + const PrintingPolicy &P) const {
>const DeclContext *Ctx = getDeclContext();
>
>// For ObjC methods and properties, look through categories and use the
> @@ -1571,10 +1584,8 @@ void NamedDecl::printQualifiedName(raw_o
>  Ctx = ID;
>}
>
> -  if (Ctx->isFunctionOrMethod()) {
> -printName(OS);
> +  if (Ctx->isFunctionOrMethod())
>  return;
> -  }
>
>using ContextsTy = SmallVector;
>ContextsTy Contexts;
> @@ -1644,11 +1655,6 @@ void NamedDecl::printQualifiedName(raw_o
>  }
>  OS << "::";
>}
> -
> -  if (getDeclName() || isa(this))
> -OS << *this;
> -  else
> -OS << "(anonymous)";
>  }
>
>  void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
>
> Modified: cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp?rev=372863&r1=372862&r2=372863&view=diff
>
> ==
> --- cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp (original)
> +++ cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp Wed Sep 25 06:09:10
> 2019
> @@ -16,9 +16,12 @@
>
>  
> //===--===//
>
>  #include "clang/AST/ASTContext.h"
> +#include "clang/AST/Decl.h"
> +#include "clang/AST/PrettyPrinter.h"
>  #include "clang/ASTMatchers/ASTMatchFinder.h"
>  #include "clang/Tooling/Tooling.h"
>  #include "llvm/ADT/SmallString.h"
> +#include "llvm/Support/raw_ostream.h"
>  #include "gtest/gtest.h"
>
>  using namespace clang;
> @@ -30,11 +33,12 @@ namespace {
>  class PrintMatch : public MatchFinder::MatchCallback {
>SmallString<1024> Printed;
>unsigned NumFoundDecls;
> -  bool SuppressUnwrittenScope;
> +  std::function Printer;
>
>  public:
> -  explicit PrintMatch(bool suppressUnwrittenScope)
> -: NumFoundDecls(0), Supp

[PATCH] D68024: [clangd] Implement GetEligibleRegions

2019-09-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added reviewers: hokein, ilya-biryukov.
Herald added subscribers: cfe-commits, usaxena95, arphaman, jkorous, MaskRay.
Herald added a project: clang.

This is an helper for incoming move definition out-of-line action to
figure out possible insertion locations for definition of a qualified name.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68024

Files:
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/unittests/SourceCodeTests.cpp

Index: clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
===
--- clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
+++ clang-tools-extra/clangd/unittests/SourceCodeTests.cpp
@@ -19,6 +19,7 @@
 #include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 
 namespace clang {
 namespace clangd {
@@ -603,6 +604,66 @@
 Test.llvm::Annotations::point("bar"));
 }
 
+TEST(SourceCodeTests, GetEligibleRegion) {
+  constexpr std::tuple
+  Cases[] = {
+  {R"cpp(// FIXME: We should also mark positions before and after
+ //declarations/definitions as eligible.
+  namespace ns1 {
+  namespace a { namespace ns2 {} }
+  namespace ns2 {^
+  void foo();
+  namespace {}
+  void bar() {}
+  namespace ns3 {}
+  class T {};
+  ^}
+  using namespace ns2;
+  })cpp",
+   "ns1::ns2::symbol", "ns1::ns2::"},
+  {R"cpp(
+  namespace ns1 {^
+  namespace a { namespace ns2 {} }
+  namespace b {}
+  namespace ns {}
+  ^})cpp",
+   "ns1::ns2::symbol", "ns1::"},
+  {R"cpp(
+  namespace x {
+  namespace a { namespace ns2 {} }
+  namespace b {}
+  namespace ns {}
+  })cpp",
+   "ns1::ns2::symbol", ""},
+  {R"cpp(
+  namespace ns1 {
+  namespace ns2 {^^}
+  namespace b {}
+  namespace ns2 {^^}
+  }
+  namespace ns1 {namespace ns2 {^^}})cpp",
+   "ns1::ns2::symbol", "ns1::ns2::"},
+  {R"cpp(
+  namespace ns1 {^
+  namespace ns {}
+  namespace b {}
+  namespace ns {}
+  ^}
+  namespace ns1 {^namespace ns {}^})cpp",
+   "ns1::ns2::symbol", "ns1::"},
+  };
+  for (auto Case : Cases) {
+Annotations Test(std::get<0>(Case));
+
+auto Res = getEligibleRegion(Test.code(), std::get<1>(Case),
+ format::getLLVMStyle());
+EXPECT_THAT(Res.EligiblePoints, testing::ElementsAreArray(Test.points()))
+<< Test.code();
+EXPECT_EQ(Res.CurrentNamespace, std::get<2>(Case)) << Test.code();
+  }
+}
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/SourceCode.h
===
--- clang-tools-extra/clangd/SourceCode.h
+++ clang-tools-extra/clangd/SourceCode.h
@@ -262,6 +262,25 @@
 std::vector visibleNamespaces(llvm::StringRef Code,
const format::FormatStyle &Style);
 
+// Represents locations that can accept a definition.
+struct EligibleRegion {
+  /// Namespace that owns all of the EligiblePoints, e.g.
+  /// namespace a{ namespace b { ^ void foo();^} }
+  /// It will be “a::b” for both carrot locations.
+  std::string CurrentNamespace;
+  /// Offsets into the code marking eligible points to insert a function
+  /// definition.
+  std::vector EligiblePoints;
+};
+
+/// Returns most eligible region to insert a definition for FullyQualifiedName
+/// in the Code. Pseudo parses Code under the hood to determine namespace decls
+/// and possible insertion points. Choses the region that matches the longest
+/// prefix of FullyQualifiedName.
+EligibleRegion getEligibleRegion(llvm::StringRef Code,
+ llvm::StringRef FullyQualifiedName,
+ const format::FormatStyle &Style);
+
 struct DefinedMacro {
   llvm::StringRef Name;
   const MacroInfo *Info;
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -20,9 +20,11 @@
 #include "clang/Format/Format.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/Token.h"
 #include "clang/Tooling/Core/Replacement.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/None.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
@@ -37,6 +39,9 @@
 #include "llvm/Su

[PATCH] D68026: [clangd] Add missing header guard, NFC.

2019-09-25 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: gribozavr.
Herald added subscribers: usaxena95, kadircet, arphaman, jkorous, MaskRay, 
ilya-biryukov.
Herald added a project: clang.

[clang-tidy] Make llvm-header-guard work on llvm git monorepo.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68026

Files:
  clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp
  clang-tools-extra/clangd/FindTarget.h
  clang-tools-extra/clangd/HeaderSourceSwitch.h
  clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp


Index: clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
@@ -211,6 +211,15 @@
  "#endif  /* LLVM_ADT_FOO_H\\ \n"
  " FOO */",
  "include/llvm/ADT/foo.h", None));
+
+  EXPECT_EQ("#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_FOO_H\n"
+"#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_FOO_H\n"
+"\n"
+"\n"
+"#endif\n",
+runHeaderGuardCheck(
+"", "/llvm-project/clang-tools-extra/clangd/foo.h",
+StringRef("header is missing header guard")));
 }
 #endif
 
Index: clang-tools-extra/clangd/HeaderSourceSwitch.h
===
--- clang-tools-extra/clangd/HeaderSourceSwitch.h
+++ clang-tools-extra/clangd/HeaderSourceSwitch.h
@@ -6,6 +6,9 @@
 //
 
//===--===//
 
+#ifndef LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_HEADERSOURCESWITCH_H
+#define LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_HEADERSOURCESWITCH_H
+
 #include "ParsedAST.h"
 #include "llvm/ADT/Optional.h"
 
@@ -20,3 +23,5 @@
 
 } // namespace clangd
 } // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_HEADERSOURCESWITCH_H
Index: clang-tools-extra/clangd/FindTarget.h
===
--- clang-tools-extra/clangd/FindTarget.h
+++ clang-tools-extra/clangd/FindTarget.h
@@ -19,6 +19,9 @@
 //
 
//===--===//
 
+#ifndef LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_FINDTARGET_H
+#define LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_FINDTARGET_H
+
 #include "clang/AST/ASTTypeTraits.h"
 #include "clang/AST/NestedNameSpecifier.h"
 #include "clang/AST/Stmt.h"
@@ -176,3 +179,5 @@
 
 } // namespace clangd
 } // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_FINDTARGET_H
Index: clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp
===
--- clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp
+++ clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp
@@ -33,6 +33,13 @@
   if (PosToolsClang != StringRef::npos)
 Guard = Guard.substr(PosToolsClang + std::strlen("tools/"));
 
+  // Unlike LLVM svn, LLVM git monorepo is named llvm-project, so we replace
+  // "/llvm-project/" with the cannonical "/llvm/".
+  const static StringRef LLVMProject = "/llvm-project/";
+  size_t PosLLVMProject = Guard.rfind(LLVMProject);
+  if (PosLLVMProject != StringRef::npos)
+Guard = Guard.replace(PosLLVMProject, LLVMProject.size(), "/llvm/");
+
   // The remainder is LLVM_FULL_PATH_TO_HEADER_H
   size_t PosLLVM = Guard.rfind("llvm/");
   if (PosLLVM != StringRef::npos)


Index: clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
@@ -211,6 +211,15 @@
  "#endif  /* LLVM_ADT_FOO_H\\ \n"
  " FOO */",
  "include/llvm/ADT/foo.h", None));
+
+  EXPECT_EQ("#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_FOO_H\n"
+"#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_FOO_H\n"
+"\n"
+"\n"
+"#endif\n",
+runHeaderGuardCheck(
+"", "/llvm-project/clang-tools-extra/clangd/foo.h",
+StringRef("header is missing header guard")));
 }
 #endif
 
Index: clang-tools-extra/clangd/HeaderSourceSwitch.h
===
--- clang-tools-extra/clangd/HeaderSourceSwitch.h
+++ clang-tools-extra/clangd/HeaderSourceSwitch.h
@@ -6,6 +6,9 @@
 //
 //===--===//
 
+#ifndef LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_HEADERSOURCESWITCH_H
+#define LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_HEADERSOURCESWITCH_H
+
 #include "ParsedAST.h"
 #include "llvm/ADT/Optional.h"
 
@@ -20,3 +23,5 @@
 
 } // namespace 

[PATCH] D68026: [clangd] Add missing header guard, NFC.

2019-09-25 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 221765.
hokein added a comment.

upload correct diff.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68026

Files:
  clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp
  clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp


Index: clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
@@ -211,6 +211,15 @@
  "#endif  /* LLVM_ADT_FOO_H\\ \n"
  " FOO */",
  "include/llvm/ADT/foo.h", None));
+
+  EXPECT_EQ("#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_FOO_H\n"
+"#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_FOO_H\n"
+"\n"
+"\n"
+"#endif\n",
+runHeaderGuardCheck(
+"", "/llvm-project/clang-tools-extra/clangd/foo.h",
+StringRef("header is missing header guard")));
 }
 #endif
 
Index: clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp
===
--- clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp
+++ clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp
@@ -33,6 +33,13 @@
   if (PosToolsClang != StringRef::npos)
 Guard = Guard.substr(PosToolsClang + std::strlen("tools/"));
 
+  // Unlike LLVM svn, LLVM git monorepo is named llvm-project, so we replace
+  // "/llvm-project/" with the cannonical "/llvm/".
+  const static StringRef LLVMProject = "/llvm-project/";
+  size_t PosLLVMProject = Guard.rfind(LLVMProject);
+  if (PosLLVMProject != StringRef::npos)
+Guard = Guard.replace(PosLLVMProject, LLVMProject.size(), "/llvm/");
+
   // The remainder is LLVM_FULL_PATH_TO_HEADER_H
   size_t PosLLVM = Guard.rfind("llvm/");
   if (PosLLVM != StringRef::npos)


Index: clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp
@@ -211,6 +211,15 @@
  "#endif  /* LLVM_ADT_FOO_H\\ \n"
  " FOO */",
  "include/llvm/ADT/foo.h", None));
+
+  EXPECT_EQ("#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_FOO_H\n"
+"#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_FOO_H\n"
+"\n"
+"\n"
+"#endif\n",
+runHeaderGuardCheck(
+"", "/llvm-project/clang-tools-extra/clangd/foo.h",
+StringRef("header is missing header guard")));
 }
 #endif
 
Index: clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp
===
--- clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp
+++ clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp
@@ -33,6 +33,13 @@
   if (PosToolsClang != StringRef::npos)
 Guard = Guard.substr(PosToolsClang + std::strlen("tools/"));
 
+  // Unlike LLVM svn, LLVM git monorepo is named llvm-project, so we replace
+  // "/llvm-project/" with the cannonical "/llvm/".
+  const static StringRef LLVMProject = "/llvm-project/";
+  size_t PosLLVMProject = Guard.rfind(LLVMProject);
+  if (PosLLVMProject != StringRef::npos)
+Guard = Guard.replace(PosLLVMProject, LLVMProject.size(), "/llvm/");
+
   // The remainder is LLVM_FULL_PATH_TO_HEADER_H
   size_t PosLLVM = Guard.rfind("llvm/");
   if (PosLLVM != StringRef::npos)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68027: [clangd] Change constness of parameters to findExplicitRefs

2019-09-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: ilya-biryukov.
Herald added subscribers: cfe-commits, usaxena95, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Recursive AST requires non-const ast nodes, but it doesn't really
mutate them. In addition to that, in clangd we mostly have const ast nodes. So
it makes sense to move the const_cast into callee rather than having it at every
caller in the future.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68027

Files:
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/FindTarget.h


Index: clang-tools-extra/clangd/FindTarget.h
===
--- clang-tools-extra/clangd/FindTarget.h
+++ clang-tools-extra/clangd/FindTarget.h
@@ -101,9 +101,9 @@
 /// qualifiers.
 /// FIXME: currently this does not report references to overloaded operators.
 /// FIXME: extend to report location information about declaration names too.
-void findExplicitReferences(Stmt *S,
+void findExplicitReferences(const Stmt *S,
 llvm::function_ref Out);
-void findExplicitReferences(Decl *D,
+void findExplicitReferences(const Decl *D,
 llvm::function_ref Out);
 
 /// Similar to targetDecl(), however instead of applying a filter, all possible
Index: clang-tools-extra/clangd/FindTarget.cpp
===
--- clang-tools-extra/clangd/FindTarget.cpp
+++ clang-tools-extra/clangd/FindTarget.cpp
@@ -616,15 +616,15 @@
 };
 } // namespace
 
-void findExplicitReferences(Stmt *S,
+void findExplicitReferences(const Stmt *S,
 llvm::function_ref Out) {
   assert(S);
-  ExplicitReferenceColletor(Out).TraverseStmt(S);
+  ExplicitReferenceColletor(Out).TraverseStmt(const_cast(S));
 }
-void findExplicitReferences(Decl *D,
+void findExplicitReferences(const Decl *D,
 llvm::function_ref Out) {
   assert(D);
-  ExplicitReferenceColletor(Out).TraverseDecl(D);
+  ExplicitReferenceColletor(Out).TraverseDecl(const_cast(D));
 }
 
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {


Index: clang-tools-extra/clangd/FindTarget.h
===
--- clang-tools-extra/clangd/FindTarget.h
+++ clang-tools-extra/clangd/FindTarget.h
@@ -101,9 +101,9 @@
 /// qualifiers.
 /// FIXME: currently this does not report references to overloaded operators.
 /// FIXME: extend to report location information about declaration names too.
-void findExplicitReferences(Stmt *S,
+void findExplicitReferences(const Stmt *S,
 llvm::function_ref Out);
-void findExplicitReferences(Decl *D,
+void findExplicitReferences(const Decl *D,
 llvm::function_ref Out);
 
 /// Similar to targetDecl(), however instead of applying a filter, all possible
Index: clang-tools-extra/clangd/FindTarget.cpp
===
--- clang-tools-extra/clangd/FindTarget.cpp
+++ clang-tools-extra/clangd/FindTarget.cpp
@@ -616,15 +616,15 @@
 };
 } // namespace
 
-void findExplicitReferences(Stmt *S,
+void findExplicitReferences(const Stmt *S,
 llvm::function_ref Out) {
   assert(S);
-  ExplicitReferenceColletor(Out).TraverseStmt(S);
+  ExplicitReferenceColletor(Out).TraverseStmt(const_cast(S));
 }
-void findExplicitReferences(Decl *D,
+void findExplicitReferences(const Decl *D,
 llvm::function_ref Out) {
   assert(D);
-  ExplicitReferenceColletor(Out).TraverseDecl(D);
+  ExplicitReferenceColletor(Out).TraverseDecl(const_cast(D));
 }
 
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68028: [clang] Add no_builtin attribute

2019-09-25 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet created this revision.
gchatelet added reviewers: tejohnson, courbet, theraven, t.p.northover, 
jdoerfert.
Herald added subscribers: cfe-commits, mgrang.
Herald added a project: clang.

This is a follow up on https://reviews.llvm.org/D61634
This patch is simpler and only adds the no_builtin attribute.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68028

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/no-builtin.c
  clang/test/Misc/pragma-attribute-supported-attributes-list.test

Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -74,6 +74,7 @@
 // CHECK-NEXT: NSConsumed (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: NSConsumesSelf (SubjectMatchRule_objc_method)
 // CHECK-NEXT: Naked (SubjectMatchRule_function)
+// CHECK-NEXT: NoBuiltin (SubjectMatchRule_function)
 // CHECK-NEXT: NoCommon (SubjectMatchRule_variable)
 // CHECK-NEXT: NoDebug (SubjectMatchRule_type_alias, SubjectMatchRule_hasType_functionType, SubjectMatchRule_objc_method, SubjectMatchRule_variable_not_is_parameter)
 // CHECK-NEXT: NoDestroy (SubjectMatchRule_variable)
Index: clang/test/CodeGen/no-builtin.c
===
--- /dev/null
+++ clang/test/CodeGen/no-builtin.c
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -S -emit-llvm -o - %s | FileCheck %s
+
+// CHECK-LABEL: define void @foo_no_mempcy() #0
+void foo_no_mempcy() __attribute__((no_builtin("memcpy"))) {}
+
+// CHECK-LABEL: define void @foo_no_builtins() #1
+void foo_no_builtins() __attribute__((no_builtin)) {}
+
+// CHECK-LABEL: define void @foo_no_mempcy_memset() #2
+void foo_no_mempcy_memset() __attribute__((no_builtin("memset", "memcpy"))) {}
+
+// CHECK-LABEL: define void @separate_attrs() #2
+void separate_attrs() __attribute__((no_builtin("memset"))) __attribute__((no_builtin("memcpy"))) {}
+
+// CHECK-LABEL: define void @wildcard_wins() #1
+void wildcard_wins() __attribute__((no_builtin("memset"))) __attribute__((no_builtin)) __attribute__((no_builtin("memcpy"))) {}
+
+// CHECK: attributes #0 = {{{.*}}"no-builtin-memcpy"{{.*}}}
+// CHECK: attributes #1 = {{{.*}}"no-builtins"{{.*}}}
+// CHECK: attributes #2 = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -1068,6 +1068,42 @@
   S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast(D)));
 }
 
+static void handleNoBuiltin(Sema &S, Decl *D, const ParsedAttr &AL) {
+  const StringRef Wildcard = "*";
+  llvm::SmallSetVector FunctionNames;
+
+  // Insert previous NoBuiltin attributes.
+  if (D->hasAttr())
+for (StringRef FunctionName : D->getAttr()->functionNames())
+  FunctionNames.insert(FunctionName);
+
+  if (AL.getNumArgs() == 0)
+FunctionNames.insert(Wildcard);
+  else
+for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
+  StringRef FunctionName;
+  SourceLocation LiteralLoc;
+  if (!S.checkStringLiteralArgumentAttr(AL, I, FunctionName, &LiteralLoc))
+return;
+  FunctionNames.insert(FunctionName);
+}
+
+  // Wildcard is a super set of all builtins, we keep only this one.
+  if (FunctionNames.count(Wildcard) > 0) {
+FunctionNames.clear();
+FunctionNames.insert(Wildcard);
+  }
+
+  auto UniqueFunctionNames = FunctionNames.takeVector();
+  llvm::sort(UniqueFunctionNames);
+
+  if (D->hasAttr())
+D->dropAttr();
+
+  D->addAttr(::new (S.Context) NoBuiltinAttr(
+  S.Context, AL, UniqueFunctionNames.data(), UniqueFunctionNames.size()));
+}
+
 static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
   if (D->hasAttr()) {
 S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
@@ -6573,6 +6609,9 @@
   case ParsedAttr::AT_DiagnoseIf:
 handleDiagnoseIfAttr(S, D, AL);
 break;
+  case ParsedAttr::AT_NoBuiltin:
+handleNoBuiltin(S, D, AL);
+break;
   case ParsedAttr::AT_ExtVectorType:
 handleExtVectorTypeAttr(S, D, AL);
 break;
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -1849,6 +1849,22 @@
   FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
 if (TargetDecl->hasAttr())
   FuncAttrs.addAttribute(llvm::Attribute::Convergent);
+if (const auto *Attr = TargetDecl->getAttr()) {
+  const auto HasWildcard = llvm::is_contained(Attr->functionNames(), "*");
+  assert(!HasWildcard ||
+ Attr->functionN

[PATCH] D67978: [OpenMP 5.0] Fix user-defined mapper lookup in sema for arrays

2019-09-25 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

Definitely need positive tests with ast printing and codegen.




Comment at: lib/Sema/SemaOpenMP.cpp:14751
+assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
+Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
+  }

Why do you want canonical type here? I think it is wrong. It drops all language 
sugar like typedefs etc. But typedefs are not supported in mappers, right?


Repository:
  rC Clang

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

https://reviews.llvm.org/D67978



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


[PATCH] D61634: [clang/llvm] Allow efficient implementation of libc's memory functions in C/C++

2019-09-25 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet added a comment.

In D61634#1679331 , @tejohnson wrote:

> In D61634#1635595 , @tejohnson wrote:
>
> > I had some time to work on this finally late last week. I decided the most 
> > straightforward thing was to implement the necessary interface changes to 
> > the TLI analysis to make it require a Function (without any changes yet to 
> > how that analysis operates). See D66428  
> > that I just mailed for review. That takes care of the most widespread 
> > changes needed for this migration, and afterwards we can change the 
> > analysis to look at the function attributes and make a truly per-function 
> > TLI.
>
>
> D66428  went in a few weeks ago at r371284, 
> and I just mailed the follow on patch D67923 
>  which will adds the support into the TLI 
> analysis to use the Function to override the available builtins (with some of 
> the code stubbed out since we don't yet have those per-Function attributes 
> finalized).
>
> @gchatelet where are you at on finalizing this patch? Also, I mentioned this 
> offline but to follow up here: I think we will want an attribute to represent 
> -fno-builtins (so that it doesn't need to be expanded out into the full list 
> of individual no-builtin-{func} attributes, which would be both more verbose 
> and less efficient, as well as being less backward compatible when new 
> builtin funcs are added).


I'll break this patch in several pieces. The first one is to add the 
`no_builtin` attribute, see https://reviews.llvm.org/D61634.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61634



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


[PATCH] D67969: [libTooling] Add `run` combinator to Stencils.

2019-09-25 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr accepted this revision.
gribozavr added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/include/clang/Tooling/Refactoring/Stencil.h:181
+/// This supports user-defined extensions to the Stencil language.
+StencilPart run(MatchConsumer C);
+

ymandel wrote:
> gribozavr wrote:
> > We could reimplement all other stencils through `run()` and eliminate 
> > `StencilPartInterface`. 
> > 
> > The idea is to make `StencilPart` contain a 
> > `std::shared_ptr>`. Then `run()` can be 
> > implemented as creating a `StencilPart` directly, and everything else can 
> > be implemented in terms of `run()`.
> > 
> > WDYT?
> Answering both questions together: the equality function is designed to make 
> testing of the format-string parser feasible (or, at least, reasonable).  As 
> is, the only reason not to do what you suggest above is exactly the equality 
> function -- otherwise, StencilPart is just 
> `std::shared_ptr>`.
> 
> I can also plausibly imagine that we'll extend the interface to include a 
> "print" function as well at some point.  
> 
> However, currently the parser hasn't been upstreamed and the print function 
> is only an idea, so it would be reasonable to drop `StencilPartInterface` and 
> all the associated baggage and we could reinstate it later as needed.  Or, if 
> you can think of a good way to test the parser that doesn't require an 
> equality function, that too would be convincing.
Ilya suggested that rather than comparing objects, a better way is to compare 
pretty-printed strings. First, it avoids the need for equality (which might get 
used for other things), and second, test failures will be more debuggable 
because we will have an obvious diff in the pretty printed string.

With that, I agree that `StencilPartInterface` has to stay since we are going 
to have at least two operations.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67969



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


r372880 - Revert r372863: [AST] Extract Decl::printNestedNameSpecifier helper from Decl::printQualifiedName

2019-09-25 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Sep 25 07:50:12 2019
New Revision: 372880

URL: http://llvm.org/viewvc/llvm-project?rev=372880&view=rev
Log:
Revert r372863: [AST] Extract Decl::printNestedNameSpecifier helper from 
Decl::printQualifiedName

Reason: causes a test failure, will investigate and re-land with a fix.

Modified:
cfe/trunk/include/clang/AST/Decl.h
cfe/trunk/lib/AST/Decl.cpp
cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp

Modified: cfe/trunk/include/clang/AST/Decl.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Decl.h?rev=372880&r1=372879&r2=372880&view=diff
==
--- cfe/trunk/include/clang/AST/Decl.h (original)
+++ cfe/trunk/include/clang/AST/Decl.h Wed Sep 25 07:50:12 2019
@@ -310,14 +310,6 @@ public:
   void printQualifiedName(raw_ostream &OS) const;
   void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
 
-  /// Print only the nested name specifier part of a fully-qualified name,
-  /// including the '::' at the end. E.g.
-  ///when `printQualifiedName(D)` prints "A::B::i",
-  ///this function prints "A::B::".
-  void printNestedNameSpecifier(raw_ostream &OS) const;
-  void printNestedNameSpecifier(raw_ostream &OS,
-const PrintingPolicy &Policy) const;
-
   // FIXME: Remove string version.
   std::string getQualifiedNameAsString() const;
 

Modified: cfe/trunk/lib/AST/Decl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=372880&r1=372879&r2=372880&view=diff
==
--- cfe/trunk/lib/AST/Decl.cpp (original)
+++ cfe/trunk/lib/AST/Decl.cpp Wed Sep 25 07:50:12 2019
@@ -1558,19 +1558,6 @@ void NamedDecl::printQualifiedName(raw_o
 
 void NamedDecl::printQualifiedName(raw_ostream &OS,
const PrintingPolicy &P) const {
-  printNestedNameSpecifier(OS, P);
-  if (getDeclName() || isa(this))
-OS << *this;
-  else
-OS << "(anonymous)";
-}
-
-void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
-  printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
-}
-
-void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
- const PrintingPolicy &P) const {
   const DeclContext *Ctx = getDeclContext();
 
   // For ObjC methods and properties, look through categories and use the
@@ -1584,8 +1571,10 @@ void NamedDecl::printNestedNameSpecifier
 Ctx = ID;
   }
 
-  if (Ctx->isFunctionOrMethod())
+  if (Ctx->isFunctionOrMethod()) {
+printName(OS);
 return;
+  }
 
   using ContextsTy = SmallVector;
   ContextsTy Contexts;
@@ -1655,6 +1644,11 @@ void NamedDecl::printNestedNameSpecifier
 }
 OS << "::";
   }
+
+  if (getDeclName() || isa(this))
+OS << *this;
+  else
+OS << "(anonymous)";
 }
 
 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,

Modified: cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp?rev=372880&r1=372879&r2=372880&view=diff
==
--- cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp (original)
+++ cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp Wed Sep 25 07:50:12 2019
@@ -16,12 +16,9 @@
 
//===--===//
 
 #include "clang/AST/ASTContext.h"
-#include "clang/AST/Decl.h"
-#include "clang/AST/PrettyPrinter.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/Support/raw_ostream.h"
 #include "gtest/gtest.h"
 
 using namespace clang;
@@ -33,12 +30,11 @@ namespace {
 class PrintMatch : public MatchFinder::MatchCallback {
   SmallString<1024> Printed;
   unsigned NumFoundDecls;
-  std::function Printer;
+  bool SuppressUnwrittenScope;
 
 public:
-  explicit PrintMatch(
-  std::function Printer)
-  : NumFoundDecls(0), Printer(std::move(Printer)) {}
+  explicit PrintMatch(bool suppressUnwrittenScope)
+: NumFoundDecls(0), SuppressUnwrittenScope(suppressUnwrittenScope) {}
 
   void run(const MatchFinder::MatchResult &Result) override {
 const NamedDecl *ND = Result.Nodes.getNodeAs("id");
@@ -49,7 +45,9 @@ public:
   return;
 
 llvm::raw_svector_ostream Out(Printed);
-Printer(Out, ND);
+PrintingPolicy Policy = Result.Context->getPrintingPolicy();
+Policy.SuppressUnwrittenScope = SuppressUnwrittenScope;
+ND->printQualifiedName(Out, Policy);
   }
 
   StringRef getPrinted() const {
@@ -61,12 +59,12 @@ public:
   }
 };
 
-::testing::AssertionResult PrintedDeclMatches(
-StringRef Code, const std::vector &Args,
-const DeclarationMatcher &NodeMatch, StringRef ExpectedPrinted,
-StringRef FileName,
-std::function Print) {
-  PrintMatch Printer(std::move(P

[PATCH] D67748: [clangd] Add a helper for extracting nonlocal decls in a FunctionDecl

2019-09-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 221772.
kadircet added a comment.

- Use Decl overload of findExplicitReferences


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67748

Files:
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/XRefs.h
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -10,6 +10,7 @@
 #include "Matchers.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
+#include "SourceCode.h"
 #include "SyncAPI.h"
 #include "TestFS.h"
 #include "TestIndex.h"
@@ -18,13 +19,19 @@
 #include "index/FileIndex.h"
 #include "index/MemIndex.h"
 #include "index/SymbolCollector.h"
+#include "clang/AST/Decl.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Index/IndexingAction.h"
 #include "llvm/ADT/None.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -2187,6 +2194,84 @@
   }
 }
 
+TEST(GetNonLocalDeclRefs, All) {
+  struct Case {
+llvm::StringRef AnnotatedCode;
+std::vector ExpectedDecls;
+  } Cases[] = {
+  {
+  // VarDecl and ParamVarDecl
+  R"cpp(
+void bar();
+void ^foo(int baz) {
+  int x = 10;
+  bar();
+})cpp",
+  {"bar"},
+  },
+  {
+  // Method from class
+  R"cpp(
+class Foo { public: void foo(); };
+class Bar {
+  void foo();
+  void bar();
+};
+void Bar::^foo() {
+  Foo f;
+  bar();
+  f.foo();
+})cpp",
+  {"Bar", "Bar::bar", "Foo", "Foo::foo"},
+  },
+  {
+  // Local types
+  R"cpp(
+void ^foo() {
+  class Foo { public: void foo() {} };
+  class Bar { public: void bar() {} };
+  Foo f;
+  Bar b;
+  b.bar();
+  f.foo();
+})cpp",
+  {},
+  },
+  {
+  // Template params
+  R"cpp(
+template  class Q>
+void ^foo() {
+  T x;
+  Q y;
+})cpp",
+  {},
+  },
+  };
+  for (const Case &C : Cases) {
+Annotations File(C.AnnotatedCode);
+auto AST = TestTU::withCode(File.code()).build();
+ASSERT_TRUE(AST.getDiagnostics().empty())
+<< AST.getDiagnostics().begin()->Message;
+SourceLocation SL = llvm::cantFail(
+sourceLocationInMainFile(AST.getSourceManager(), File.point()));
+
+const FunctionDecl *FD =
+llvm::dyn_cast(&findDecl(AST, [SL](const NamedDecl &ND) {
+  return ND.getLocation() == SL && llvm::isa(ND);
+}));
+ASSERT_NE(FD, nullptr);
+
+auto NonLocalDeclRefs = getNonLocalDeclRefs(AST, FD);
+std::vector Names;
+for (const Decl *D : NonLocalDeclRefs) {
+  if (const auto *ND = llvm::dyn_cast(D))
+Names.push_back(ND->getQualifiedNameAsString());
+}
+EXPECT_THAT(Names, UnorderedElementsAreArray(C.ExpectedDecls));
+  }
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/XRefs.h
===
--- clang-tools-extra/clangd/XRefs.h
+++ clang-tools-extra/clangd/XRefs.h
@@ -17,8 +17,8 @@
 #include "Path.h"
 #include "Protocol.h"
 #include "index/Index.h"
-#include "clang/AST/Type.h"
 #include "index/SymbolLocation.h"
+#include "clang/AST/Type.h"
 #include "clang/Format/Format.h"
 #include "clang/Index/IndexSymbol.h"
 #include "llvm/ADT/Optional.h"
@@ -158,6 +158,9 @@
 /// SourceLocationBeg must point to the first character of the token
 bool hasDeducedType(ParsedAST &AST, SourceLocation SourceLocationBeg);
 
+/// Returns all decls that are referenced in the \p FD except local symbols.
+llvm::DenseSet getNonLocalDeclRefs(ParsedAST &AST,
+ const FunctionDecl *FD);
 } // namespace clangd
 } // namespace clang
 
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -9,6 +9,7 @@
 #include "AST.h"
 #include "CodeCompletionStrings.h"
 #include "FindSymbols.h"
+#include "FindTarget.h"
 #include "FormattedString.h"
 #include "Logger.h"
 #include "ParsedAST.h"
@@ -1299,5 +1300,18 @@
   return OS;
 }
 
+llvm::DenseSet getNonLocalDeclRefs(ParsedAST &AST,
+ const Fun

r372884 - [NFC] Fix typo in `getPreviousDecl` comment.

2019-09-25 Thread Yitzhak Mandelbaum via cfe-commits
Author: ymandel
Date: Wed Sep 25 07:58:39 2019
New Revision: 372884

URL: http://llvm.org/viewvc/llvm-project?rev=372884&view=rev
Log:
[NFC] Fix typo in `getPreviousDecl` comment.

Modified:
cfe/trunk/include/clang/AST/DeclBase.h

Modified: cfe/trunk/include/clang/AST/DeclBase.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DeclBase.h?rev=372884&r1=372883&r2=372884&view=diff
==
--- cfe/trunk/include/clang/AST/DeclBase.h (original)
+++ cfe/trunk/include/clang/AST/DeclBase.h Wed Sep 25 07:58:39 2019
@@ -959,7 +959,7 @@ public:
   /// as this declaration, or NULL if there is no previous declaration.
   Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
 
-  /// Retrieve the most recent declaration that declares the same entity
+  /// Retrieve the previous declaration that declares the same entity
   /// as this declaration, or NULL if there is no previous declaration.
   const Decl *getPreviousDecl() const {
 return const_cast(this)->getPreviousDeclImpl();


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


[PATCH] D68029: [ThinLTO] Enable index-only WPD from clang

2019-09-25 Thread Teresa Johnson via Phabricator via cfe-commits
tejohnson created this revision.
tejohnson added a reviewer: pcc.
Herald added subscribers: arphaman, dexonsmith, steven_wu, inglorion, 
mehdi_amini.
Herald added a project: clang.

To trigger the index-only Whole Program Devirt support added to LLVM, we
need to be able to specify -fno-split-lto-unit in conjunction with
-fwhole-program-vtables. Keep the default for -fwhole-program-vtables as
-fsplit-lto-unit, but don't error on that option combination.


Repository:
  rC Clang

https://reviews.llvm.org/D68029

Files:
  lib/Driver/ToolChains/Clang.cpp
  test/Driver/split-lto-unit.c


Index: test/Driver/split-lto-unit.c
===
--- test/Driver/split-lto-unit.c
+++ test/Driver/split-lto-unit.c
@@ -6,5 +6,5 @@
 
 // UNIT: "-fsplit-lto-unit"
 // NOUNIT-NOT: "-fsplit-lto-unit"
-// ERROR1: error: invalid argument '-fno-split-lto-unit' not allowed with 
'-fwhole-program-vtables'
+// ERROR1-NOT: error: invalid argument
 // ERROR2: error: invalid argument '-fno-split-lto-unit' not allowed with 
'-fsanitize=cfi'
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -5446,14 +5446,13 @@
 CmdArgs.push_back("-fwhole-program-vtables");
   }
 
-  bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
+  bool DefaultsSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
   bool SplitLTOUnit =
   Args.hasFlag(options::OPT_fsplit_lto_unit,
-   options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
-  if (RequiresSplitLTOUnit && !SplitLTOUnit)
-D.Diag(diag::err_drv_argument_not_allowed_with)
-<< "-fno-split-lto-unit"
-<< (WholeProgramVTables ? "-fwhole-program-vtables" : 
"-fsanitize=cfi");
+   options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
+  if (Sanitize.needsLTO() && !SplitLTOUnit)
+D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
+<< "-fsanitize=cfi";
   if (SplitLTOUnit)
 CmdArgs.push_back("-fsplit-lto-unit");
 


Index: test/Driver/split-lto-unit.c
===
--- test/Driver/split-lto-unit.c
+++ test/Driver/split-lto-unit.c
@@ -6,5 +6,5 @@
 
 // UNIT: "-fsplit-lto-unit"
 // NOUNIT-NOT: "-fsplit-lto-unit"
-// ERROR1: error: invalid argument '-fno-split-lto-unit' not allowed with '-fwhole-program-vtables'
+// ERROR1-NOT: error: invalid argument
 // ERROR2: error: invalid argument '-fno-split-lto-unit' not allowed with '-fsanitize=cfi'
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -5446,14 +5446,13 @@
 CmdArgs.push_back("-fwhole-program-vtables");
   }
 
-  bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
+  bool DefaultsSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
   bool SplitLTOUnit =
   Args.hasFlag(options::OPT_fsplit_lto_unit,
-   options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
-  if (RequiresSplitLTOUnit && !SplitLTOUnit)
-D.Diag(diag::err_drv_argument_not_allowed_with)
-<< "-fno-split-lto-unit"
-<< (WholeProgramVTables ? "-fwhole-program-vtables" : "-fsanitize=cfi");
+   options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
+  if (Sanitize.needsLTO() && !SplitLTOUnit)
+D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
+<< "-fsanitize=cfi";
   if (SplitLTOUnit)
 CmdArgs.push_back("-fsplit-lto-unit");
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68027: [clangd] Change constness of parameters to findExplicitRefs

2019-09-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Who are the callers? Selection tree?
FWIW, I'd rather pass non-const everywhere, the concept of const-ness is just 
not very useful for AST nodes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68027



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


[PATCH] D68030: [CUDA][HIP] Initial kernel return type relaxing.

2019-09-25 Thread Michael Liao via Phabricator via cfe-commits
hliao created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.
hliao abandoned this revision.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68030

Files:
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp


Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3093,6 +3093,13 @@
   Function->getTypeSpecStartLoc(), Function->getDeclName());
 if (ResultType.isNull() || Trap.hasErrorOccurred())
   return TDK_SubstitutionFailure;
+// CUDA: Kernel function must have 'void' return type.
+if (getLangOpts().CUDA)
+  if (Function->hasAttr() && !ResultType->isVoidType()) {
+Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
+<< Function->getType() << Function->getSourceRange();
+return TDK_SubstitutionFailure;
+  }
   }
 
   // Instantiate the types of each of the function parameters given the
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -3500,6 +3500,14 @@
   return true;
   }
 
+  // CUDA: Kernel function must have 'void' return type.
+  if (getLangOpts().CUDA)
+if (FD->hasAttr() && !Deduced->isVoidType()) {
+  Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
+  << FD->getType() << FD->getSourceRange();
+  return true;
+}
+
   //  If a function with a declared return type that contains a placeholder 
type
   //  has multiple return statements, the return type is deduced for each 
return
   //  statement. [...] if the type deduced is not the same in each deduction,
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -5891,7 +5891,9 @@
 << FDecl << Fn->getSourceRange());
 
   // CUDA: Kernel function must have 'void' return type
-  if (!FuncT->getReturnType()->isVoidType())
+  if (!FuncT->getReturnType()->isVoidType() &&
+  !FuncT->getReturnType()->getAs() &&
+  !FuncT->getReturnType()->isInstantiationDependentType())
 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
 << Fn->getType() << Fn->getSourceRange());
 } else {
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -4223,7 +4223,9 @@
 return;
   }
   const auto *FD = cast(D);
-  if (!FD->getReturnType()->isVoidType()) {
+  if (!FD->getReturnType()->isVoidType() &&
+  !FD->getReturnType()->getAs() &&
+  !FD->getReturnType()->isInstantiationDependentType()) {
 SourceRange RTRange = FD->getReturnTypeSourceRange();
 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
 << FD->getType()


Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3093,6 +3093,13 @@
   Function->getTypeSpecStartLoc(), Function->getDeclName());
 if (ResultType.isNull() || Trap.hasErrorOccurred())
   return TDK_SubstitutionFailure;
+// CUDA: Kernel function must have 'void' return type.
+if (getLangOpts().CUDA)
+  if (Function->hasAttr() && !ResultType->isVoidType()) {
+Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
+<< Function->getType() << Function->getSourceRange();
+return TDK_SubstitutionFailure;
+  }
   }
 
   // Instantiate the types of each of the function parameters given the
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -3500,6 +3500,14 @@
   return true;
   }
 
+  // CUDA: Kernel function must have 'void' return type.
+  if (getLangOpts().CUDA)
+if (FD->hasAttr() && !Deduced->isVoidType()) {
+  Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
+  << FD->getType() << FD->getSourceRange();
+  return true;
+}
+
   //  If a function with a declared return type that contains a placeholder type
   //  has multiple return statements, the return type is deduced for each return
   //  statement. [...] if the type deduced is not the same in each deduction,
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -5891,7 +5891,9 @@
 << FDecl << Fn->getSource

[PATCH] D68028: [clang] Add no_builtin attribute

2019-09-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a reviewer: aaron.ballman.
aaron.ballman added a comment.

Thank you for working on this!

It looks like you're missing all of the sema tests that check that the 
attribute only appertains to functions, accepts the proper kind of arguments, 
etc.




Comment at: clang/include/clang/Basic/Attr.td:3349
+  let Spellings = [Clang<"no_builtin">];
+  let Args = [VariadicStringArgument<"FunctionNames">];
+  let Subjects = SubjectList<[Function]>;

The documentation should explain what this is.



Comment at: clang/lib/CodeGen/CGCall.cpp:1853
+if (const auto *Attr = TargetDecl->getAttr()) {
+  const auto HasWildcard = llvm::is_contained(Attr->functionNames(), "*");
+  assert(!HasWildcard ||

`const auto` -> `bool` (and drop the top-level `const`).



Comment at: clang/lib/CodeGen/CGCall.cpp:1859
+  else
+for (const auto &FunctionName : Attr->functionNames()) {
+  SmallString<32> AttributeName;

`const auto &` -> `StringRef`?



Comment at: clang/lib/CodeGen/CGCall.cpp:1861-1862
+  SmallString<32> AttributeName;
+  // TODO: check that function names are valid for the
+  // TargetLibraryInfo.
+  AttributeName += "no-builtin-";

I think this checking should happen in Sema rather than CodeGen.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:1075-1078
+  // Insert previous NoBuiltin attributes.
+  if (D->hasAttr())
+for (StringRef FunctionName : D->getAttr()->functionNames())
+  FunctionNames.insert(FunctionName);

I think that this should be done in a `merge` function; there are plenty of 
examples of how this is typically done elsewhere in the file.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:1080-1081
+
+  if (AL.getNumArgs() == 0)
+FunctionNames.insert(Wildcard);
+  else

Given that the user has to provide the parens for the attribute anyway, I think 
this situation should be diagnosed rather than defaulting to the wildcard. It 
helps catch think-os where the user put in parens and forgot to add the 
parameter in the first place (the wildcard is not onerous to spell out).



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:1091
+
+  // Wildcard is a super set of all builtins, we keep only this one.
+  if (FunctionNames.count(Wildcard) > 0) {

super set -> superset



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:1092
+  // Wildcard is a super set of all builtins, we keep only this one.
+  if (FunctionNames.count(Wildcard) > 0) {
+FunctionNames.clear();

This silently changes the behavior from what the user might expect, which seems 
bad. For instance, it would be very reasonable for a user to write 
`[[clang::no_builtin("__builtin_mem*")]]` expecting that to behave as a regex 
pattern, but instead it silently turns into a "disable all builtins".

I think it makes sense to diagnose unexpected input like that rather than 
silently accept it under perhaps unexpected semantics. It may also make sense 
to support regex patterns in the strings or at least keep the design such that 
we can add that functionality later without breaking users.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:1097
+
+  auto UniqueFunctionNames = FunctionNames.takeVector();
+  llvm::sort(UniqueFunctionNames);

Please don't use `auto` here as the type is not spelled out in the 
initialization.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:1100-1101
+
+  if (D->hasAttr())
+D->dropAttr();
+

I think this needs to happen in a `merge` function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68028



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


[PATCH] D68027: [clangd] Change constness of parameters to findExplicitRefs

2019-09-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov added a comment.
This revision is now accepted and ready to land.

@kadircet says we're using this pattern all over clangd. This somehow slipped 
my view before.
LGTM to be consistent with the rest of clangd (and functions in `FindTarget.h`).

I think we should switch to passing non-const pointers everywhere, but that's a 
discussion for another day...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68027



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


[PATCH] D68031: [CUDA][HIP] Enable kernel function return type deduction.

2019-09-25 Thread Michael Liao via Phabricator via cfe-commits
hliao created this revision.
hliao added reviewers: tra, jlebar.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

- Even though only `void` is still accepted as the deduced return type, 
enabling deduction/instantiation on the return type allows more consistent 
coding.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68031

Files:
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/test/SemaCUDA/autoret-global.cu

Index: clang/test/SemaCUDA/autoret-global.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/autoret-global.cu
@@ -0,0 +1,44 @@
+// RUN: %clang_cc1 -std=c++14 -fsyntax-only -verify %s
+
+#include "Inputs/cuda.h"
+
+template 
+__global__ T foo() {
+  // expected-note@-1 {{kernel function type 'T ()' must have void return type}}
+}
+
+void f0() {
+  foo<<<0, 0>>>();
+  foo<<<0, 0>>>();
+  // expected-error@-1 {{no matching function for call to 'foo'}}
+}
+
+__global__ auto f1() {
+}
+
+__global__ auto f2(int x) {
+  return x + 1;
+  // expected-error@-2 {{kernel function type 'auto (int)' must have void return type}}
+}
+
+template  struct enable_if { typedef T type; };
+template  struct enable_if {};
+
+template 
+__global__
+auto bar() -> typename enable_if::type {
+  // expected-note@-1 {{requirement '3 == 1' was not satisfied [with N = 3]}}
+}
+
+template 
+__global__
+auto bar() -> typename enable_if::type {
+  // expected-note@-1 {{requirement '3 == 2' was not satisfied [with N = 3]}}
+}
+
+void f3() {
+  bar<1><<<0, 0>>>();
+  bar<2><<<0, 0>>>();
+  bar<3><<<0, 0>>>();
+  // expected-error@-1 {{no matching function for call to 'bar'}}
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3093,6 +3093,13 @@
   Function->getTypeSpecStartLoc(), Function->getDeclName());
 if (ResultType.isNull() || Trap.hasErrorOccurred())
   return TDK_SubstitutionFailure;
+// CUDA: Kernel function must have 'void' return type.
+if (getLangOpts().CUDA)
+  if (Function->hasAttr() && !ResultType->isVoidType()) {
+Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
+<< Function->getType() << Function->getSourceRange();
+return TDK_SubstitutionFailure;
+  }
   }
 
   // Instantiate the types of each of the function parameters given the
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -3500,6 +3500,14 @@
   return true;
   }
 
+  // CUDA: Kernel function must have 'void' return type.
+  if (getLangOpts().CUDA)
+if (FD->hasAttr() && !Deduced->isVoidType()) {
+  Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
+  << FD->getType() << FD->getSourceRange();
+  return true;
+}
+
   //  If a function with a declared return type that contains a placeholder type
   //  has multiple return statements, the return type is deduced for each return
   //  statement. [...] if the type deduced is not the same in each deduction,
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -5891,7 +5891,9 @@
 << FDecl << Fn->getSourceRange());
 
   // CUDA: Kernel function must have 'void' return type
-  if (!FuncT->getReturnType()->isVoidType())
+  if (!FuncT->getReturnType()->isVoidType() &&
+  !FuncT->getReturnType()->getAs() &&
+  !FuncT->getReturnType()->isInstantiationDependentType())
 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
 << Fn->getType() << Fn->getSourceRange());
 } else {
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -4223,7 +4223,9 @@
 return;
   }
   const auto *FD = cast(D);
-  if (!FD->getReturnType()->isVoidType()) {
+  if (!FD->getReturnType()->isVoidType() &&
+  !FD->getReturnType()->getAs() &&
+  !FD->getReturnType()->isInstantiationDependentType()) {
 SourceRange RTRange = FD->getReturnTypeSourceRange();
 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
 << FD->getType()
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r372888 - [clangd] Change constness of parameters to findExplicitRefs

2019-09-25 Thread Kadir Cetinkaya via cfe-commits
Author: kadircet
Date: Wed Sep 25 08:44:26 2019
New Revision: 372888

URL: http://llvm.org/viewvc/llvm-project?rev=372888&view=rev
Log:
[clangd] Change constness of parameters to findExplicitRefs

Summary:
Recursive AST requires non-const ast nodes, but it doesn't really
mutate them. In addition to that, in clangd we mostly have const ast nodes. So
it makes sense to move the const_cast into callee rather than having it at every
caller in the future.

Reviewers: ilya-biryukov

Subscribers: MaskRay, jkorous, arphaman, usaxena95, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/FindTarget.cpp
clang-tools-extra/trunk/clangd/FindTarget.h

Modified: clang-tools-extra/trunk/clangd/FindTarget.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FindTarget.cpp?rev=372888&r1=372887&r2=372888&view=diff
==
--- clang-tools-extra/trunk/clangd/FindTarget.cpp (original)
+++ clang-tools-extra/trunk/clangd/FindTarget.cpp Wed Sep 25 08:44:26 2019
@@ -616,15 +616,15 @@ private:
 };
 } // namespace
 
-void findExplicitReferences(Stmt *S,
+void findExplicitReferences(const Stmt *S,
 llvm::function_ref Out) {
   assert(S);
-  ExplicitReferenceColletor(Out).TraverseStmt(S);
+  ExplicitReferenceColletor(Out).TraverseStmt(const_cast(S));
 }
-void findExplicitReferences(Decl *D,
+void findExplicitReferences(const Decl *D,
 llvm::function_ref Out) {
   assert(D);
-  ExplicitReferenceColletor(Out).TraverseDecl(D);
+  ExplicitReferenceColletor(Out).TraverseDecl(const_cast(D));
 }
 
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {

Modified: clang-tools-extra/trunk/clangd/FindTarget.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FindTarget.h?rev=372888&r1=372887&r2=372888&view=diff
==
--- clang-tools-extra/trunk/clangd/FindTarget.h (original)
+++ clang-tools-extra/trunk/clangd/FindTarget.h Wed Sep 25 08:44:26 2019
@@ -101,9 +101,9 @@ llvm::raw_ostream &operator<<(llvm::raw_
 /// qualifiers.
 /// FIXME: currently this does not report references to overloaded operators.
 /// FIXME: extend to report location information about declaration names too.
-void findExplicitReferences(Stmt *S,
+void findExplicitReferences(const Stmt *S,
 llvm::function_ref Out);
-void findExplicitReferences(Decl *D,
+void findExplicitReferences(const Decl *D,
 llvm::function_ref Out);
 
 /// Similar to targetDecl(), however instead of applying a filter, all possible


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


[PATCH] D68027: [clangd] Change constness of parameters to findExplicitRefs

2019-09-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL372888: [clangd] Change constness of parameters to 
findExplicitRefs (authored by kadircet, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D68027?vs=221767&id=221782#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D68027

Files:
  clang-tools-extra/trunk/clangd/FindTarget.cpp
  clang-tools-extra/trunk/clangd/FindTarget.h


Index: clang-tools-extra/trunk/clangd/FindTarget.h
===
--- clang-tools-extra/trunk/clangd/FindTarget.h
+++ clang-tools-extra/trunk/clangd/FindTarget.h
@@ -101,9 +101,9 @@
 /// qualifiers.
 /// FIXME: currently this does not report references to overloaded operators.
 /// FIXME: extend to report location information about declaration names too.
-void findExplicitReferences(Stmt *S,
+void findExplicitReferences(const Stmt *S,
 llvm::function_ref Out);
-void findExplicitReferences(Decl *D,
+void findExplicitReferences(const Decl *D,
 llvm::function_ref Out);
 
 /// Similar to targetDecl(), however instead of applying a filter, all possible
Index: clang-tools-extra/trunk/clangd/FindTarget.cpp
===
--- clang-tools-extra/trunk/clangd/FindTarget.cpp
+++ clang-tools-extra/trunk/clangd/FindTarget.cpp
@@ -616,15 +616,15 @@
 };
 } // namespace
 
-void findExplicitReferences(Stmt *S,
+void findExplicitReferences(const Stmt *S,
 llvm::function_ref Out) {
   assert(S);
-  ExplicitReferenceColletor(Out).TraverseStmt(S);
+  ExplicitReferenceColletor(Out).TraverseStmt(const_cast(S));
 }
-void findExplicitReferences(Decl *D,
+void findExplicitReferences(const Decl *D,
 llvm::function_ref Out) {
   assert(D);
-  ExplicitReferenceColletor(Out).TraverseDecl(D);
+  ExplicitReferenceColletor(Out).TraverseDecl(const_cast(D));
 }
 
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {


Index: clang-tools-extra/trunk/clangd/FindTarget.h
===
--- clang-tools-extra/trunk/clangd/FindTarget.h
+++ clang-tools-extra/trunk/clangd/FindTarget.h
@@ -101,9 +101,9 @@
 /// qualifiers.
 /// FIXME: currently this does not report references to overloaded operators.
 /// FIXME: extend to report location information about declaration names too.
-void findExplicitReferences(Stmt *S,
+void findExplicitReferences(const Stmt *S,
 llvm::function_ref Out);
-void findExplicitReferences(Decl *D,
+void findExplicitReferences(const Decl *D,
 llvm::function_ref Out);
 
 /// Similar to targetDecl(), however instead of applying a filter, all possible
Index: clang-tools-extra/trunk/clangd/FindTarget.cpp
===
--- clang-tools-extra/trunk/clangd/FindTarget.cpp
+++ clang-tools-extra/trunk/clangd/FindTarget.cpp
@@ -616,15 +616,15 @@
 };
 } // namespace
 
-void findExplicitReferences(Stmt *S,
+void findExplicitReferences(const Stmt *S,
 llvm::function_ref Out) {
   assert(S);
-  ExplicitReferenceColletor(Out).TraverseStmt(S);
+  ExplicitReferenceColletor(Out).TraverseStmt(const_cast(S));
 }
-void findExplicitReferences(Decl *D,
+void findExplicitReferences(const Decl *D,
 llvm::function_ref Out) {
   assert(D);
-  ExplicitReferenceColletor(Out).TraverseDecl(D);
+  ExplicitReferenceColletor(Out).TraverseDecl(const_cast(D));
 }
 
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r372889 - Re-land r372863: [AST] Extract Decl::printNestedNameSpecifier helper from Decl::printQualifiedName

2019-09-25 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Sep 25 08:46:04 2019
New Revision: 372889

URL: http://llvm.org/viewvc/llvm-project?rev=372889&view=rev
Log:
Re-land r372863: [AST] Extract Decl::printNestedNameSpecifier helper from 
Decl::printQualifiedName

Reverted in r372880 due to the test failure.
Also contains a fix that adjusts printQualifiedName to return the same results 
as before in
case of anonymous function locals and parameters.

Modified:
cfe/trunk/include/clang/AST/Decl.h
cfe/trunk/lib/AST/Decl.cpp
cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp

Modified: cfe/trunk/include/clang/AST/Decl.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Decl.h?rev=372889&r1=372888&r2=372889&view=diff
==
--- cfe/trunk/include/clang/AST/Decl.h (original)
+++ cfe/trunk/include/clang/AST/Decl.h Wed Sep 25 08:46:04 2019
@@ -310,6 +310,14 @@ public:
   void printQualifiedName(raw_ostream &OS) const;
   void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
 
+  /// Print only the nested name specifier part of a fully-qualified name,
+  /// including the '::' at the end. E.g.
+  ///when `printQualifiedName(D)` prints "A::B::i",
+  ///this function prints "A::B::".
+  void printNestedNameSpecifier(raw_ostream &OS) const;
+  void printNestedNameSpecifier(raw_ostream &OS,
+const PrintingPolicy &Policy) const;
+
   // FIXME: Remove string version.
   std::string getQualifiedNameAsString() const;
 

Modified: cfe/trunk/lib/AST/Decl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=372889&r1=372888&r2=372889&view=diff
==
--- cfe/trunk/lib/AST/Decl.cpp (original)
+++ cfe/trunk/lib/AST/Decl.cpp Wed Sep 25 08:46:04 2019
@@ -1558,6 +1558,24 @@ void NamedDecl::printQualifiedName(raw_o
 
 void NamedDecl::printQualifiedName(raw_ostream &OS,
const PrintingPolicy &P) const {
+  if (getDeclContext()->isFunctionOrMethod()) {
+// We do not print '(anonymous)' for function parameters without name.
+printName(OS);
+return;
+  }
+  printNestedNameSpecifier(OS, P);
+  if (getDeclName() || isa(this))
+OS << *this;
+  else
+OS << "(anonymous)";
+}
+
+void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
+  printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
+}
+
+void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
+ const PrintingPolicy &P) const {
   const DeclContext *Ctx = getDeclContext();
 
   // For ObjC methods and properties, look through categories and use the
@@ -1571,10 +1589,8 @@ void NamedDecl::printQualifiedName(raw_o
 Ctx = ID;
   }
 
-  if (Ctx->isFunctionOrMethod()) {
-printName(OS);
+  if (Ctx->isFunctionOrMethod())
 return;
-  }
 
   using ContextsTy = SmallVector;
   ContextsTy Contexts;
@@ -1644,11 +1660,6 @@ void NamedDecl::printQualifiedName(raw_o
 }
 OS << "::";
   }
-
-  if (getDeclName() || isa(this))
-OS << *this;
-  else
-OS << "(anonymous)";
 }
 
 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,

Modified: cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp?rev=372889&r1=372888&r2=372889&view=diff
==
--- cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp (original)
+++ cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp Wed Sep 25 08:46:04 2019
@@ -16,9 +16,12 @@
 
//===--===//
 
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/PrettyPrinter.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/Support/raw_ostream.h"
 #include "gtest/gtest.h"
 
 using namespace clang;
@@ -30,11 +33,12 @@ namespace {
 class PrintMatch : public MatchFinder::MatchCallback {
   SmallString<1024> Printed;
   unsigned NumFoundDecls;
-  bool SuppressUnwrittenScope;
+  std::function Printer;
 
 public:
-  explicit PrintMatch(bool suppressUnwrittenScope)
-: NumFoundDecls(0), SuppressUnwrittenScope(suppressUnwrittenScope) {}
+  explicit PrintMatch(
+  std::function Printer)
+  : NumFoundDecls(0), Printer(std::move(Printer)) {}
 
   void run(const MatchFinder::MatchResult &Result) override {
 const NamedDecl *ND = Result.Nodes.getNodeAs("id");
@@ -45,9 +49,7 @@ public:
   return;
 
 llvm::raw_svector_ostream Out(Printed);
-PrintingPolicy Policy = Result.Context->getPrintingPolicy();
-Policy.SuppressUnwrittenScope = SuppressUnwrittenScope;
-ND->printQualifiedName(Out, Policy);
+Printer(Out, ND);
   }
 
   StringRef getPrinted() const {
@@ -59,1

Re: r372863 - [AST] Extract Decl::printNestedNameSpecifier helper from Decl::printQualifiedName

2019-09-25 Thread Ilya Biryukov via cfe-commits
Reverted and re-landed with a fix to this.
This should've been an NFC, but I missed one corner case. Sorry about that.

On Wed, Sep 25, 2019 at 4:22 PM Nico Weber  wrote:

> Is it possible that this broke Tooling/clang-diff-ast.cpp
> http://lab.llvm.org:8011/builders/clang-cmake-x86_64-avx2-linux/builds/11395/steps/ninja%20check%201/logs/FAIL%3A%20Clang%3A%3Aclang-diff-ast.cpp
> ?
>
> On Wed, Sep 25, 2019 at 9:07 AM Ilya Biryukov via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: ibiryukov
>> Date: Wed Sep 25 06:09:10 2019
>> New Revision: 372863
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=372863&view=rev
>> Log:
>> [AST] Extract Decl::printNestedNameSpecifier helper from
>> Decl::printQualifiedName
>>
>> Summary:
>> To be used in clangd, e.g. in D66647.
>> Currently the alternative to this function is doing string manipulation
>> on results of `printQualifiedName`, which is
>> hard-to-impossible to get right in presence of template arguments.
>>
>> Reviewers: kadircet, aaron.ballman
>>
>> Reviewed By: kadircet, aaron.ballman
>>
>> Subscribers: aaron.ballman, usaxena95, cfe-commits
>>
>> Tags: #clang
>>
>> Differential Revision: https://reviews.llvm.org/D67825
>>
>> Modified:
>> cfe/trunk/include/clang/AST/Decl.h
>> cfe/trunk/lib/AST/Decl.cpp
>> cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp
>>
>> Modified: cfe/trunk/include/clang/AST/Decl.h
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Decl.h?rev=372863&r1=372862&r2=372863&view=diff
>>
>> ==
>> --- cfe/trunk/include/clang/AST/Decl.h (original)
>> +++ cfe/trunk/include/clang/AST/Decl.h Wed Sep 25 06:09:10 2019
>> @@ -310,6 +310,14 @@ public:
>>void printQualifiedName(raw_ostream &OS) const;
>>void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy)
>> const;
>>
>> +  /// Print only the nested name specifier part of a fully-qualified
>> name,
>> +  /// including the '::' at the end. E.g.
>> +  ///when `printQualifiedName(D)` prints "A::B::i",
>> +  ///this function prints "A::B::".
>> +  void printNestedNameSpecifier(raw_ostream &OS) const;
>> +  void printNestedNameSpecifier(raw_ostream &OS,
>> +const PrintingPolicy &Policy) const;
>> +
>>// FIXME: Remove string version.
>>std::string getQualifiedNameAsString() const;
>>
>>
>> Modified: cfe/trunk/lib/AST/Decl.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=372863&r1=372862&r2=372863&view=diff
>>
>> ==
>> --- cfe/trunk/lib/AST/Decl.cpp (original)
>> +++ cfe/trunk/lib/AST/Decl.cpp Wed Sep 25 06:09:10 2019
>> @@ -1558,6 +1558,19 @@ void NamedDecl::printQualifiedName(raw_o
>>
>>  void NamedDecl::printQualifiedName(raw_ostream &OS,
>> const PrintingPolicy &P) const {
>> +  printNestedNameSpecifier(OS, P);
>> +  if (getDeclName() || isa(this))
>> +OS << *this;
>> +  else
>> +OS << "(anonymous)";
>> +}
>> +
>> +void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
>> +  printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
>> +}
>> +
>> +void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
>> + const PrintingPolicy &P) const {
>>const DeclContext *Ctx = getDeclContext();
>>
>>// For ObjC methods and properties, look through categories and use the
>> @@ -1571,10 +1584,8 @@ void NamedDecl::printQualifiedName(raw_o
>>  Ctx = ID;
>>}
>>
>> -  if (Ctx->isFunctionOrMethod()) {
>> -printName(OS);
>> +  if (Ctx->isFunctionOrMethod())
>>  return;
>> -  }
>>
>>using ContextsTy = SmallVector;
>>ContextsTy Contexts;
>> @@ -1644,11 +1655,6 @@ void NamedDecl::printQualifiedName(raw_o
>>  }
>>  OS << "::";
>>}
>> -
>> -  if (getDeclName() || isa(this))
>> -OS << *this;
>> -  else
>> -OS << "(anonymous)";
>>  }
>>
>>  void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
>>
>> Modified: cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp?rev=372863&r1=372862&r2=372863&view=diff
>>
>> ==
>> --- cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp (original)
>> +++ cfe/trunk/unittests/AST/NamedDeclPrinterTest.cpp Wed Sep 25 06:09:10
>> 2019
>> @@ -16,9 +16,12 @@
>>
>>  
>> //===--===//
>>
>>  #include "clang/AST/ASTContext.h"
>> +#include "clang/AST/Decl.h"
>> +#include "clang/AST/PrettyPrinter.h"
>>  #include "clang/ASTMatchers/ASTMatchFinder.h"
>>  #include "clang/Tooling/Tooling.h"
>>  #include "llvm/ADT/SmallString.h"
>> +#include "llvm/Support/raw_ostream.h"
>>  #include "gtest/gtest.h"
>>
>>  using namespace clan

[PATCH] D63640: [clang] Improve Serialization/Imporing/Dumping of APValues

2019-09-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/AST/APValue.h:613
+  /// in place as after importing/deserializating then.
+  void reserveVector(unsigned N) {
+assert(isVector() && "Invalid accessor");

`ReserveVector`



Comment at: clang/include/clang/AST/APValue.h:620
+  unsigned Size);
+  void setLValueEmptyPath(LValueBase B, const CharUnits &O, unsigned Size,
+  bool OnePastTheEnd, bool IsNullPtr);

`SetLValueEmptyPath`



Comment at: clang/lib/AST/APValue.cpp:599
 Out << '[' << Path[I].getAsArrayIndex() << ']';
-ElemTy = Ctx.getAsArrayType(ElemTy)->getElementType();
+ElemTy = cast(ElemTy)->getElementType();
   }

Tyker wrote:
> aaron.ballman wrote:
> > Are you sure this doesn't change behavior? See the implementation of 
> > `ASTContext::getAsArrayType()`. Same question applies below.
> i ran the test suite after the change it there wasn't any test failures. but 
> the test on dumping APValue are probably not as thorough as we would like 
> them to be.
> from analysis of `ASTContext::getAsArrayType()` the only effect i see on the 
> element type is de-sugaring and canonicalization which shouldn't affect 
> correctness of the output.  de-sugaring requires the ASTContext but 
> canonicalization doesn't.
> 
> i think the best way the have higher confidence is to ask rsmith what he 
> thinks.
Yeah, I doubt we have good test coverage for all the various behaviors here. I 
was wondering if the qualifiers bit was handled properly with a simple cast. 
@rsmith is a good person to weigh in.



Comment at: clang/test/ASTMerge/APValue/APValue.cpp:28
+
+// FIXME: Add test for FixePoint, ComplexInt, ComplexFloat, AddrLabelDiff.
+

Tyker wrote:
> aaron.ballman wrote:
> > Tyker wrote:
> > > aaron.ballman wrote:
> > > > Are you planning to address this in this patch? Also, I think it's 
> > > > FixedPoint and not FixePoint.
> > > i don't intend to add them in this patch or subsequent patches. i don't 
> > > know how to use the features that have these representations, i don't 
> > > even know if they can be stored stored in that AST. so this is untested 
> > > code.
> > > that said theses representations aren't complex. the imporing for 
> > > FixePoint, ComplexInt, ComplexFloat is a no-op and for AddrLabelDiff it 
> > > is trivial. for serialization, I can put an llvm_unreachable to mark them 
> > > as untested if you want ?
> > I don't think `llvm_unreachable` makes a whole lot of sense unless the code 
> > is truly unreachable because there's no way to get an AST with that 
> > representation. By code inspection, the code looks reasonable but it does 
> > make me a bit uncomfortable to adopt it without tests. I suppose the FIXME 
> > is a reasonable compromise in this case, but if you have some spare cycles 
> > to investigate ways to get those representations, it would be appreciated.
> the reason i proposed `llvm_unreachable` was because it passes the tests and 
> prevents future developer from depending on the code that depend on it 
> assuming it works.
We typically only use `llvm_unreachable` for situations where we believe the 
code path is impossible to reach, which is why I think that's the wrong 
approach. We could use an assertion to test the theory, however.


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

https://reviews.llvm.org/D63640



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


[PATCH] D67901: [clangd] Improve semantic highlighting in dependent contexts (fixes #154)

2019-09-25 Thread Nathan Ridge via Phabricator via cfe-commits
nridge marked 2 inline comments as done.
nridge added inline comments.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:181
+  addToken(E->getMemberLoc(), E->getQualifier()
+  ? HighlightingKind::StaticField
+  : HighlightingKind::Field);

hokein wrote:
> ilya-biryukov wrote:
> > nridge wrote:
> > > hokein wrote:
> > > > This could be member functions, a case is like
> > > > 
> > > > ```
> > > > template
> > > > class Foo {
> > > > public:
> > > >   void foo() {
> > > > this->foo();
> > > >   }
> > > > };
> > > > ```
> > > Thanks for the example.
> > > 
> > > Do you have a suggestion for how to discriminate this case? To me, it 
> > > would seem logical to do it based on syntax (highlight as a member 
> > > function if the expression forms the function name of a function call 
> > > expression). That would require navigating from the expression to its 
> > > parent node. Is there a way to do that?
> > There is no way to do this in C++.
> > Even if the name is followed by a pair of parenthese, this could either be 
> > a field with overloaded `operator()` (e.g. a `std::function field`) 
> > or a function with the same name.
> > 
> > It's much better to pick a separate highlighting kind for dependent names, 
> > this follows the actual semantics of C++.
> +1, I think we should just highlight them as a dependent type.
Of course, any attempt to disambiguate between a member function and a field 
would be heuristic only. I figured that would be better than nothing. But if 
you prefer using a separate highlighting for dependent names that resolve to a 
function or a variable, we could do that.

(Hokein, I assume you don't actually mean using the dependent *type* 
highlighting. Using a type highlighting for something we know is not a type, 
but rather a function or variable, would be rather confusing.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67901



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


[PATCH] D67919: [Diagnostics] Warn if enumeration type mismatch in conditional expression

2019-09-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: lib/Sema/SemaChecking.cpp:11264
+
+  const EnumType *LHSEnumType = LHSStrippedType->getAs();
+  if (!LHSEnumType)

`const auto *` (and below as well) since the type is spelled out in the 
initialization.



Comment at: lib/Sema/SemaChecking.cpp:11272-11274
+  if (!LHSEnumType->getDecl()->getIdentifier() &&
+  !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
+return;

Would it make sense to use `!LHSEnumType->getDecl()->hasNameForLinkage()` here? 
It seems like that's the situation we care about.



Comment at: lib/Sema/SemaChecking.cpp:11785
   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
+  checkConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(),
+E->getFalseExpr());

Might make sense to name the new function `CheckConditionalWithEnumTypes()` to 
match the local style better.



Comment at: test/Sema/warn-conditional-emum-types-mismatch.c:15
+  #else 
+  // expected-no-diagnostics'
+  #endif

Spurious `'`



Comment at: test/Sema/warn-conditional-emum-types-mismatch.c:19
+
+int get_flag_anon_enum(int cond) {
+  return cond ? A : C;

xbolva00 wrote:
> Gcc warns here, but Clang does not warn when A != C..
> 
> So not sure here..
My gut reaction is that I think Clang should warn here as well because the code 
pattern is confusing, but I'd also say that if there's a lot of false positives 
where the code is sensible, it may make sense to suppress the diagnostic. One 
situation I was thinking of where you could run into something like this is:
```
enum {
  STATUS_SUCCESS,
  STATUS_FAILURE,
  ...
  MAX_BASE_STATUS_CODE
};

enum ExtendedStatusCodes {
  STATUS_SOMETHING_INTERESTING = MAX_BASE_STATUS_CODE + 1000,
  ...
};

int whatever(void) {
  return some_condition() ? STATUS_SOMETHING_INTERESTING : STATUS_SUCCESS;
}
```


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

https://reviews.llvm.org/D67919



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


[PATCH] D68031: [CUDA][HIP] Enable kernel function return type deduction.

2019-09-25 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra added a comment.
This revision is now accepted and ready to land.

Nice.  I'd mention in the commit message that NVCC does not support deduced 
return type for kernel functions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68031



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


r372898 - [CUDA][HIP] Enable kernel function return type deduction.

2019-09-25 Thread Michael Liao via cfe-commits
Author: hliao
Date: Wed Sep 25 09:51:45 2019
New Revision: 372898

URL: http://llvm.org/viewvc/llvm-project?rev=372898&view=rev
Log:
[CUDA][HIP] Enable kernel function return type deduction.

Summary:
- Even though only `void` is still accepted as the deduced return type,
  enabling deduction/instantiation on the return type allows more
  consistent coding.

Reviewers: tra, jlebar

Subscribers: cfe-commits, yaxunl

Tags: #clang

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

Added:
cfe/trunk/test/SemaCUDA/autoret-global.cu
Modified:
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/lib/Sema/SemaExpr.cpp
cfe/trunk/lib/Sema/SemaStmt.cpp
cfe/trunk/lib/Sema/SemaTemplateDeduction.cpp

Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=372898&r1=372897&r2=372898&view=diff
==
--- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Wed Sep 25 09:51:45 2019
@@ -4223,7 +4223,9 @@ static void handleGlobalAttr(Sema &S, De
 return;
   }
   const auto *FD = cast(D);
-  if (!FD->getReturnType()->isVoidType()) {
+  if (!FD->getReturnType()->isVoidType() &&
+  !FD->getReturnType()->getAs() &&
+  !FD->getReturnType()->isInstantiationDependentType()) {
 SourceRange RTRange = FD->getReturnTypeSourceRange();
 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
 << FD->getType()

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=372898&r1=372897&r2=372898&view=diff
==
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Wed Sep 25 09:51:45 2019
@@ -5891,7 +5891,9 @@ ExprResult Sema::BuildResolvedCallExpr(E
 << FDecl << Fn->getSourceRange());
 
   // CUDA: Kernel function must have 'void' return type
-  if (!FuncT->getReturnType()->isVoidType())
+  if (!FuncT->getReturnType()->isVoidType() &&
+  !FuncT->getReturnType()->getAs() &&
+  !FuncT->getReturnType()->isInstantiationDependentType())
 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
 << Fn->getType() << Fn->getSourceRange());
 } else {

Modified: cfe/trunk/lib/Sema/SemaStmt.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaStmt.cpp?rev=372898&r1=372897&r2=372898&view=diff
==
--- cfe/trunk/lib/Sema/SemaStmt.cpp (original)
+++ cfe/trunk/lib/Sema/SemaStmt.cpp Wed Sep 25 09:51:45 2019
@@ -3500,6 +3500,14 @@ bool Sema::DeduceFunctionTypeFromReturnE
   return true;
   }
 
+  // CUDA: Kernel function must have 'void' return type.
+  if (getLangOpts().CUDA)
+if (FD->hasAttr() && !Deduced->isVoidType()) {
+  Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
+  << FD->getType() << FD->getSourceRange();
+  return true;
+}
+
   //  If a function with a declared return type that contains a placeholder 
type
   //  has multiple return statements, the return type is deduced for each 
return
   //  statement. [...] if the type deduced is not the same in each deduction,

Modified: cfe/trunk/lib/Sema/SemaTemplateDeduction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaTemplateDeduction.cpp?rev=372898&r1=372897&r2=372898&view=diff
==
--- cfe/trunk/lib/Sema/SemaTemplateDeduction.cpp (original)
+++ cfe/trunk/lib/Sema/SemaTemplateDeduction.cpp Wed Sep 25 09:51:45 2019
@@ -3093,6 +3093,13 @@ Sema::SubstituteExplicitTemplateArgument
   Function->getTypeSpecStartLoc(), Function->getDeclName());
 if (ResultType.isNull() || Trap.hasErrorOccurred())
   return TDK_SubstitutionFailure;
+// CUDA: Kernel function must have 'void' return type.
+if (getLangOpts().CUDA)
+  if (Function->hasAttr() && !ResultType->isVoidType()) {
+Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
+<< Function->getType() << Function->getSourceRange();
+return TDK_SubstitutionFailure;
+  }
   }
 
   // Instantiate the types of each of the function parameters given the

Added: cfe/trunk/test/SemaCUDA/autoret-global.cu
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCUDA/autoret-global.cu?rev=372898&view=auto
==
--- cfe/trunk/test/SemaCUDA/autoret-global.cu (added)
+++ cfe/trunk/test/SemaCUDA/autoret-global.cu Wed Sep 25 09:51:45 2019
@@ -0,0 +1,44 @@
+// RUN: %clang_cc1 -std=c++14 -fsyntax-only -verify %s
+
+#include "Inputs/cuda.h"
+
+template 
+__global__ T foo() {
+  // expected-note@-1 {{kernel function type 'T ()' 

[PATCH] D68031: [CUDA][HIP] Enable kernel function return type deduction.

2019-09-25 Thread Michael Liao via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG24337db61666: [CUDA][HIP] Enable kernel function return type 
deduction. (authored by hliao).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68031

Files:
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/test/SemaCUDA/autoret-global.cu

Index: clang/test/SemaCUDA/autoret-global.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/autoret-global.cu
@@ -0,0 +1,44 @@
+// RUN: %clang_cc1 -std=c++14 -fsyntax-only -verify %s
+
+#include "Inputs/cuda.h"
+
+template 
+__global__ T foo() {
+  // expected-note@-1 {{kernel function type 'T ()' must have void return type}}
+}
+
+void f0() {
+  foo<<<0, 0>>>();
+  foo<<<0, 0>>>();
+  // expected-error@-1 {{no matching function for call to 'foo'}}
+}
+
+__global__ auto f1() {
+}
+
+__global__ auto f2(int x) {
+  return x + 1;
+  // expected-error@-2 {{kernel function type 'auto (int)' must have void return type}}
+}
+
+template  struct enable_if { typedef T type; };
+template  struct enable_if {};
+
+template 
+__global__
+auto bar() -> typename enable_if::type {
+  // expected-note@-1 {{requirement '3 == 1' was not satisfied [with N = 3]}}
+}
+
+template 
+__global__
+auto bar() -> typename enable_if::type {
+  // expected-note@-1 {{requirement '3 == 2' was not satisfied [with N = 3]}}
+}
+
+void f3() {
+  bar<1><<<0, 0>>>();
+  bar<2><<<0, 0>>>();
+  bar<3><<<0, 0>>>();
+  // expected-error@-1 {{no matching function for call to 'bar'}}
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -3093,6 +3093,13 @@
   Function->getTypeSpecStartLoc(), Function->getDeclName());
 if (ResultType.isNull() || Trap.hasErrorOccurred())
   return TDK_SubstitutionFailure;
+// CUDA: Kernel function must have 'void' return type.
+if (getLangOpts().CUDA)
+  if (Function->hasAttr() && !ResultType->isVoidType()) {
+Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
+<< Function->getType() << Function->getSourceRange();
+return TDK_SubstitutionFailure;
+  }
   }
 
   // Instantiate the types of each of the function parameters given the
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -3500,6 +3500,14 @@
   return true;
   }
 
+  // CUDA: Kernel function must have 'void' return type.
+  if (getLangOpts().CUDA)
+if (FD->hasAttr() && !Deduced->isVoidType()) {
+  Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
+  << FD->getType() << FD->getSourceRange();
+  return true;
+}
+
   //  If a function with a declared return type that contains a placeholder type
   //  has multiple return statements, the return type is deduced for each return
   //  statement. [...] if the type deduced is not the same in each deduction,
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -5891,7 +5891,9 @@
 << FDecl << Fn->getSourceRange());
 
   // CUDA: Kernel function must have 'void' return type
-  if (!FuncT->getReturnType()->isVoidType())
+  if (!FuncT->getReturnType()->isVoidType() &&
+  !FuncT->getReturnType()->getAs() &&
+  !FuncT->getReturnType()->isInstantiationDependentType())
 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
 << Fn->getType() << Fn->getSourceRange());
 } else {
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -4223,7 +4223,9 @@
 return;
   }
   const auto *FD = cast(D);
-  if (!FD->getReturnType()->isVoidType()) {
+  if (!FD->getReturnType()->isVoidType() &&
+  !FD->getReturnType()->getAs() &&
+  !FD->getReturnType()->isInstantiationDependentType()) {
 SourceRange RTRange = FD->getReturnTypeSourceRange();
 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
 << FD->getType()
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68031: [CUDA][HIP] Enable kernel function return type deduction.

2019-09-25 Thread Michael Liao via Phabricator via cfe-commits
hliao added a comment.

In D68031#1682822 , @tra wrote:

> Nice.  I'd mention in the commit message that NVCC does not support deduced 
> return type for kernel functions.


Just tried with NVCC from CUDA 10, except auto-based deduced type is not 
supported, type deduction in a template is supported, the following test code 
passes compilation with NVCC

  #include 
  
  template 
  __global__ T foo() {
  }
  
  void f0() {
foo<<<0, 0>>>();
  #if 0
foo<<<0, 0>>>();
  #endif
  }
  
  template  struct enable_if { typedef T type; };
  template  struct enable_if {};
  
  template 
  __global__
  auto bar() -> typename enable_if::type {
  }
  
  template 
  __global__
  auto bar() -> typename enable_if::type {
  }
  
  void f3() {
bar<1><<<0, 0>>>();
bar<2><<<0, 0>>>();
  #if 0
bar<3><<<0, 0>>>();
  #endif
  }

`s/#if 0/#if 1` also shows NVCC could give the error on the correct position 
but the message, IMHO, is misleading compared to the one from clang.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68031



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


[PATCH] D67774: [Mangle] Add flag to asm labels to disable '\01' prefixing

2019-09-25 Thread Vedant Kumar via Phabricator via cfe-commits
vsk updated this revision to Diff 221801.
vsk added a comment.

- Add a comment describing where non-literal labels are used.


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

https://reviews.llvm.org/D67774

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/AST/Mangle.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/unittests/AST/DeclTest.cpp
  lldb/source/Symbol/ClangASTContext.cpp

Index: lldb/source/Symbol/ClangASTContext.cpp
===
--- lldb/source/Symbol/ClangASTContext.cpp
+++ lldb/source/Symbol/ClangASTContext.cpp
@@ -8301,8 +8301,8 @@
 cxx_method_decl->addAttr(clang::UsedAttr::CreateImplicit(*getASTContext()));
 
   if (mangled_name != nullptr) {
-cxx_method_decl->addAttr(
-clang::AsmLabelAttr::CreateImplicit(*getASTContext(), mangled_name));
+cxx_method_decl->addAttr(clang::AsmLabelAttr::CreateImplicit(
+*getASTContext(), mangled_name, /*literal=*/false));
   }
 
   // Populate the method decl with parameter decls
Index: clang/unittests/AST/DeclTest.cpp
===
--- clang/unittests/AST/DeclTest.cpp
+++ clang/unittests/AST/DeclTest.cpp
@@ -10,12 +10,16 @@
 //
 //===--===//
 
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Mangle.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Tooling/Tooling.h"
 #include "gtest/gtest.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::tooling;
+using namespace clang;
 
 TEST(Decl, CleansUpAPValues) {
   MatchFinder Finder;
@@ -56,3 +60,48 @@
   "constexpr _Complex __uint128_t c = 0x;",
   Args));
 }
+
+TEST(Decl, AsmLabelAttr) {
+  // Create two method decls: `f` and `g`.
+  StringRef Code = R"(
+struct S {
+  void f() {}
+  void g() {}
+};
+  )";
+  auto AST =
+  tooling::buildASTFromCodeWithArgs(Code, {"-target", "i386-apple-darwin"});
+  ASTContext &Ctx = AST->getASTContext();
+  assert(Ctx.getTargetInfo().getDataLayout().getGlobalPrefix() &&
+ "Expected target to have a global prefix");
+  DiagnosticsEngine &Diags = AST->getDiagnostics();
+  SourceManager &SM = AST->getSourceManager();
+  FileID MainFileID = SM.getMainFileID();
+
+  // Find the method decls within the AST.
+  SmallVector Decls;
+  AST->findFileRegionDecls(MainFileID, Code.find('{'), 0, Decls);
+  ASSERT_TRUE(Decls.size() == 1);
+  CXXRecordDecl *DeclS = cast(Decls[0]);
+  NamedDecl *DeclF = *DeclS->method_begin();
+  NamedDecl *DeclG = *(++DeclS->method_begin());
+
+  // Attach asm labels to the decls: one literal, and one not.
+  DeclF->addAttr(::new (Ctx) AsmLabelAttr(Ctx, SourceLocation(), "foo",
+  /*LiteralLabel=*/true));
+  DeclG->addAttr(::new (Ctx) AsmLabelAttr(Ctx, SourceLocation(), "goo",
+  /*LiteralLabel=*/false));
+
+  // Mangle the decl names.
+  std::string MangleF, MangleG;
+  MangleContext *MC = ItaniumMangleContext::create(Ctx, Diags);
+  {
+llvm::raw_string_ostream OS_F(MangleF);
+llvm::raw_string_ostream OS_G(MangleG);
+MC->mangleName(DeclF, OS_F);
+MC->mangleName(DeclG, OS_G);
+  }
+
+  ASSERT_TRUE(0 == MangleF.compare("\x01" "foo"));
+  ASSERT_TRUE(0 == MangleG.compare("goo"));
+}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -2766,7 +2766,7 @@
 
   if (AsmLabelAttr *NewA = New->getAttr()) {
 if (AsmLabelAttr *OldA = Old->getAttr()) {
-  if (OldA->getLabel() != NewA->getLabel()) {
+  if (!OldA->isEquivalent(NewA)) {
 // This redeclaration changes __asm__ label.
 Diag(New->getLocation(), diag::err_different_asm_label);
 Diag(OldA->getLocation(), diag::note_previous_declaration);
@@ -6983,8 +6983,8 @@
   }
 }
 
-NewVD->addAttr(::new (Context)
-   AsmLabelAttr(Context, SE->getStrTokenLoc(0), Label));
+NewVD->addAttr(::new (Context) AsmLabelAttr(
+Context, SE->getStrTokenLoc(0), Label, /*IsLiteralLabel=*/true));
   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
 llvm::DenseMap::iterator I =
   ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
@@ -8882,8 +8882,9 @@
   if (Expr *E = (Expr*) D.getAsmLabel()) {
 // The parser guarantees this is a string.
 StringLiteral *SE = cast(E);
-NewFD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getStrTokenLoc(0),
-SE->getString()));
+NewFD->addAttr(::new (Context)
+   AsmLabelAttr(Context, SE->getStrTokenLoc(0),
+SE->getString(), /*IsLiteralLabel=*/true));
   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
 

[PATCH] D67774: [Mangle] Add flag to asm labels to disable '\01' prefixing

2019-09-25 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

Thanks, LGTM.


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

https://reviews.llvm.org/D67774



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


LLVM buildmaster will be updated and restarted tonight

2019-09-25 Thread Galina Kistanova via cfe-commits
 Hello everyone,

LLVM buildmaster will be updated and restarted after 6PM Pacific time today.

Thanks

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


[PATCH] D67031: [Clang][Bundler] Error reporting improvements

2019-09-25 Thread Sergey Dmitriev via Phabricator via cfe-commits
sdmitriev added a comment.

Ping.


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

https://reviews.llvm.org/D67031



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


r372903 - [Mangle] Add flag to asm labels to disable '\01' prefixing

2019-09-25 Thread Vedant Kumar via cfe-commits
Author: vedantk
Date: Wed Sep 25 11:00:31 2019
New Revision: 372903

URL: http://llvm.org/viewvc/llvm-project?rev=372903&view=rev
Log:
[Mangle] Add flag to asm labels to disable '\01' prefixing

LLDB synthesizes decls using asm labels. These decls cannot have a mangle
different than the one specified in the label name. I.e., the '\01' prefix
should not be added.

Fixes an expression evaluation failure in lldb's TestVirtual.py on iOS.

rdar://45827323

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

Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/include/clang/Basic/AttrDocs.td
cfe/trunk/lib/AST/Mangle.cpp
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/unittests/AST/DeclTest.cpp

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=372903&r1=372902&r2=372903&view=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Wed Sep 25 11:00:31 2019
@@ -722,9 +722,25 @@ def AVRSignal : InheritableAttr, TargetS
 
 def AsmLabel : InheritableAttr {
   let Spellings = [Keyword<"asm">, Keyword<"__asm__">];
-  let Args = [StringArgument<"Label">];
+  let Args = [
+// Label specifies the mangled name for the decl.
+StringArgument<"Label">,
+
+// IsLiteralLabel specifies whether the label is literal (i.e. suppresses
+// the global C symbol prefix) or not. If not, the mangle-suppression 
prefix
+// ('\01') is omitted from the decl name at the LLVM IR level.
+//
+// Non-literal labels are used by some external AST sources like LLDB.
+BoolArgument<"IsLiteralLabel", /*optional=*/0, /*fake=*/1>
+  ];
   let SemaHandler = 0;
-  let Documentation = [Undocumented];
+  let Documentation = [AsmLabelDocs];
+  let AdditionalMembers =
+[{
+bool isEquivalent(AsmLabelAttr *Other) const {
+  return getLabel() == Other->getLabel() && getIsLiteralLabel() == 
Other->getIsLiteralLabel();
+}
+}];
 }
 
 def Availability : InheritableAttr {

Modified: cfe/trunk/include/clang/Basic/AttrDocs.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttrDocs.td?rev=372903&r1=372902&r2=372903&view=diff
==
--- cfe/trunk/include/clang/Basic/AttrDocs.td (original)
+++ cfe/trunk/include/clang/Basic/AttrDocs.td Wed Sep 25 11:00:31 2019
@@ -2558,6 +2558,30 @@ manipulating bits of the enumerator when
   }];
 }
 
+def AsmLabelDocs : Documentation {
+  let Category = DocCatDecl;
+  let Content = [{
+This attribute can be used on a function or variable to specify its symbol 
name.
+
+On some targets, all C symbols are prefixed by default with a single 
character, typically ``_``.  This was done historically to distinguish them 
from symbols used by other languages.  (This prefix is also added to the 
standard Itanium C++ ABI prefix on "mangled" symbol names, so that e.g. on such 
targets the true symbol name for a C++ variable declared as ``int cppvar;`` 
would be ``__Z6cppvar``; note the two underscores.)  This prefix is *not* added 
to the symbol names specified by the ``asm`` attribute; programmers wishing to 
match a C symbol name must compensate for this.
+
+For example, consider the following C code:
+
+.. code-block:: c
+
+  int var1 asm("altvar") = 1;  // "altvar" in symbol table.
+  int var2 = 1; // "_var2" in symbol table.
+
+  void func1(void) asm("altfunc");
+  void func1(void) {} // "altfunc" in symbol table.
+  void func2(void) {} // "_func2" in symbol table.
+
+Clang's implementation of this attribute is compatible with GCC's, `documented 
here `_.
+
+While it is possible to use this attribute to name a special symbol used 
internally by the compiler, such as an LLVM intrinsic, this is neither 
recommended nor supported and may cause the compiler to crash or miscompile.  
Users who wish to gain access to intrinsic behavior are strongly encouraged to 
request new builtin functions.
+  }];
+}
+
 def EnumExtensibilityDocs : Documentation {
   let Category = DocCatDecl;
   let Content = [{

Modified: cfe/trunk/lib/AST/Mangle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Mangle.cpp?rev=372903&r1=372902&r2=372903&view=diff
==
--- cfe/trunk/lib/AST/Mangle.cpp (original)
+++ cfe/trunk/lib/AST/Mangle.cpp Wed Sep 25 11:00:31 2019
@@ -122,15 +122,21 @@ void MangleContext::mangleName(const Nam
   if (const AsmLabelAttr *ALA = D->getAttr()) {
 // If we have an asm name, then we use it as the mangling.
 
+// If the label isn't literal, or if this is an alias for an LLVM 
intrinsic,
+// do not add a "\01" prefix.
+if (!ALA->getIsLiteralLabel() || ALA->getLabel().startswith("llvm.")) {
+  Out << ALA->getLabel();
+  return;
+}
+
 //

[PATCH] D67774: [Mangle] Add flag to asm labels to disable '\01' prefixing

2019-09-25 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL372903: [Mangle] Add flag to asm labels to disable 
'\01' prefixing (authored by vedantk, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D67774?vs=221801&id=221805#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D67774

Files:
  cfe/trunk/include/clang/Basic/Attr.td
  cfe/trunk/include/clang/Basic/AttrDocs.td
  cfe/trunk/lib/AST/Mangle.cpp
  cfe/trunk/lib/Sema/SemaDecl.cpp
  cfe/trunk/unittests/AST/DeclTest.cpp
  lldb/trunk/source/Symbol/ClangASTContext.cpp

Index: cfe/trunk/include/clang/Basic/Attr.td
===
--- cfe/trunk/include/clang/Basic/Attr.td
+++ cfe/trunk/include/clang/Basic/Attr.td
@@ -722,9 +722,25 @@
 
 def AsmLabel : InheritableAttr {
   let Spellings = [Keyword<"asm">, Keyword<"__asm__">];
-  let Args = [StringArgument<"Label">];
+  let Args = [
+// Label specifies the mangled name for the decl.
+StringArgument<"Label">,
+
+// IsLiteralLabel specifies whether the label is literal (i.e. suppresses
+// the global C symbol prefix) or not. If not, the mangle-suppression prefix
+// ('\01') is omitted from the decl name at the LLVM IR level.
+//
+// Non-literal labels are used by some external AST sources like LLDB.
+BoolArgument<"IsLiteralLabel", /*optional=*/0, /*fake=*/1>
+  ];
   let SemaHandler = 0;
-  let Documentation = [Undocumented];
+  let Documentation = [AsmLabelDocs];
+  let AdditionalMembers =
+[{
+bool isEquivalent(AsmLabelAttr *Other) const {
+  return getLabel() == Other->getLabel() && getIsLiteralLabel() == Other->getIsLiteralLabel();
+}
+}];
 }
 
 def Availability : InheritableAttr {
Index: cfe/trunk/include/clang/Basic/AttrDocs.td
===
--- cfe/trunk/include/clang/Basic/AttrDocs.td
+++ cfe/trunk/include/clang/Basic/AttrDocs.td
@@ -2558,6 +2558,30 @@
   }];
 }
 
+def AsmLabelDocs : Documentation {
+  let Category = DocCatDecl;
+  let Content = [{
+This attribute can be used on a function or variable to specify its symbol name.
+
+On some targets, all C symbols are prefixed by default with a single character, typically ``_``.  This was done historically to distinguish them from symbols used by other languages.  (This prefix is also added to the standard Itanium C++ ABI prefix on "mangled" symbol names, so that e.g. on such targets the true symbol name for a C++ variable declared as ``int cppvar;`` would be ``__Z6cppvar``; note the two underscores.)  This prefix is *not* added to the symbol names specified by the ``asm`` attribute; programmers wishing to match a C symbol name must compensate for this.
+
+For example, consider the following C code:
+
+.. code-block:: c
+
+  int var1 asm("altvar") = 1;  // "altvar" in symbol table.
+  int var2 = 1; // "_var2" in symbol table.
+
+  void func1(void) asm("altfunc");
+  void func1(void) {} // "altfunc" in symbol table.
+  void func2(void) {} // "_func2" in symbol table.
+
+Clang's implementation of this attribute is compatible with GCC's, `documented here `_.
+
+While it is possible to use this attribute to name a special symbol used internally by the compiler, such as an LLVM intrinsic, this is neither recommended nor supported and may cause the compiler to crash or miscompile.  Users who wish to gain access to intrinsic behavior are strongly encouraged to request new builtin functions.
+  }];
+}
+
 def EnumExtensibilityDocs : Documentation {
   let Category = DocCatDecl;
   let Content = [{
Index: cfe/trunk/lib/AST/Mangle.cpp
===
--- cfe/trunk/lib/AST/Mangle.cpp
+++ cfe/trunk/lib/AST/Mangle.cpp
@@ -122,15 +122,21 @@
   if (const AsmLabelAttr *ALA = D->getAttr()) {
 // If we have an asm name, then we use it as the mangling.
 
+// If the label isn't literal, or if this is an alias for an LLVM intrinsic,
+// do not add a "\01" prefix.
+if (!ALA->getIsLiteralLabel() || ALA->getLabel().startswith("llvm.")) {
+  Out << ALA->getLabel();
+  return;
+}
+
 // Adding the prefix can cause problems when one file has a "foo" and
 // another has a "\01foo". That is known to happen on ELF with the
 // tricks normally used for producing aliases (PR9177). Fortunately the
 // llvm mangler on ELF is a nop, so we can just avoid adding the \01
-// marker.  We also avoid adding the marker if this is an alias for an
-// LLVM intrinsic.
+// marker.
 char GlobalPrefix =
 getASTContext().getTargetInfo().getDataLayout().getGlobalPrefix();
-if (GlobalPrefix && !ALA->getLabel().startswith("llvm."))
+if (GlobalPrefix)
   Out << '\01'; // LLVM IR Marker for __asm("foo")

Re: r369999 - Don't lose the FoundDecl and template arguments for a DeclRefExpr in

2019-09-25 Thread Peter Collingbourne via cfe-commits
Hi Richard, it looks like this commit caused an assertion failure on the
following input:

$ cat test2.ii
# 2 "" 3
namespace a {
enum { b };
}
template  void c() {
  auto d = [](auto) {
using a::b;
b;
  };
  d(0);
}
void e() { c; }
$ clang test2.ii
clang: ../clang/lib/Sema/SemaTemplateInstantiate.cpp:2985:
llvm::PointerUnion
*clang::LocalInstantiationScope::findInstantiationOf(const clang::Decl *):
Assertion `isa(D) && "declaration not instantiated in this
scope"' failed.

Can you please take a look?

Peter

On Mon, Aug 26, 2019 at 6:04 PM Richard Smith via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: rsmith
> Date: Mon Aug 26 18:06:21 2019
> New Revision: 36
>
> URL: http://llvm.org/viewvc/llvm-project?rev=36&view=rev
> Log:
> Don't lose the FoundDecl and template arguments for a DeclRefExpr in
> TreeTransform.
>
> Modified:
> cfe/trunk/lib/Sema/TreeTransform.h
>
> Modified: cfe/trunk/lib/Sema/TreeTransform.h
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/TreeTransform.h?rev=36&r1=369998&r2=36&view=diff
>
> ==
> --- cfe/trunk/lib/Sema/TreeTransform.h (original)
> +++ cfe/trunk/lib/Sema/TreeTransform.h Mon Aug 26 18:06:21 2019
> @@ -2167,13 +2167,12 @@ public:
>ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
>  ValueDecl *VD,
>  const DeclarationNameInfo &NameInfo,
> +NamedDecl *Found,
>  TemplateArgumentListInfo *TemplateArgs) {
>  CXXScopeSpec SS;
>  SS.Adopt(QualifierLoc);
> -
> -// FIXME: loses template args.
> -
> -return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
> +return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
> +  TemplateArgs);
>}
>
>/// Build a new expression in parentheses.
> @@ -9204,6 +9203,14 @@ TreeTransform::TransformDeclRef
>if (!ND)
>  return ExprError();
>
> +  NamedDecl *Found = ND;
> +  if (E->getFoundDecl() != E->getDecl()) {
> +Found = cast_or_null(
> +getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
> +if (!Found)
> +  return ExprError();
> +  }
> +
>DeclarationNameInfo NameInfo = E->getNameInfo();
>if (NameInfo.getName()) {
>  NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
> @@ -9236,7 +9243,7 @@ TreeTransform::TransformDeclRef
>}
>
>return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
> - TemplateArgs);
> + Found, TemplateArgs);
>  }
>
>  template
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>


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


[PATCH] D66437: Sema: Create a no-op implicit cast for lvalue function conversions.

2019-09-25 Thread Peter Collingbourne via Phabricator via cfe-commits
pcc added a comment.

Ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66437



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


RE: r370123 - [preprocessor] Add an opportunity to retain excluded conditional blocks

2019-09-25 Thread Eli Friedman via cfe-commits
-Original Message-
From: cfe-commits  On Behalf Of Evgeny 
Mankov via cfe-commits
Sent: Tuesday, August 27, 2019 3:16 PM
To: cfe-commits@lists.llvm.org
Subject: [EXT] r370123 - [preprocessor] Add an opportunity to retain excluded 
conditional blocks

Added: cfe/trunk/test/Index/retain-excluded-conditional-blocks.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/retain-excluded-conditional-blocks.m?rev=370123&view=auto
==
--- cfe/trunk/test/Index/retain-excluded-conditional-blocks.m (added)
+++ cfe/trunk/test/Index/retain-excluded-conditional-blocks.m Tue Aug 27 
15:15:32 2019
@@ -0,0 +1,132 @@
+// RUN: c-index-test -retain-excluded-conditional-blocks %s | FileCheck %s
+
+#include 

Including libc headers, like stdint.h, in regression tests is not allowed. The 
compiler might not find an appropriate header if clang is built with a 
non-native default target.

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


[PATCH] D67969: [libTooling] Add `run` combinator to Stencils.

2019-09-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked 4 inline comments as done.
ymandel added a comment.

Thanks for the review!




Comment at: clang/include/clang/Tooling/Refactoring/Stencil.h:181
+/// This supports user-defined extensions to the Stencil language.
+StencilPart run(MatchConsumer C);
+

gribozavr wrote:
> ymandel wrote:
> > gribozavr wrote:
> > > We could reimplement all other stencils through `run()` and eliminate 
> > > `StencilPartInterface`. 
> > > 
> > > The idea is to make `StencilPart` contain a 
> > > `std::shared_ptr>`. Then `run()` can be 
> > > implemented as creating a `StencilPart` directly, and everything else can 
> > > be implemented in terms of `run()`.
> > > 
> > > WDYT?
> > Answering both questions together: the equality function is designed to 
> > make testing of the format-string parser feasible (or, at least, 
> > reasonable).  As is, the only reason not to do what you suggest above is 
> > exactly the equality function -- otherwise, StencilPart is just 
> > `std::shared_ptr>`.
> > 
> > I can also plausibly imagine that we'll extend the interface to include a 
> > "print" function as well at some point.  
> > 
> > However, currently the parser hasn't been upstreamed and the print function 
> > is only an idea, so it would be reasonable to drop `StencilPartInterface` 
> > and all the associated baggage and we could reinstate it later as needed.  
> > Or, if you can think of a good way to test the parser that doesn't require 
> > an equality function, that too would be convincing.
> Ilya suggested that rather than comparing objects, a better way is to compare 
> pretty-printed strings. First, it avoids the need for equality (which might 
> get used for other things), and second, test failures will be more debuggable 
> because we will have an obvious diff in the pretty printed string.
> 
> With that, I agree that `StencilPartInterface` has to stay since we are going 
> to have at least two operations.
Yes, I like that!  Pretty printing has obvious other benefits, which equality 
doesn't.  Will do in followup patch. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67969



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


r372917 - [OPENMP50]Parsing/sema support for 'implementation/vendor' context

2019-09-25 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Wed Sep 25 12:43:37 2019
New Revision: 372917

URL: http://llvm.org/viewvc/llvm-project?rev=372917&view=rev
Log:
[OPENMP50]Parsing/sema support for 'implementation/vendor' context
selector.

Added basic parsing/semantic support for
'implementation={vendor()}' context selector.

Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td
cfe/trunk/include/clang/Basic/OpenMPKinds.def
cfe/trunk/include/clang/Parse/Parser.h
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Parse/ParseOpenMP.cpp
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
cfe/trunk/test/OpenMP/declare_variant_ast_print.c
cfe/trunk/test/OpenMP/declare_variant_ast_print.cpp
cfe/trunk/test/OpenMP/declare_variant_messages.c
cfe/trunk/test/OpenMP/declare_variant_messages.cpp

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=372917&r1=372916&r2=372917&view=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Wed Sep 25 12:43:37 2019
@@ -3288,18 +3288,51 @@ def OMPDeclareVariant : Attr {
   let HasCustomParsing = 1;
   let Documentation = [OMPDeclareVariantDocs];
   let Args = [
-ExprArgument<"VariantFuncRef">
+ExprArgument<"VariantFuncRef">,
+EnumArgument<"CtxSelectorSet", "CtxSelectorSetType",
+ [ "", "implementation"
+ ],
+ [
+   "CtxSetUnknown", "CtxSetImplementation"
+ ]>,
+EnumArgument<"CtxSelector", "CtxSelectorType",
+ [ "", "vendor"
+ ],
+ [
+   "CtxUnknown", "CtxVendor"
+ ]>,
+StringArgument<"ImplVendor", 1>
   ];
   let AdditionalMembers = [{
 void printPrettyPragma(raw_ostream & OS, const PrintingPolicy &Policy)
 const {
+  assert(getCtxSelectorSet() != CtxSetUnknown &&
+ getCtxSelector() != CtxUnknown && "Unknown context selector.");
   if (const Expr *E = getVariantFuncRef()) {
 OS << "(";
 E->printPretty(OS, nullptr, Policy);
 OS << ")";
   }
   // TODO: add printing of real context selectors.
-  OS << " match(unknown={})";
+  OS << " match(";
+  switch (getCtxSelectorSet()) {
+  case CtxSetImplementation:
+OS << "implementation={";
+switch (getCtxSelector()) {
+case CtxVendor:
+  OS << "vendor(";
+  OS << getImplVendor();
+  OS << ")";
+  break;
+case CtxUnknown:
+  llvm_unreachable("Unknown context selector.");
+}
+OS << "}";
+break;
+  case CtxSetUnknown:
+llvm_unreachable("Unknown context selector set.");
+  }
+  OS << ")";
 }
   }];
 }

Modified: cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td?rev=372917&r1=372916&r2=372917&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td Wed Sep 25 12:43:37 
2019
@@ -1206,6 +1206,11 @@ def err_omp_declare_variant_no_ctx_selec
   "expected context selector in '%0' clause on 'omp declare variant' 
directive">;
 def err_omp_declare_variant_equal_expected : Error<
   "expected '=' after '%0' context selector set name on 'omp declare variant' 
directive">;
+def warn_omp_declare_variant_cs_name_expected : Warning<
+  "unknown context selector in '%0' context selector set of 'omp declare 
variant' directive, ignored">,
+  InGroup;
+def err_omp_declare_variant_item_expected : Error<
+  "expected %0 in '%1' context selector of '%2' selector set of 'omp declare 
variant' directive">;
 def warn_omp_more_one_device_type_clause : Warning<
   "more than one 'device_type' clause is specified">,
   InGroup;

Modified: cfe/trunk/include/clang/Basic/OpenMPKinds.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/OpenMPKinds.def?rev=372917&r1=372916&r2=372917&view=diff
==
--- cfe/trunk/include/clang/Basic/OpenMPKinds.def (original)
+++ cfe/trunk/include/clang/Basic/OpenMPKinds.def Wed Sep 25 12:43:37 2019
@@ -197,6 +197,9 @@
 #ifndef OPENMP_DECLARE_VARIANT_CLAUSE
 #define OPENMP_DECLARE_VARIANT_CLAUSE(Name)
 #endif
+#ifndef OPENMP_MATCH_KIND
+#define OPENMP_MATCH_KIND(Name)
+#endif
 
 // OpenMP directives.
 OPENMP_DIRECTIVE(threadprivate)
@@ -965,6 +968,11 @@ OPENMP_DEVICE_TYPE_KIND(any)
 // Clauses allowed for OpenMP directive 'declare variant'.
 OPENMP_DECLARE_VARIANT_CLAUSE(match)
 
+// Context selectors for 'match' clause.

r372918 - [libTooling][NFC] Switch StencilTest.cpp to use EXPECT_THAT_EXPECTED

2019-09-25 Thread Yitzhak Mandelbaum via cfe-commits
Author: ymandel
Date: Wed Sep 25 13:04:25 2019
New Revision: 372918

URL: http://llvm.org/viewvc/llvm-project?rev=372918&view=rev
Log:
[libTooling][NFC] Switch StencilTest.cpp to use EXPECT_THAT_EXPECTED

Summary:
Currently, some tests use homegrown matchers to handle `llvm::Expected`
values. This revision standardizes on EXPECT_THAT_EXPECTED and `HasValue`.

Reviewers: ilya-biryukov

Subscribers: cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/unittests/Tooling/StencilTest.cpp

Modified: cfe/trunk/unittests/Tooling/StencilTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Tooling/StencilTest.cpp?rev=372918&r1=372917&r2=372918&view=diff
==
--- cfe/trunk/unittests/Tooling/StencilTest.cpp (original)
+++ cfe/trunk/unittests/Tooling/StencilTest.cpp Wed Sep 25 13:04:25 2019
@@ -31,23 +31,6 @@ using stencil::dPrint;
 using stencil::ifBound;
 using stencil::text;
 
-// In tests, we can't directly match on llvm::Expected since its accessors
-// mutate the object. So, we collapse it to an Optional.
-static llvm::Optional toOptional(llvm::Expected V) {
-  if (V)
-return *V;
-  ADD_FAILURE() << "Losing error in conversion to IsSomething: "
-<< llvm::toString(V.takeError());
-  return llvm::None;
-}
-
-// A very simple matcher for llvm::Optional values.
-MATCHER_P(IsSomething, ValueMatcher, "") {
-  if (!arg)
-return false;
-  return ::testing::ExplainMatchResult(ValueMatcher, *arg, result_listener);
-}
-
 // Create a valid translation-unit from a statement.
 static std::string wrapSnippet(StringRef StatementCode) {
   return ("struct S { int field; }; auto stencil_test_snippet = []{" +
@@ -151,8 +134,8 @@ TEST_F(StencilTest, SingleStatement) {
   // Invert the if-then-else.
   auto Stencil = cat("if (!", node(Condition), ") ", statement(Else), " else ",
  statement(Then));
-  EXPECT_THAT(toOptional(Stencil.eval(StmtMatch->Result)),
-  IsSomething(Eq("if (!true) return 0; else return 1;")));
+  EXPECT_THAT_EXPECTED(Stencil.eval(StmtMatch->Result),
+   HasValue("if (!true) return 0; else return 1;"));
 }
 
 TEST_F(StencilTest, SingleStatementCallOperator) {
@@ -170,8 +153,8 @@ TEST_F(StencilTest, SingleStatementCallO
   // Invert the if-then-else.
   Stencil S = cat("if (!", node(Condition), ") ", statement(Else), " else ",
   statement(Then));
-  EXPECT_THAT(toOptional(S(StmtMatch->Result)),
-  IsSomething(Eq("if (!true) return 0; else return 1;")));
+  EXPECT_THAT_EXPECTED(S(StmtMatch->Result),
+   HasValue("if (!true) return 0; else return 1;"));
 }
 
 TEST_F(StencilTest, UnboundNode) {


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


[PATCH] D67973: [libTooling][NFC] Switch StencilTest.cpp to use EXPECT_THAT_EXPECTED

2019-09-25 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL372918: [libTooling][NFC] Switch StencilTest.cpp to use 
EXPECT_THAT_EXPECTED (authored by ymandel, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D67973?vs=221561&id=221822#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D67973

Files:
  cfe/trunk/unittests/Tooling/StencilTest.cpp


Index: cfe/trunk/unittests/Tooling/StencilTest.cpp
===
--- cfe/trunk/unittests/Tooling/StencilTest.cpp
+++ cfe/trunk/unittests/Tooling/StencilTest.cpp
@@ -31,23 +31,6 @@
 using stencil::ifBound;
 using stencil::text;
 
-// In tests, we can't directly match on llvm::Expected since its accessors
-// mutate the object. So, we collapse it to an Optional.
-static llvm::Optional toOptional(llvm::Expected V) {
-  if (V)
-return *V;
-  ADD_FAILURE() << "Losing error in conversion to IsSomething: "
-<< llvm::toString(V.takeError());
-  return llvm::None;
-}
-
-// A very simple matcher for llvm::Optional values.
-MATCHER_P(IsSomething, ValueMatcher, "") {
-  if (!arg)
-return false;
-  return ::testing::ExplainMatchResult(ValueMatcher, *arg, result_listener);
-}
-
 // Create a valid translation-unit from a statement.
 static std::string wrapSnippet(StringRef StatementCode) {
   return ("struct S { int field; }; auto stencil_test_snippet = []{" +
@@ -151,8 +134,8 @@
   // Invert the if-then-else.
   auto Stencil = cat("if (!", node(Condition), ") ", statement(Else), " else ",
  statement(Then));
-  EXPECT_THAT(toOptional(Stencil.eval(StmtMatch->Result)),
-  IsSomething(Eq("if (!true) return 0; else return 1;")));
+  EXPECT_THAT_EXPECTED(Stencil.eval(StmtMatch->Result),
+   HasValue("if (!true) return 0; else return 1;"));
 }
 
 TEST_F(StencilTest, SingleStatementCallOperator) {
@@ -170,8 +153,8 @@
   // Invert the if-then-else.
   Stencil S = cat("if (!", node(Condition), ") ", statement(Else), " else ",
   statement(Then));
-  EXPECT_THAT(toOptional(S(StmtMatch->Result)),
-  IsSomething(Eq("if (!true) return 0; else return 1;")));
+  EXPECT_THAT_EXPECTED(S(StmtMatch->Result),
+   HasValue("if (!true) return 0; else return 1;"));
 }
 
 TEST_F(StencilTest, UnboundNode) {


Index: cfe/trunk/unittests/Tooling/StencilTest.cpp
===
--- cfe/trunk/unittests/Tooling/StencilTest.cpp
+++ cfe/trunk/unittests/Tooling/StencilTest.cpp
@@ -31,23 +31,6 @@
 using stencil::ifBound;
 using stencil::text;
 
-// In tests, we can't directly match on llvm::Expected since its accessors
-// mutate the object. So, we collapse it to an Optional.
-static llvm::Optional toOptional(llvm::Expected V) {
-  if (V)
-return *V;
-  ADD_FAILURE() << "Losing error in conversion to IsSomething: "
-<< llvm::toString(V.takeError());
-  return llvm::None;
-}
-
-// A very simple matcher for llvm::Optional values.
-MATCHER_P(IsSomething, ValueMatcher, "") {
-  if (!arg)
-return false;
-  return ::testing::ExplainMatchResult(ValueMatcher, *arg, result_listener);
-}
-
 // Create a valid translation-unit from a statement.
 static std::string wrapSnippet(StringRef StatementCode) {
   return ("struct S { int field; }; auto stencil_test_snippet = []{" +
@@ -151,8 +134,8 @@
   // Invert the if-then-else.
   auto Stencil = cat("if (!", node(Condition), ") ", statement(Else), " else ",
  statement(Then));
-  EXPECT_THAT(toOptional(Stencil.eval(StmtMatch->Result)),
-  IsSomething(Eq("if (!true) return 0; else return 1;")));
+  EXPECT_THAT_EXPECTED(Stencil.eval(StmtMatch->Result),
+   HasValue("if (!true) return 0; else return 1;"));
 }
 
 TEST_F(StencilTest, SingleStatementCallOperator) {
@@ -170,8 +153,8 @@
   // Invert the if-then-else.
   Stencil S = cat("if (!", node(Condition), ") ", statement(Else), " else ",
   statement(Then));
-  EXPECT_THAT(toOptional(S(StmtMatch->Result)),
-  IsSomething(Eq("if (!true) return 0; else return 1;")));
+  EXPECT_THAT_EXPECTED(S(StmtMatch->Result),
+   HasValue("if (!true) return 0; else return 1;"));
 }
 
 TEST_F(StencilTest, UnboundNode) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68049: Propeller: Clang options for basic block sections

2019-09-25 Thread Sriraman Tallam via Phabricator via cfe-commits
tmsriram created this revision.
tmsriram added a reviewer: rnk.
Herald added a project: clang.

Options for basic block sections, unique internal linkage function names.

This is part of the Propeller framework to do post link code layout 
optimizations.  Please see the RFC here: 
https://groups.google.com/forum/#!msg/llvm-dev/ef3mKzAdJ7U/1shV64BYBAAJ and the 
detailed RFC doc here: 
https://github.com/google/llvm-propeller/blob/plo-dev/Propeller_RFC.pdf

This is one in the series of patches for Propeller.

This patch adds the following options to clang:

1. -funique-internal-funcnames : Makes function names with internal linkage 
unique (best effort).
2. -fbasicblock-sections={all, , labels, none} : Enables/Disables basic 
block sections for all or a subset of basic blocks. "labels" only enables basic 
block symbols.
3. -funique-bb-section-names:  Enables unique section names for basic block 
sections, disabled by default.
4. -mrelocate-with-symbols:  Use symbols for relocations instead of sections.
5. -fpropeller-label:  Enables all options related to Propeller for labelling 
basic blocks like basic block symbols.
6. -fpropeller-optimize=: Enables all options related to Propeller for 
optimizing like basic block sections and associated linker options.


Repository:
  rC Clang

https://reviews.llvm.org/D68049

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/CC1Options.td
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CodeGen/basicblock-sections.c
  clang/test/CodeGen/basicblock-sections.funcnames
  clang/test/CodeGen/unique_internal_funcnames.c
  clang/test/Driver/propeller-flags.c
  clang/tools/driver/cc1as_main.cpp

Index: clang/tools/driver/cc1as_main.cpp
===
--- clang/tools/driver/cc1as_main.cpp
+++ clang/tools/driver/cc1as_main.cpp
@@ -90,6 +90,7 @@
   unsigned SaveTemporaryLabels : 1;
   unsigned GenDwarfForAssembly : 1;
   unsigned RelaxELFRelocations : 1;
+  unsigned RelocateWithSymbols : 1;
   unsigned DwarfVersion;
   std::string DwarfDebugFlags;
   std::string DwarfDebugProducer;
@@ -236,6 +237,7 @@
   }
 
   Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
+  Opts.RelocateWithSymbols = Args.hasArg(OPT_mrelocate_with_symbols);
   Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
   Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
   Opts.DwarfDebugProducer = Args.getLastArgValue(OPT_dwarf_debug_producer);
@@ -361,6 +363,7 @@
   MAI->setCompressDebugSections(Opts.CompressDebugSections);
 
   MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
+  MAI->setRelocateWithSymbols(Opts.RelocateWithSymbols);
 
   bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
   if (Opts.OutputPath.empty())
Index: clang/test/Driver/propeller-flags.c
===
--- /dev/null
+++ clang/test/Driver/propeller-flags.c
@@ -0,0 +1,13 @@
+// Check that -fpropeller flag invokes the correct options.
+// RUN: %clang -### %s -target x86_64-unknown-linux -fpropeller-label -flto=thin 2>&1 | FileCheck %s -check-prefix=CHECK_PROPELLER_LABEL
+// RUN: %clang -### %s -target x86_64-unknown-linux -fpropeller-optimize=perf.propeller -flto=thin 2>&1 | FileCheck %s -check-prefix=CHECK_PROPELLER_OPT
+
+// CHECK_PROPELLER_LABEL: "-fbasicblock-sections=labels"
+// CHECK_PROPELLER_LABEL: "-funique-internal-funcnames"
+// CHECK_PROPELLER_LABEL: "--lto-basicblock-sections=labels"
+//
+// CHECK_PROPELLER_OPT: "-fbasicblock-sections=perf.propeller"
+// CHECK_PROPELLER_OPT: "-funique-internal-funcnames"
+// CHECK_PROPELLER_OPT: "--propeller=perf.propeller"
+// CHECK_PROPELLER_OPT: "--lto-basicblock-sections=perf.propeller"
+// CHECK_PROPELLER_OPT: "--optimize-bb-jumps"
Index: clang/test/CodeGen/unique_internal_funcnames.c
===
--- /dev/null
+++ clang/test/CodeGen/unique_internal_funcnames.c
@@ -0,0 +1,18 @@
+// REQUIRES: x86-registered-target
+
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -S -o - < %s | FileCheck %s --check-prefix=PLAIN
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -S -funique-internal-funcnames -fno-unique-internal-funcnames -o - < %s | FileCheck %s --check-prefix=PLAIN
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -S -funique-internal-funcnames -o - < %s | FileCheck %s --check-prefix=UNIQUE
+
+
+static int foo() {
+  return 0;
+}
+
+int (*bar()) () {
+   return foo;
+}
+
+// PLAIN: foo:
+// UNIQUE-NOT: foo:
+// UNIQUE: foo.$
Index: clang/test/CodeGen/basicblock-sections.funcnames
===
--- /dev/

r372919 - [clang-format] Modified SortIncludes and IncludeCategories to priority for sorting #includes within the Group Category.

2019-09-25 Thread Paul Hoad via cfe-commits
Author: paulhoad
Date: Wed Sep 25 13:33:01 2019
New Revision: 372919

URL: http://llvm.org/viewvc/llvm-project?rev=372919&view=rev
Log:
[clang-format] Modified SortIncludes and IncludeCategories to priority for 
sorting #includes within the Group Category.

Summary:
This new Style rule is made as a part of adding support for NetBSD KNF in 
clang-format. NetBSD have it's own priority of includes which should be 
followed while formatting NetBSD code. This style sorts the Cpp Includes 
according to the priorities of NetBSD, as mentioned in the [Style 
Guide](http://cvsweb.netbsd.org/bsdweb.cgi/src/share/misc/style?rev=HEAD&content-type=text/x-cvsweb-markup)
 The working of this Style rule shown below:

**Configuration:**
This revision introduces a new field under IncludeCategories named 
`SortPriority` which defines the priority of ordering the `#includes` and the 
`Priority` will define the categories for grouping the `#include blocks`.

Reviewers: cfe-commits, mgorny, christos, MyDeveloperDay

Reviewed By: MyDeveloperDay

Subscribers: lebedev.ri, rdwampler, christos, mgorny, krytarowski

Patch By: Manikishan

Tags: #clang, #clang-format

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

Modified:
cfe/trunk/docs/ClangFormatStyleOptions.rst
cfe/trunk/include/clang/Tooling/Inclusions/HeaderIncludes.h
cfe/trunk/include/clang/Tooling/Inclusions/IncludeStyle.h
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/lib/Tooling/Inclusions/HeaderIncludes.cpp
cfe/trunk/lib/Tooling/Inclusions/IncludeStyle.cpp
cfe/trunk/unittests/Format/SortIncludesTest.cpp

Modified: cfe/trunk/docs/ClangFormatStyleOptions.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangFormatStyleOptions.rst?rev=372919&r1=372918&r2=372919&view=diff
==
--- cfe/trunk/docs/ClangFormatStyleOptions.rst (original)
+++ cfe/trunk/docs/ClangFormatStyleOptions.rst Wed Sep 25 13:33:01 2019
@@ -1511,6 +1511,13 @@ the configuration (without a prefix: ``A
   can also assign negative priorities if you have certain headers that
   always need to be first.
 
+  There is a third and optional field ``SortPriority`` which can used while
+  ``IncludeBloks = IBS_Regroup`` to define the priority in which ``#includes``
+  should be ordered, and value of ``Priority`` defines the order of
+  ``#include blocks`` and also enables to group ``#includes`` of different
+  priority for order.``SortPriority`` is set to the value of ``Priority``
+  as default if it is not assigned.
+
   To configure this in the .clang-format file, use:
 
   .. code-block:: yaml
@@ -1518,12 +1525,14 @@ the configuration (without a prefix: ``A
 IncludeCategories:
   - Regex:   '^"(llvm|llvm-c|clang|clang-c)/'
 Priority:2
+SortPriority:2
   - Regex:   '^(<|"(gtest|gmock|isl|json)/)'
 Priority:3
   - Regex:   '<[[:alnum:].]+>'
 Priority:4
   - Regex:   '.*'
 Priority:1
+SortPriority:0
 
 **IncludeIsMainRegex** (``std::string``)
   Specify a regular expression of suffixes that are allowed in the

Modified: cfe/trunk/include/clang/Tooling/Inclusions/HeaderIncludes.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Inclusions/HeaderIncludes.h?rev=372919&r1=372918&r2=372919&view=diff
==
--- cfe/trunk/include/clang/Tooling/Inclusions/HeaderIncludes.h (original)
+++ cfe/trunk/include/clang/Tooling/Inclusions/HeaderIncludes.h Wed Sep 25 
13:33:01 2019
@@ -32,6 +32,7 @@ public:
   /// 0. Otherwise, returns the priority of the matching category or INT_MAX.
   /// NOTE: this API is not thread-safe!
   int getIncludePriority(StringRef IncludeName, bool CheckMainHeader) const;
+  int getSortIncludePriority(StringRef IncludeName, bool CheckMainHeader) 
const;
 
 private:
   bool isMainHeader(StringRef IncludeName) const;

Modified: cfe/trunk/include/clang/Tooling/Inclusions/IncludeStyle.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Inclusions/IncludeStyle.h?rev=372919&r1=372918&r2=372919&view=diff
==
--- cfe/trunk/include/clang/Tooling/Inclusions/IncludeStyle.h (original)
+++ cfe/trunk/include/clang/Tooling/Inclusions/IncludeStyle.h Wed Sep 25 
13:33:01 2019
@@ -58,6 +58,8 @@ struct IncludeStyle {
 std::string Regex;
 /// The priority to assign to this category.
 int Priority;
+/// The custom priority to sort before grouping.
+int SortPriority;
 bool operator==(const IncludeCategory &Other) const {
   return Regex == Other.Regex && Priority == Other.Priority;
 }

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=372919&r1=372918&r2=372919&view=diff

[PATCH] D64695: [clang-format] Modified SortIncludes and IncludeCategories to priority for sorting #includes within the Group Category.

2019-09-25 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL372919: [clang-format] Modified SortIncludes and 
IncludeCategories to priority for… (authored by paulhoad, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D64695?vs=216576&id=221828#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D64695

Files:
  cfe/trunk/docs/ClangFormatStyleOptions.rst
  cfe/trunk/include/clang/Tooling/Inclusions/HeaderIncludes.h
  cfe/trunk/include/clang/Tooling/Inclusions/IncludeStyle.h
  cfe/trunk/lib/Format/Format.cpp
  cfe/trunk/lib/Tooling/Inclusions/HeaderIncludes.cpp
  cfe/trunk/lib/Tooling/Inclusions/IncludeStyle.cpp
  cfe/trunk/unittests/Format/SortIncludesTest.cpp

Index: cfe/trunk/lib/Format/Format.cpp
===
--- cfe/trunk/lib/Format/Format.cpp
+++ cfe/trunk/lib/Format/Format.cpp
@@ -1771,6 +1771,7 @@
   StringRef Text;
   unsigned Offset;
   int Category;
+  int Priority;
 };
 
 struct JavaImportDirective {
@@ -1834,6 +1835,7 @@
 ArrayRef Ranges, StringRef FileName,
 StringRef Code, tooling::Replacements &Replaces,
 unsigned *Cursor) {
+  tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
   unsigned IncludesBeginOffset = Includes.front().Offset;
   unsigned IncludesEndOffset =
   Includes.back().Offset + Includes.back().Text.size();
@@ -1841,11 +1843,12 @@
   if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
 return;
   SmallVector Indices;
-  for (unsigned i = 0, e = Includes.size(); i != e; ++i)
+  for (unsigned i = 0, e = Includes.size(); i != e; ++i) {
 Indices.push_back(i);
+  }
   llvm::stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
-return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
-   std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
+return std::tie(Includes[LHSI].Priority, Includes[LHSI].Filename) <
+   std::tie(Includes[RHSI].Priority, Includes[RHSI].Filename);
   });
   // The index of the include on which the cursor will be put after
   // sorting/deduplicating.
@@ -1960,9 +1963,12 @@
 int Category = Categories.getIncludePriority(
 IncludeName,
 /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
+int Priority = Categories.getSortIncludePriority(
+IncludeName, !MainIncludeFound && FirstIncludeBlock);
 if (Category == 0)
   MainIncludeFound = true;
-IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
+IncludesInBlock.push_back(
+{IncludeName, Line, Prev, Category, Priority});
   } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
 sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code,
 Replaces, Cursor);
Index: cfe/trunk/lib/Tooling/Inclusions/IncludeStyle.cpp
===
--- cfe/trunk/lib/Tooling/Inclusions/IncludeStyle.cpp
+++ cfe/trunk/lib/Tooling/Inclusions/IncludeStyle.cpp
@@ -17,6 +17,7 @@
 IO &IO, IncludeStyle::IncludeCategory &Category) {
   IO.mapOptional("Regex", Category.Regex);
   IO.mapOptional("Priority", Category.Priority);
+  IO.mapOptional("SortPriority", Category.SortPriority);
 }
 
 void ScalarEnumerationTraits::enumeration(
Index: cfe/trunk/lib/Tooling/Inclusions/HeaderIncludes.cpp
===
--- cfe/trunk/lib/Tooling/Inclusions/HeaderIncludes.cpp
+++ cfe/trunk/lib/Tooling/Inclusions/HeaderIncludes.cpp
@@ -199,6 +199,20 @@
   return Ret;
 }
 
+int IncludeCategoryManager::getSortIncludePriority(StringRef IncludeName,
+   bool CheckMainHeader) const {
+  int Ret = INT_MAX;
+  for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
+if (CategoryRegexs[i].match(IncludeName)) {
+  Ret = Style.IncludeCategories[i].SortPriority;
+  if (Ret == 0)
+Ret = Style.IncludeCategories[i].Priority;
+  break;
+}
+  if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
+Ret = 0;
+  return Ret;
+}
 bool IncludeCategoryManager::isMainHeader(StringRef IncludeName) const {
   if (!IncludeName.startswith("\""))
 return false;
Index: cfe/trunk/unittests/Format/SortIncludesTest.cpp
===
--- cfe/trunk/unittests/Format/SortIncludesTest.cpp
+++ cfe/trunk/unittests/Format/SortIncludesTest.cpp
@@ -70,6 +70,77 @@
  {tooling::Range(25, 1)}));
 }
 
+TEST_F(SortIncludesTest, SortedIncludesUsingSortPriorityAttribute) {
+  FmtStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Regroup;
+  FmtSty

[PATCH] D67837: [CUDA][HIP] Fix assertion in Sema::markKnownEmitted with -fopenmp

2019-09-25 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 221829.
yaxunl edited the summary of this revision.
yaxunl added a comment.

Unify CUDA/HIP/OpenMP host/device check.


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

https://reviews.llvm.org/D67837

Files:
  include/clang/Sema/Sema.h
  lib/Sema/SemaCUDA.cpp
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaOpenMP.cpp
  test/SemaCUDA/call-device-fn-from-host.cu
  test/SemaCUDA/host-device-constexpr.cu
  test/SemaCUDA/openmp-static-func.cu

Index: test/SemaCUDA/openmp-static-func.cu
===
--- /dev/null
+++ test/SemaCUDA/openmp-static-func.cu
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fsyntax-only \
+// RUN:-verify -fopenmp %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fsyntax-only \
+// RUN:-verify -fopenmp -x hip %s
+// expected-no-diagnostics
+
+// Tests there is no assertion in Sema::markKnownEmitted when fopenmp is used
+// with CUDA/HIP host compilation.
+
+static void f() {}
+
+static void g() { f(); }
+
+static void h() { g(); }
Index: test/SemaCUDA/host-device-constexpr.cu
===
--- test/SemaCUDA/host-device-constexpr.cu
+++ test/SemaCUDA/host-device-constexpr.cu
@@ -1,5 +1,10 @@
 // RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify -isystem %S/Inputs %s
-// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify -isystem %S/Inputs %s -fcuda-is-device
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify -isystem %S/Inputs %s \
+// RUN:-fcuda-is-device
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify -isystem %S/Inputs \
+// RUN:-fopenmp %s
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify -isystem %S/Inputs \
+// RUN:-fopenmp %s -fcuda-is-device
 
 #include "Inputs/cuda.h"
 
Index: test/SemaCUDA/call-device-fn-from-host.cu
===
--- test/SemaCUDA/call-device-fn-from-host.cu
+++ test/SemaCUDA/call-device-fn-from-host.cu
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 %s --std=c++11 -triple x86_64-unknown-linux -emit-llvm -o - \
 // RUN:   -verify -verify-ignore-unexpected=note
+// RUN: %clang_cc1 %s --std=c++11 -triple x86_64-unknown-linux -emit-llvm -o - \
+// RUN:   -verify -verify-ignore-unexpected=note -fopenmp
 
 // Note: This test won't work with -fsyntax-only, because some of these errors
 // are emitted during codegen.
Index: lib/Sema/SemaOpenMP.cpp
===
--- lib/Sema/SemaOpenMP.cpp
+++ lib/Sema/SemaOpenMP.cpp
@@ -1566,25 +1566,11 @@
 } // anonymous namespace
 
 /// Do we know that we will eventually codegen the given function?
-static FunctionEmissionStatus isKnownDeviceEmitted(Sema &S, FunctionDecl *FD) {
+static Sema::FunctionEmissionStatus isKnownDeviceEmitted(Sema &S,
+ FunctionDecl *FD) {
   assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  "Expected OpenMP device compilation.");
-  // Templates are emitted when they're instantiated.
-  if (FD->isDependentContext())
-return FunctionEmissionStatus::Discarded;
-
-  Optional DevTy =
-  OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
-  if (DevTy.hasValue())
-return (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
-   ? FunctionEmissionStatus::Discarded
-   : FunctionEmissionStatus::Emitted;
-
-  // Otherwise, the function is known-emitted if it's in our set of
-  // known-emitted functions.
-  return (S.DeviceKnownEmittedFns.count(FD) > 0)
- ? FunctionEmissionStatus::Emitted
- : FunctionEmissionStatus::Unknown;
+  return S.getEmissionStatus(FD);
 }
 
 Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
@@ -1602,7 +1588,9 @@
 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
: DeviceDiagBuilder::K_Immediate;
 break;
-  case FunctionEmissionStatus::Discarded:
+  case FunctionEmissionStatus::TemplateDiscarded:
+  case FunctionEmissionStatus::OMPDiscarded:
+  case FunctionEmissionStatus::CUDADiscarded:
 Kind = DeviceDiagBuilder::K_Nop;
 break;
   }
@@ -1611,25 +1599,11 @@
 }
 
 /// Do we know that we will eventually codegen the given function?
-static FunctionEmissionStatus isKnownHostEmitted(Sema &S, FunctionDecl *FD) {
+static Sema::FunctionEmissionStatus isKnownHostEmitted(Sema &S,
+   FunctionDecl *FD) {
   assert(S.LangOpts.OpenMP && !S.LangOpts.OpenMPIsDevice &&
  "Expected OpenMP host compilation.");
-  // In OpenMP 4.5 all the functions are host functions.
-  if (S.LangOpts.OpenMP <= 45)
-return FunctionEmissionStatus::Emitted;
-
-  Optional DevTy =
-  OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
-  if (DevTy.hasValue())
-   

[PATCH] D67978: [OpenMP 5.0] Fix user-defined mapper lookup in sema for arrays

2019-09-25 Thread Lingda Li via Phabricator via cfe-commits
lildmh marked an inline comment as done.
lildmh added a comment.

HI Alexey, the ast print test is already there. Because I didn't check the 
mapper for array type before, such code will always not report any error, and 
ast print test is correct. Codegen test belongs to the other patch I released. 
It fits that patch much better.




Comment at: lib/Sema/SemaOpenMP.cpp:14751
+assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
+Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
+  }

ABataev wrote:
> Why do you want canonical type here? I think it is wrong. It drops all 
> language sugar like typedefs etc. But typedefs are not supported in mappers, 
> right?
I didn't see that the spec says typedef is not supported in mappers, so I 
suppose it should be supported. So I think `getCanonicalType` is necessary here?


Repository:
  rC Clang

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

https://reviews.llvm.org/D67978



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


[PATCH] D67978: [OpenMP 5.0] Fix user-defined mapper lookup in sema for arrays

2019-09-25 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

In D67978#1683146 , @lildmh wrote:

> HI Alexey, the ast print test is already there. Because I didn't check the 
> mapper for array type before, such code will always not report any error, and 
> ast print test is correct. Codegen test belongs to the other patch I 
> released. It fits that patch much better.


How is this possible? If we did not have support for the array type, we could 
not have correct handling of such types in successful tests.




Comment at: lib/Sema/SemaOpenMP.cpp:14751
+assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
+Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
+  }

lildmh wrote:
> ABataev wrote:
> > Why do you want canonical type here? I think it is wrong. It drops all 
> > language sugar like typedefs etc. But typedefs are not supported in 
> > mappers, right?
> I didn't see that the spec says typedef is not supported in mappers, so I 
> suppose it should be supported. So I think `getCanonicalType` is necessary 
> here?
Do we check the canonicaL type by default, for non-array type?


Repository:
  rC Clang

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

https://reviews.llvm.org/D67978



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


[PATCH] D68052: [clang-scan-deps] Allow continuation line backslashes followed by whitespace in the dependency source minimizer

2019-09-25 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman created this revision.
arphaman added reviewers: dexonsmith, Bigcheese, kousikk, aganea.
Herald added subscribers: ributzka, tschuett, jkorous.
Herald added a project: clang.

Clang allows continuations that have whitespace between the backslash and the 
newline. This patch ensures that the dependency source minimizer can handle the 
whitespace between the backslash and the newline when looking for a line 
continuation.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D68052

Files:
  clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
  clang/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp

Index: clang/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp
===
--- clang/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp
+++ clang/unittests/Lex/DependencyDirectivesSourceMinimizerTest.cpp
@@ -157,19 +157,19 @@
 
   ASSERT_FALSE(minimizeSourceToDependencyDirectives(
   "#define MACRO(\t)\tcon \t tent\t", Out));
-  EXPECT_STREQ("#define MACRO() con \t tent\t\n", Out.data());
+  EXPECT_STREQ("#define MACRO() con \t tent\n", Out.data());
 
   ASSERT_FALSE(minimizeSourceToDependencyDirectives(
   "#define MACRO(\f)\fcon \f tent\f", Out));
-  EXPECT_STREQ("#define MACRO() con \f tent\f\n", Out.data());
+  EXPECT_STREQ("#define MACRO() con \f tent\n", Out.data());
 
   ASSERT_FALSE(minimizeSourceToDependencyDirectives(
   "#define MACRO(\v)\vcon \v tent\v", Out));
-  EXPECT_STREQ("#define MACRO() con \v tent\v\n", Out.data());
+  EXPECT_STREQ("#define MACRO() con \v tent\n", Out.data());
 
   ASSERT_FALSE(minimizeSourceToDependencyDirectives(
   "#define MACRO \t\v\f\v\t con\f\t\vtent\v\f \v", Out));
-  EXPECT_STREQ("#define MACRO con\f\t\vtent\v\n", Out.data());
+  EXPECT_STREQ("#define MACRO con\f\t\vtent\n", Out.data());
 }
 
 TEST(MinimizeSourceToDependencyDirectivesTest, DefineMultilineArgs) {
@@ -476,6 +476,17 @@
   EXPECT_STREQ("#define GUA RD\n", Out.data());
 }
 
+TEST(MinimizeSourceToDependencyDirectivesTest,
+ WhitespaceAfterLineContinuationSlash) {
+  SmallVector Out;
+
+  ASSERT_FALSE(minimizeSourceToDependencyDirectives("#define A 1 + \\  \n"
+"2 + \\\t\n"
+"3\n",
+Out));
+  EXPECT_STREQ("#define A 1 + 2 + 3\n", Out.data());
+}
+
 TEST(MinimizeSourceToDependencyDirectivesTest, PoundWarningAndError) {
   SmallVector Out;
 
Index: clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
===
--- clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
+++ clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
@@ -244,7 +244,8 @@
   }
 }
 
-static const char *reverseOverSpaces(const char *First, const char *Last) {
+static const char *reverseOverSpacesUntilFirstSpace(const char *First,
+const char *Last) {
   assert(First <= Last);
   const char *PrevLast = Last;
   while (First != Last && isHorizontalWhitespace(Last[-1])) {
@@ -254,6 +255,13 @@
   return PrevLast;
 }
 
+static const char *reverseOverSpaces(const char *First, const char *Last) {
+  assert(First <= Last);
+  while (First != Last && isHorizontalWhitespace(Last[-1]))
+--Last;
+  return Last;
+}
+
 static void skipLineComment(const char *&First, const char *const End) {
   assert(First[0] == '/' && First[1] == '/');
   First += 2;
@@ -385,7 +393,7 @@
   }
 
   // Deal with "//..." and "/*...*/".
-  append(First, reverseOverSpaces(First, Last));
+  append(First, reverseOverSpacesUntilFirstSpace(First, Last));
   First = Last;
 
   if (Last[1] == '/') {
@@ -400,15 +408,20 @@
 } while (Last != End && !isVerticalWhitespace(*Last));
 
 // Print out the string.
-if (Last == End || Last == First || Last[-1] != '\\') {
-  append(First, reverseOverSpaces(First, Last));
+const char *LastBeforeTrailingSpace = reverseOverSpaces(First, Last);
+if (Last == End || LastBeforeTrailingSpace == First ||
+LastBeforeTrailingSpace[-1] != '\\') {
+  append(First, LastBeforeTrailingSpace);
   First = Last;
   skipNewline(First, End);
   return;
 }
 
-// Print up to the backslash, backing up over spaces.
-append(First, reverseOverSpaces(First, Last - 1));
+// Print up to the backslash, backing up over spaces. Preserve at least one
+// space, as the space matters when tokens are separated by a line
+// continuation.
+append(First, reverseOverSpacesUntilFirstSpace(
+  First, LastBeforeTrailingSpace - 1));
 
 First = Last;
 skipNewline(First, End);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D65744: [PR42707][OpenCL] Fix addr space deduction for auto

2019-09-25 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:5998
+QualType Type = Var->getType();
+if (Type->isSamplerT() || Type->isVoidType())
+  return;

Anastasia wrote:
> I don't seem to need a check for dependent or auto types because the 
> substitution happens using type info rather than getting type from the 
> declaration. Not sure if I should explain it here or add the checks just in 
> case?
If you have adequate test-case coverage (both inside and out of templates) then 
I don't think you need further explanation.



Comment at: clang/lib/Sema/SemaDecl.cpp:6721
 
+  if (getLangOpts().OpenCL) {
+

Since you're moving this code anyway, can this be split into its own function?  
I'm not sure if it's actually important that some of these failures return 
immediately and some of them fall through to later checks.



Comment at: clang/lib/Sema/SemaType.cpp:7460
+  // the initializing expression type during the type deduction.
+  (T->isUndeducedAutoType() && IsPointee) ||
   // OpenCL spec v2.0 s6.9.b:

Anastasia wrote:
> rjmccall wrote:
> > Okay, I understand why you're doing this now, and it makes sense.  I would 
> > like to propose changing the entire way `deduceOpenCLImplicitAddrSpace` 
> > works.  Why don't we do it more like how ObjC ARC infers its implicit 
> > ownership qualifiers:
> > 
> > - In SemaType, we add the default address space to non-qualified, 
> > non-dependent, non-undeduced-`auto` pointees when parsing a pointer or 
> > reference type.
> > - In SemaType, we add the default address space to non-qualified pointees 
> > when building a pointer or reference type.
> > - We add the default address space at the top level when when building a 
> > variable.
> > 
> > Then all of this context-specific logic where we're looking at different 
> > declarator chunks and trying to infer the relationship of the current chunk 
> > to the overall type being parsed can just go away or get pushed into a more 
> > appropriate position.
> Ok, it mainly works, however I still need a bit of parsing horribleness when 
> deducing addr space of declarations with parenthesis  in 
> `GetFullTypeForDeclarator`. This is the case for block pointers or 
> pointers/references to arrays. It is incorrect to add address spaces on 
> ParenType while building a pointer or references so I have to detect this as 
> special case.
You can't add an address space outside a `ParenType`?  That seems odd; what 
problems are you seeing exactly?

If it's really just specific to `ParenType`, you could simply drill through 
them and then rebuild the `ParenType`s.


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

https://reviews.llvm.org/D65744



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


  1   2   >