[PATCH] D78374: [Analyzer][StreamChecker] Added evaluation of fread and fwrite.

2020-05-14 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

The indeterminate position is mentioned only at fread and fwrite. I do not know 
if it is reasonable to make the indeterminate position in other cases. Th 
indeterminate position is separate from error flags because of "clearerr" that 
clears the error flag but not the indeterminate position (if this is the right 
way of how it works), and because even **ferror** does not imply an 
indeterminate position always like after a write to a file opened in read mode. 
Then it is a detail question after what functions to set indeterminate position 
and before what functions check for it, the support for it is still needed. The 
current way of its handling seems correct to me, indeterminate position is not 
allowed before read or write but no problem before fseek (at least with an 
absolute seek value, this is not checked now).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78374



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


[PATCH] D78374: [Analyzer][StreamChecker] Added evaluation of fread and fwrite.

2020-05-14 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

We can assume that size of a file does not change by external (to the analyzed 
program) events so the **EOF** state can not disappear. (Is this true for 
`stdin`, or it has never an **EOF**?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78374



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


[PATCH] D78374: [Analyzer][StreamChecker] Added evaluation of fread and fwrite.

2020-05-14 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

Adding a state chart may help something but does not tell the full picture 
because conditions on the transitions are not trivial to indicate and follow. 
And the state chart is too complex to draw it in ASCII-art format.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78374



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


[PATCH] D79923: [clangd] Only emit default error/fatal diagnostices from included files.

2020-05-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman, jkorous, MaskRay, 
ilya-biryukov.
Herald added a project: clang.

This would avoid adding too much noise when there is a "-Wall" in the
compile command.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D79923

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp


Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1033,6 +1033,20 @@
   WithNote(Diag(Header.range(), "error occurred here");
 }
 
+TEST(DiagsInHeaders, OnlyDefaultErrorOrFatal) {
+  Annotations Main(R"cpp(
+#include [["a.h"]] // get unused "foo" warning when building preamble.
+)cpp");
+  Annotations Header(R"cpp(
+namespace { void foo() {} }
+void func() {foo();} ;)cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
+  // promote warnings to errors.
+  TU.ExtraArgs = {"-Werror", "-Wunused"};
+  EXPECT_THAT(TU.build().getDiagnostics(), IsEmpty());
+}
+
 TEST(DiagsInHeaders, FromNonWrittenSources) {
   Annotations Main(R"cpp(
 #include [["a.h"]]
Index: clang-tools-extra/clangd/Diagnostics.cpp
===
--- clang-tools-extra/clangd/Diagnostics.cpp
+++ clang-tools-extra/clangd/Diagnostics.cpp
@@ -124,7 +124,10 @@
 bool adjustDiagFromHeader(Diag &D, const clang::Diagnostic &Info,
   const LangOptions &LangOpts) {
   // We only report diagnostics with at least error severity from headers.
-  if (D.Severity < DiagnosticsEngine::Level::Error)
+  // Note that we only use the default serverity to avoid adding too much 
noise,
+  // especially there is a "-Werror" flag in the compile command.
+  if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+  Info.getID()))
 return false;
 
   const SourceManager &SM = Info.getSourceManager();
@@ -514,7 +517,8 @@
   if (Info.getLocation().isInvalid()) {
 // Handle diagnostics coming from command-line arguments. The source 
manager
 // is *not* available at this point, so we cannot use it.
-if (DiagLevel < DiagnosticsEngine::Level::Error) {
+if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+Info.getID())) {
   IgnoreDiagnostics::log(DiagLevel, Info);
   return; // non-errors add too much noise, do not show them.
 }


Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1033,6 +1033,20 @@
   WithNote(Diag(Header.range(), "error occurred here");
 }
 
+TEST(DiagsInHeaders, OnlyDefaultErrorOrFatal) {
+  Annotations Main(R"cpp(
+#include [["a.h"]] // get unused "foo" warning when building preamble.
+)cpp");
+  Annotations Header(R"cpp(
+namespace { void foo() {} }
+void func() {foo();} ;)cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
+  // promote warnings to errors.
+  TU.ExtraArgs = {"-Werror", "-Wunused"};
+  EXPECT_THAT(TU.build().getDiagnostics(), IsEmpty());
+}
+
 TEST(DiagsInHeaders, FromNonWrittenSources) {
   Annotations Main(R"cpp(
 #include [["a.h"]]
Index: clang-tools-extra/clangd/Diagnostics.cpp
===
--- clang-tools-extra/clangd/Diagnostics.cpp
+++ clang-tools-extra/clangd/Diagnostics.cpp
@@ -124,7 +124,10 @@
 bool adjustDiagFromHeader(Diag &D, const clang::Diagnostic &Info,
   const LangOptions &LangOpts) {
   // We only report diagnostics with at least error severity from headers.
-  if (D.Severity < DiagnosticsEngine::Level::Error)
+  // Note that we only use the default serverity to avoid adding too much noise,
+  // especially there is a "-Werror" flag in the compile command.
+  if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+  Info.getID()))
 return false;
 
   const SourceManager &SM = Info.getSourceManager();
@@ -514,7 +517,8 @@
   if (Info.getLocation().isInvalid()) {
 // Handle diagnostics coming from command-line arguments. The source manager
 // is *not* available at this point, so we cannot use it.
-if (DiagLevel < DiagnosticsEngine::Level::Error) {
+if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+Info.getID())) {
   IgnoreDiagnostics::log(DiagLevel, Info);
   return; // non-errors add too much noise, do not show them.
 }
___

[PATCH] D69778: Make -fmodules-codegen and -fmodules-debuginfo work also with precompiled headers

2020-05-14 Thread Luboš Luňák via Phabricator via cfe-commits
llunak added a subscriber: aganea.
llunak added a comment.

In D69778#2035318 , @dblaikie wrote:

> Do you have a sense of the larger testing that PR44953 was reduced from? Have 
> you tried compiling a non-trivial codebase (I assume you might've tested it 
> with Open Office, for instance) - wonder why PR44953 didn't show up there? 
> (perhaps just the construct needed to tickle the issue isn't common/isn't 
> common in Open Office code, etc)


I've been building LibreOffice and some of its 3rd-party dependencies such as 
Skia for months with this patch, without problems. PR44953 seems to be a corner 
case, we do not use D3DX12 headers in LO, and (I presume) __declspec(selectany) 
is a niche feature. And while I do not understand why PR44953 was happening, I 
do understand why my original patch was triggering it, and it will not happen 
with this patch (or, if it will happen, then it'll happen with modules as 
well). And I've tested with the testcase in PR44953.

(It's LibreOffice BTW, OpenOffice is anything but dead.)

> and/or maybe see if the person who filed PR44953 might be able to test this 
> version of the patch on the original codebase that bug was reduced from?

@aganea Have you tried how this version of the patch affects PR44953? If not, 
could you please try?


Repository:
  rC Clang

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

https://reviews.llvm.org/D69778



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


[PATCH] D79117: [clang] [Darwin] Add reverse mappings for aarch64/aarch64_32 to darwin arch names

2020-05-14 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

Ping @t.p.northover


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79117



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


[PATCH] D79923: [clangd] Only emit default error/fatal diagnostices from included files.

2020-05-14 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Thanks!




Comment at: clang-tools-extra/clangd/Diagnostics.cpp:127
   // We only report diagnostics with at least error severity from headers.
-  if (D.Severity < DiagnosticsEngine::Level::Error)
+  // Note that we only use the default serverity to avoid adding too much 
noise,
+  // especially there is a "-Werror" flag in the compile command.

"especially" suggests there are other cases where we we report non-default 
errors, but I'm not sure there are.

Maybe just "Use default severity to avoid noise with -Werror".


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79923



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


[PATCH] D79330: [Analyzer][VLASizeChecker] Check for VLA size overflow.

2020-05-14 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

In D79330#2033990 , @Szelethus wrote:

> > Variable-length array (VLA) should have a size that fits into a size_t 
> > value. At least if the size is queried with sizeof, but it is better (and 
> > more simple) to check it always
>
> So creating VLA larger than `sizeof(size_t)` isn't a bug, bur rather a sign 
> of code smell? Then we shouldn't create a fatal error node for it, **unless** 
> we're trying to fit it in a variable that isn't sufficiently large. The fact 
> that `sizeof`ing it is a bug wasn't immediately obvious to me either, so a 
> quote from the standard as comments would be appreciated:
>
> §6.5.3.4.4 , about 
> operator sizeof: The value of the result is implementation-defined, and its 
> type (an unsigned integer type) is `size_t`, defined in `` (and 
> other headers).


I was looking at CERT ARR32-C 

 "Ensure size arguments for variable length arrays are in a valid range". The 
VLA should not have a size that is larger than 
`std::numeric_limits::max()`, in other words "fit into a size_t value", 
or not?

Yes creating the too large VLA in itself is not a bug, only when `sizeof` is 
called on it because it can not return the correct size. A non-fatal error is a 
better option, or delay the check until the sizeof call. But probably the 
create of such a big array in itself is sign of code smell. The array actually 
does not need to be created to make the problem happen, only a sizeof call on a 
typedef-ed and too large VLA. (What does mean that "result of sizeof is 
implementation-defined"? Probably it can return not the size in bytes or 
"chars" but something other? In such a case the checker would be not correct.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79330



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


[PATCH] D72705: [analyzer] Added new checker 'alpha.unix.ErrorReturn'.

2020-05-14 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

I think this is a useful concept and it can nicely complement the ongoing 
summary based work in `StdLibraryFunctionsChecker`. Still, in my opinion, there 
are more discussions and work to be done here before we get to the final 
implementation.

Our analyzer does not reason about all paths, we try to find only ONE path 
where an error occurs. This leads to a non-trivial question: Is it an error if 
we have some paths that do not check for the return value and at least one path 
where we do?
(1) One answer could be that there is bug if we find out that we use a rotten 
file descriptor or a nullptr. But, if we don't "use" them then that is not bug. 
How do we define "use"? We could say that any function that takes the return 
value is using that, but that may lead to false positives if we cannot see into 
the function body (that function may check the value). I think we should define 
"use" in the terms of preconditions of other functions. In the previous example 
(`use(*P)`) we should be able to specify that the parameter of `use` must not 
be null and if that condition is violated only then should we diagnose the bug. 
In the CERT description we see that the different functions are related. For 
instance, we should use `fgetc` only with a valid `FILE*` that must not be 
NULL. This approach is being implemented in `StdLibraryFunctionsChecker`.

(2) On the other hand, there are cases when there is no such visible data 
dependency between the functions. E.g. the example from ERR33-C:

  size_t read_at(FILE *file, long offset,
 void *buf, size_t nbytes) {
fseek(file, offset, SEEK_SET);
return fread(buf, 1, nbytes, file);
  }

Here, there are no argument constraints to fread that may be violated by 
calling fseek! But, let's just remove the call of fread:

  size_t read_at(FILE *file, long offset,
 void *buf, size_t nbytes) {
return fseek(file, offset, SEEK_SET);
  }

The bug has gone! I suggest that we should create/describe function groups. In 
a group we would define those functions that are related. E.g. fseek, fread, 
fopen, etc. If they operate on the same stream and we can find a path where 
there is an fseek and then an fread without the return value checked then that 
is a real bug. What do you think? Maybe we should have a generic infrastructure 
that could be reused in StreamChecker?

> A problem with this approach is that it works only if the value (the return 
> value of the function) is not constrained already after the function call (at 
> least not for the error value), otherwise it will interpret (wrongly) this 
> constrainment as result of an error check branch in the code. So it is not 
> possible to make a branch with fixed error return value (if other checker do 
> this this is probably bad too). And it is not possible (?) to make a new 
> branch without constraint.
>  ...
>  For example a postCall put constraints on it if it is known that the 
> returned value is always non-negative. Or more worse, an error path is 
> generated when the return value is exactly the error return code. In the 
> mentioned case if the f function is modeled and a path is added where it has 
> return value zero the checker will "think" that there was an if (X == 0) 
> condition in the code.

In my understanding, if the return value is already constrained (to not have 
the error value) on a path that means we are "ready" on that path, i.e. we 
don't have to check again for the return value on that path. However, there may 
be other paths where we have to seek for the check.

> Generally, is it a problem if there are multiple checkers that may detect 
> same defects but with different approach? Or should the code of this checker 
> (for example) made more complicated only to filter out cases that may be 
> detected by other checkers too?

If we can avoid it then do it, but, in my opinion, that is not a problem. There 
will be one checker which finds the error first then emits an error node and 
then the analysis stops, the next checker will not find the same bug, because 
execution had already stopped. We need to define the order of the colliding 
checkers though. Actually, there is an example for such a case: D79420 
 (Note, I am not sure about non-fatal errors, 
does the analysis continue in that case?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72705



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


[clang-tools-extra] dbc9e1c - [clangd] Only emit default error/fatal diagnostices from included files.

2020-05-14 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2020-05-14T11:09:06+02:00
New Revision: dbc9e1c39aed43e6faa6b29caeed7bc5b43569f1

URL: 
https://github.com/llvm/llvm-project/commit/dbc9e1c39aed43e6faa6b29caeed7bc5b43569f1
DIFF: 
https://github.com/llvm/llvm-project/commit/dbc9e1c39aed43e6faa6b29caeed7bc5b43569f1.diff

LOG: [clangd] Only emit default error/fatal diagnostices from included files.

Summary:
This would avoid adding too much noise when there is a "-Wall" in the
compile command.

Reviewers: sammccall

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/Diagnostics.cpp
clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Diagnostics.cpp 
b/clang-tools-extra/clangd/Diagnostics.cpp
index 3558ca929798..f1fbaf4646ba 100644
--- a/clang-tools-extra/clangd/Diagnostics.cpp
+++ b/clang-tools-extra/clangd/Diagnostics.cpp
@@ -124,7 +124,9 @@ Range diagnosticRange(const clang::Diagnostic &D, const 
LangOptions &L) {
 bool adjustDiagFromHeader(Diag &D, const clang::Diagnostic &Info,
   const LangOptions &LangOpts) {
   // We only report diagnostics with at least error severity from headers.
-  if (D.Severity < DiagnosticsEngine::Level::Error)
+  // Use default severity to avoid noise with -Werror.
+  if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+  Info.getID()))
 return false;
 
   const SourceManager &SM = Info.getSourceManager();
@@ -514,7 +516,8 @@ void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level 
DiagLevel,
   if (Info.getLocation().isInvalid()) {
 // Handle diagnostics coming from command-line arguments. The source 
manager
 // is *not* available at this point, so we cannot use it.
-if (DiagLevel < DiagnosticsEngine::Level::Error) {
+if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+Info.getID())) {
   IgnoreDiagnostics::log(DiagLevel, Info);
   return; // non-errors add too much noise, do not show them.
 }

diff  --git a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp 
b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
index 3d838c78a3c5..e675d01ad59f 100644
--- a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1033,6 +1033,20 @@ TEST(DiagsInHeaders, OnlyErrorOrFatal) {
   WithNote(Diag(Header.range(), "error occurred here");
 }
 
+TEST(DiagsInHeaders, OnlyDefaultErrorOrFatal) {
+  Annotations Main(R"cpp(
+#include [["a.h"]] // get unused "foo" warning when building preamble.
+)cpp");
+  Annotations Header(R"cpp(
+namespace { void foo() {} }
+void func() {foo();} ;)cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
+  // promote warnings to errors.
+  TU.ExtraArgs = {"-Werror", "-Wunused"};
+  EXPECT_THAT(TU.build().getDiagnostics(), IsEmpty());
+}
+
 TEST(DiagsInHeaders, FromNonWrittenSources) {
   Annotations Main(R"cpp(
 #include [["a.h"]]



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


[PATCH] D79639: [SveEmitter] Builtins for SVE matrix multiply `mmla`.

2020-05-14 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen accepted this revision.
sdesmalen added a comment.
This revision is now accepted and ready to land.

LGTM!




Comment at: clang/test/CodeGen/aarch64-sve-intrinsics/acle_sve_mmla.c:17
+  // CHECK: ret  %[[RET]]
+  return SVE_ACLE_FUNC(svmmla, _s32, , )(x, y, z);
+}

nit: please remove the whitespace between the commas (to make it similar to the 
other tests)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79639



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


[PATCH] D79923: [clangd] Only emit default error/fatal diagnostices from included files.

2020-05-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 263945.
hokein marked an inline comment as done.
hokein added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79923

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp


Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1033,6 +1033,20 @@
   WithNote(Diag(Header.range(), "error occurred here");
 }
 
+TEST(DiagsInHeaders, OnlyDefaultErrorOrFatal) {
+  Annotations Main(R"cpp(
+#include [["a.h"]] // get unused "foo" warning when building preamble.
+)cpp");
+  Annotations Header(R"cpp(
+namespace { void foo() {} }
+void func() {foo();} ;)cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
+  // promote warnings to errors.
+  TU.ExtraArgs = {"-Werror", "-Wunused"};
+  EXPECT_THAT(TU.build().getDiagnostics(), IsEmpty());
+}
+
 TEST(DiagsInHeaders, FromNonWrittenSources) {
   Annotations Main(R"cpp(
 #include [["a.h"]]
Index: clang-tools-extra/clangd/Diagnostics.cpp
===
--- clang-tools-extra/clangd/Diagnostics.cpp
+++ clang-tools-extra/clangd/Diagnostics.cpp
@@ -124,7 +124,9 @@
 bool adjustDiagFromHeader(Diag &D, const clang::Diagnostic &Info,
   const LangOptions &LangOpts) {
   // We only report diagnostics with at least error severity from headers.
-  if (D.Severity < DiagnosticsEngine::Level::Error)
+  // Use default severity to avoid noise with -Werror.
+  if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+  Info.getID()))
 return false;
 
   const SourceManager &SM = Info.getSourceManager();
@@ -514,7 +516,8 @@
   if (Info.getLocation().isInvalid()) {
 // Handle diagnostics coming from command-line arguments. The source 
manager
 // is *not* available at this point, so we cannot use it.
-if (DiagLevel < DiagnosticsEngine::Level::Error) {
+if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+Info.getID())) {
   IgnoreDiagnostics::log(DiagLevel, Info);
   return; // non-errors add too much noise, do not show them.
 }


Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1033,6 +1033,20 @@
   WithNote(Diag(Header.range(), "error occurred here");
 }
 
+TEST(DiagsInHeaders, OnlyDefaultErrorOrFatal) {
+  Annotations Main(R"cpp(
+#include [["a.h"]] // get unused "foo" warning when building preamble.
+)cpp");
+  Annotations Header(R"cpp(
+namespace { void foo() {} }
+void func() {foo();} ;)cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
+  // promote warnings to errors.
+  TU.ExtraArgs = {"-Werror", "-Wunused"};
+  EXPECT_THAT(TU.build().getDiagnostics(), IsEmpty());
+}
+
 TEST(DiagsInHeaders, FromNonWrittenSources) {
   Annotations Main(R"cpp(
 #include [["a.h"]]
Index: clang-tools-extra/clangd/Diagnostics.cpp
===
--- clang-tools-extra/clangd/Diagnostics.cpp
+++ clang-tools-extra/clangd/Diagnostics.cpp
@@ -124,7 +124,9 @@
 bool adjustDiagFromHeader(Diag &D, const clang::Diagnostic &Info,
   const LangOptions &LangOpts) {
   // We only report diagnostics with at least error severity from headers.
-  if (D.Severity < DiagnosticsEngine::Level::Error)
+  // Use default severity to avoid noise with -Werror.
+  if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+  Info.getID()))
 return false;
 
   const SourceManager &SM = Info.getSourceManager();
@@ -514,7 +516,8 @@
   if (Info.getLocation().isInvalid()) {
 // Handle diagnostics coming from command-line arguments. The source manager
 // is *not* available at this point, so we cannot use it.
-if (DiagLevel < DiagnosticsEngine::Level::Error) {
+if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+Info.getID())) {
   IgnoreDiagnostics::log(DiagLevel, Info);
   return; // non-errors add too much noise, do not show them.
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D79704: [Analyzer] [NFC] Parameter Regions

2020-05-14 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h:1051
+
+  const Expr *OriginExpr;
+  unsigned Index;

baloghadamsoftware wrote:
> NoQ wrote:
> > baloghadamsoftware wrote:
> > > We do not use this at all. However, if I remove it then tests begin to 
> > > fail with strange reasons, some of them even crashes at strange points. 
> > > It seems that we need this for profiling the subclass.
> > `Profile` is completely essential. Without it different regions will be 
> > treated as if it's the same region.
> I know, that was not the question. It is the `OriginExpr` which I tried to 
> remove because I do not use it at all, except for profiling. It seems that 
> without this field the `Profile` does not work correctly.
Wait, how is it not used? You can't get the region type without `OriginExpr`.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h:1054-1055
+
+  ParamRegion(const Expr *OE, unsigned Idx, const MemRegion *SReg)
+  : TypedValueRegion(SReg, ParamRegionKind), OriginExpr(OE), Index(Idx) {}
+

baloghadamsoftware wrote:
> NoQ wrote:
> > It looks like you decided to keep `VarRegion` for the top frame.
> > 
> > I want that asserted here, in the constructor, so that never to make a 
> > mistake on this front.
> Yes, because in the top frame we neither have `CallExpr` nor `Decl`. So we 
> should assert here that we are not in the top frame, right? How do we check 
> this based on these parameters?
Yes, you did what i meant. The first assertion is redundant because `isa` is 
implied by `cast`. Let's also assert that `OE` is non-null.



Comment at: clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.cpp:197-198
+if (const ParamRegion *PR = R->getAs())
+  if (const StackArgumentsSpaceRegion *
+  stackReg = dyn_cast(PR->getMemorySpace()))
+if (stackReg->getStackFrame() == SFC)

baloghadamsoftware wrote:
> NoQ wrote:
> > Yes it is a `StackArgumentsSpaceRegion`! Because we're a parameter.
> So I can remove the inner branch?
In fact you can go even further and change the type of the overridden 
`getMemorySpace()` function to return `const StackArgumentsSpaceRegion *` 
("covariant return types") so that to drop the `cast` as well.



Comment at: clang/lib/StaticAnalyzer/Core/CallEvent.cpp:255
   // correspond to the stack frame's function declaration.
   assert(VR->getStackFrame() == SFC);
 

balazske wrote:
> Is it correct to create `VR` only to have this assert?
It's a valid pattern but it should be followed by `(void)VR;` in order to avoid 
unused variable warning in no-assert builds.



Comment at: clang/lib/StaticAnalyzer/Core/MemRegion.cpp:187
+QualType ParamRegion::getValueType() const {
+  return getDecl()->getType();
+}

This doesn't work when the callee is unknown. You need to consult the origin 
expr here.



Comment at: clang/lib/StaticAnalyzer/Core/MemRegion.cpp:191
+const ParmVarDecl *ParamRegion::getDecl() const {
+  const Decl *D = getStackFrame()->getDecl();
+

This doesn't work when the callee is unknown.



Comment at: clang/lib/StaticAnalyzer/Core/MemRegion.cpp:579
+  const ParmVarDecl *PVD = getDecl();
+  if (const IdentifierInfo *ID = PVD->getIdentifier()) {
+os << ID->getName();

`PVD` may be null.



Comment at: clang/lib/StaticAnalyzer/Core/MemRegion.cpp:1236
+  const Stmt *CallSite = SFC->getCallSite();
+  if (!CallSite)
+return getVarRegion(PVD, LC);

Let's make a stronger assertion:

```lang=c++
if (SFC->inTopFrame())
  return getVarRegion(PVD, LC);
assert(CallSite && "Destructors with parameters?");
```


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

https://reviews.llvm.org/D79704



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


[PATCH] D79923: [clangd] Only emit default error/fatal diagnostices from included files.

2020-05-14 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdbc9e1c39aed: [clangd] Only emit default error/fatal 
diagnostices from included files. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79923

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp


Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1033,6 +1033,20 @@
   WithNote(Diag(Header.range(), "error occurred here");
 }
 
+TEST(DiagsInHeaders, OnlyDefaultErrorOrFatal) {
+  Annotations Main(R"cpp(
+#include [["a.h"]] // get unused "foo" warning when building preamble.
+)cpp");
+  Annotations Header(R"cpp(
+namespace { void foo() {} }
+void func() {foo();} ;)cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
+  // promote warnings to errors.
+  TU.ExtraArgs = {"-Werror", "-Wunused"};
+  EXPECT_THAT(TU.build().getDiagnostics(), IsEmpty());
+}
+
 TEST(DiagsInHeaders, FromNonWrittenSources) {
   Annotations Main(R"cpp(
 #include [["a.h"]]
Index: clang-tools-extra/clangd/Diagnostics.cpp
===
--- clang-tools-extra/clangd/Diagnostics.cpp
+++ clang-tools-extra/clangd/Diagnostics.cpp
@@ -124,7 +124,9 @@
 bool adjustDiagFromHeader(Diag &D, const clang::Diagnostic &Info,
   const LangOptions &LangOpts) {
   // We only report diagnostics with at least error severity from headers.
-  if (D.Severity < DiagnosticsEngine::Level::Error)
+  // Use default severity to avoid noise with -Werror.
+  if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+  Info.getID()))
 return false;
 
   const SourceManager &SM = Info.getSourceManager();
@@ -514,7 +516,8 @@
   if (Info.getLocation().isInvalid()) {
 // Handle diagnostics coming from command-line arguments. The source 
manager
 // is *not* available at this point, so we cannot use it.
-if (DiagLevel < DiagnosticsEngine::Level::Error) {
+if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+Info.getID())) {
   IgnoreDiagnostics::log(DiagLevel, Info);
   return; // non-errors add too much noise, do not show them.
 }


Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1033,6 +1033,20 @@
   WithNote(Diag(Header.range(), "error occurred here");
 }
 
+TEST(DiagsInHeaders, OnlyDefaultErrorOrFatal) {
+  Annotations Main(R"cpp(
+#include [["a.h"]] // get unused "foo" warning when building preamble.
+)cpp");
+  Annotations Header(R"cpp(
+namespace { void foo() {} }
+void func() {foo();} ;)cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.AdditionalFiles = {{"a.h", std::string(Header.code())}};
+  // promote warnings to errors.
+  TU.ExtraArgs = {"-Werror", "-Wunused"};
+  EXPECT_THAT(TU.build().getDiagnostics(), IsEmpty());
+}
+
 TEST(DiagsInHeaders, FromNonWrittenSources) {
   Annotations Main(R"cpp(
 #include [["a.h"]]
Index: clang-tools-extra/clangd/Diagnostics.cpp
===
--- clang-tools-extra/clangd/Diagnostics.cpp
+++ clang-tools-extra/clangd/Diagnostics.cpp
@@ -124,7 +124,9 @@
 bool adjustDiagFromHeader(Diag &D, const clang::Diagnostic &Info,
   const LangOptions &LangOpts) {
   // We only report diagnostics with at least error severity from headers.
-  if (D.Severity < DiagnosticsEngine::Level::Error)
+  // Use default severity to avoid noise with -Werror.
+  if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+  Info.getID()))
 return false;
 
   const SourceManager &SM = Info.getSourceManager();
@@ -514,7 +516,8 @@
   if (Info.getLocation().isInvalid()) {
 // Handle diagnostics coming from command-line arguments. The source manager
 // is *not* available at this point, so we cannot use it.
-if (DiagLevel < DiagnosticsEngine::Level::Error) {
+if (!Info.getDiags()->getDiagnosticIDs()->isDefaultMappingAsError(
+Info.getID())) {
   IgnoreDiagnostics::log(DiagLevel, Info);
   return; // non-errors add too much noise, do not show them.
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D79770: [RISCV] Fix passing two floating-point values in complex separately by two GPRs on RV64

2020-05-14 Thread Alex Bradbury via Phabricator via cfe-commits
asb accepted this revision.
asb added a comment.
This revision is now accepted and ready to land.

Good catch, thanks for the fix! The logic was incorrectly written assuming 
`isFloatingType` would return false for complex values which is of course 
incorrect.




Comment at: clang/lib/CodeGen/TargetInfo.cpp:10241-10242
   // Pass floating point values via FPRs if possible.
-  if (IsFixed && Ty->isFloatingType() && FLen >= Size && ArgFPRsLeft) {
+  if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
+  FLen >= Size && ArgFPRsLeft) {
 ArgFPRsLeft--;

luismarques wrote:
> Do you have tests that show the impact of the added `FLen >= Size && 
> ArgFPRsLeft` conditions for other values besides complex floats?
That's actually not an added clause - it's just been clang-formatted onto a new 
line.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79770



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


[PATCH] D79930: [clangd] Add buildPreamble to TestTU

2020-05-14 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
Herald added subscribers: cfe-commits, usaxena95, arphaman, jkorous, MaskRay, 
ilya-biryukov.
Herald added a project: clang.

Depends on D77644 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D79930

Files:
  clang-tools-extra/clangd/unittests/PreambleTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp
  clang-tools-extra/clangd/unittests/TestTU.h


Index: clang-tools-extra/clangd/unittests/TestTU.h
===
--- clang-tools-extra/clangd/unittests/TestTU.h
+++ clang-tools-extra/clangd/unittests/TestTU.h
@@ -68,6 +68,7 @@
   // By default, build() will report Error diagnostics as GTest errors.
   // Suppress this behavior by adding an 'error-ok' comment to the code.
   ParsedAST build() const;
+  std::shared_ptr buildPreamble() const;
   ParseInputs inputs() const;
   SymbolSlab headerSymbols() const;
   std::unique_ptr index() const;
Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -65,14 +65,24 @@
   return Inputs;
 }
 
+std::shared_ptr TestTU::buildPreamble() const {
+  auto Inputs = inputs();
+  IgnoreDiagnostics Diags;
+  auto CI = buildCompilerInvocation(Inputs, Diags);
+  assert(CI && "Failed to build compilation invocation.");
+  return clang::clangd::buildPreamble(testPath(Filename), *CI, Inputs,
+  /*StoreInMemory=*/true,
+  /*PreambleCallback=*/nullptr);
+}
+
 ParsedAST TestTU::build() const {
   auto Inputs = inputs();
   StoreDiags Diags;
   auto CI = buildCompilerInvocation(Inputs, Diags);
   assert(CI && "Failed to build compilation invocation.");
-  auto Preamble =
-  buildPreamble(testPath(Filename), *CI, Inputs,
-/*StoreInMemory=*/true, /*PreambleCallback=*/nullptr);
+  auto Preamble = clang::clangd::buildPreamble(testPath(Filename), *CI, Inputs,
+   /*StoreInMemory=*/true,
+   /*PreambleCallback=*/nullptr);
   auto AST = ParsedAST::build(testPath(Filename), Inputs, std::move(CI),
   Diags.take(), Preamble);
   if (!AST.hasValue()) {
Index: clang-tools-extra/clangd/unittests/PreambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -36,35 +36,19 @@
   return arg.first() == File && arg.second == D;
 }
 
-std::shared_ptr
-createPreamble(llvm::StringRef Contents = "") {
-  auto TU = TestTU::withCode(Contents);
-  // ms-compatibility changes meaning of #import, make sure it is turned off.
-  TU.ExtraArgs = {"-fno-ms-compatibility"};
-  TU.Filename = "preamble.cpp";
-  auto PI = TU.inputs();
-  IgnoreDiagnostics Diags;
-  auto CI = buildCompilerInvocation(PI, Diags);
-  if (!CI) {
-ADD_FAILURE() << "failed to build compiler invocation";
-return nullptr;
-  }
-  if (auto Preamble = buildPreamble(TU.Filename, *CI, PI, true, nullptr))
-return Preamble;
-  ADD_FAILURE() << "failed to build preamble";
-  return nullptr;
-}
-
 // Builds a preamble for BaselineContents, patches it for ModifiedContents and
 // returns the includes in the patch.
 IncludeStructure
 collectPatchedIncludes(llvm::StringRef ModifiedContents,
llvm::StringRef BaselineContents,
llvm::StringRef MainFileName = "main.cpp") {
-  auto BaselinePreamble = createPreamble(BaselineContents);
-  // Create the patch.
-  auto TU = TestTU::withCode(ModifiedContents);
+  auto TU = TestTU::withCode(BaselineContents);
   TU.Filename = MainFileName.str();
+  // ms-compatibility changes meaning of #import, make sure it is turned off.
+  TU.ExtraArgs = {"-fno-ms-compatibility"};
+  auto BaselinePreamble = TU.buildPreamble();
+  // Create the patch.
+  TU = TestTU::withCode(ModifiedContents);
   auto PI = TU.inputs();
   auto PP = PreamblePatch::create(testPath(TU.Filename), PI, 
*BaselinePreamble);
   // Collect patch contents.


Index: clang-tools-extra/clangd/unittests/TestTU.h
===
--- clang-tools-extra/clangd/unittests/TestTU.h
+++ clang-tools-extra/clangd/unittests/TestTU.h
@@ -68,6 +68,7 @@
   // By default, build() will report Error diagnostics as GTest errors.
   // Suppress this behavior by adding an 'error-ok' comment to the code.
   ParsedAST build() const;
+  std::shared_ptr buildPreamble() const;
   ParseInputs inputs() const;
   SymbolSlab headerSymbols() const;
   std::unique_ptr index() const;
Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/un

[PATCH] D79918: [clangd] Don't create as much garbage while building Dex index.

2020-05-14 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 263961.
sammccall added a comment.

Address comments, add more docs.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79918

Files:
  clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp
  clang-tools-extra/clangd/index/dex/Dex.cpp
  clang-tools-extra/clangd/index/dex/Trigram.cpp
  clang-tools-extra/clangd/index/dex/Trigram.h
  clang-tools-extra/clangd/test/Inputs/requests.json
  clang-tools-extra/clangd/unittests/DexTests.cpp

Index: clang-tools-extra/clangd/unittests/DexTests.cpp
===
--- clang-tools-extra/clangd/unittests/DexTests.cpp
+++ clang-tools-extra/clangd/unittests/DexTests.cpp
@@ -366,38 +366,46 @@
   return tokensAre(Trigrams, Token::Kind::Trigram);
 }
 
+std::vector identifierTrigramTokens(llvm::StringRef S) {
+  std::vector Trigrams;
+  generateIdentifierTrigrams(S, Trigrams);
+  std::vector Tokens;
+  for (Trigram T : Trigrams)
+Tokens.emplace_back(Token::Kind::Trigram, T.str());
+  return Tokens;
+}
+
 TEST(DexTrigrams, IdentifierTrigrams) {
-  EXPECT_THAT(generateIdentifierTrigrams("X86"),
-  trigramsAre({"x86", "x", "x8"}));
+  EXPECT_THAT(identifierTrigramTokens("X86"), trigramsAre({"x86", "x", "x8"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("nl"), trigramsAre({"nl", "n"}));
+  EXPECT_THAT(identifierTrigramTokens("nl"), trigramsAre({"nl", "n"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("n"), trigramsAre({"n"}));
+  EXPECT_THAT(identifierTrigramTokens("n"), trigramsAre({"n"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("clangd"),
+  EXPECT_THAT(identifierTrigramTokens("clangd"),
   trigramsAre({"c", "cl", "cla", "lan", "ang", "ngd"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("abc_def"),
+  EXPECT_THAT(identifierTrigramTokens("abc_def"),
   trigramsAre({"a", "ab", "ad", "abc", "abd", "ade", "bcd", "bde",
"cde", "def"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("a_b_c_d_e_"),
+  EXPECT_THAT(identifierTrigramTokens("a_b_c_d_e_"),
   trigramsAre({"a", "a_", "ab", "abc", "bcd", "cde"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("unique_ptr"),
+  EXPECT_THAT(identifierTrigramTokens("unique_ptr"),
   trigramsAre({"u", "un", "up", "uni", "unp", "upt", "niq", "nip",
"npt", "iqu", "iqp", "ipt", "que", "qup", "qpt",
"uep", "ept", "ptr"}));
 
   EXPECT_THAT(
-  generateIdentifierTrigrams("TUDecl"),
+  identifierTrigramTokens("TUDecl"),
   trigramsAre({"t", "tu", "td", "tud", "tde", "ude", "dec", "ecl"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("IsOK"),
+  EXPECT_THAT(identifierTrigramTokens("IsOK"),
   trigramsAre({"i", "is", "io", "iso", "iok", "sok"}));
 
   EXPECT_THAT(
-  generateIdentifierTrigrams("abc_defGhij__klm"),
+  identifierTrigramTokens("abc_defGhij__klm"),
   trigramsAre({"a",   "ab",  "ad",  "abc", "abd", "ade", "adg", "bcd",
"bde", "bdg", "cde", "cdg", "def", "deg", "dgh", "dgk",
"efg", "egh", "egk", "fgh", "fgk", "ghi", "ghk", "gkl",
Index: clang-tools-extra/clangd/test/Inputs/requests.json
===
--- clang-tools-extra/clangd/test/Inputs/requests.json
+++ clang-tools-extra/clangd/test/Inputs/requests.json
@@ -1,7 +1,7 @@
-[{"Limit":100,"ProximityPaths":["/usr/home/user/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp"],"Query":"OMP","RestrictForCodeCompletion":true,"Scopes":["clang::"], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"s","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"sy","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"sys","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"sys","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"Dex","RestrictForCodeCompletion":true,"Scopes":["clang::clangd::", "clang::", "clang::clangd::dex::"],"AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"Variable","RestrictForCodeCompletion":true,"Scopes":[""], "AnyScope":false}]
+[{"Limit":100,"ProximityPaths":["/usr/home/user/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp"],"Query":"OMP","RestrictForCodeCompletion":true,"Scopes":["clang::"], "AnyScope":false, "PreferredTypes":[]},
+{"Limit":100,"ProximityPaths":[],"Query":"s","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false, "PreferredTypes":[]},
+{"Limit":100,"ProximityPaths":[],"Query":"sy","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false, "PreferredTypes":[]},
+{"Limit":100,"Proxi

[PATCH] D72705: [analyzer] Added new checker 'alpha.unix.ErrorReturn'.

2020-05-14 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

Probably we have different pre-conceptions about this checker. One thing is to 
discover the error by finding a violated precondition or other bug that is 
caused by the wrong return value of the called and failed function. This is 
case (1) above if I am correct. Other way is to discover the error by checking 
the state of an object that a function manipulates and find use of the object 
when it is in bad state. This is the case (2) above if I am correct. These are 
things that are done by other checkers partially already now. Case (1) is job 
of `StdLibraryFunctionsChecker` or other checkers, maybe any check for use of 
zero pointers. Case (2) is job of `StreamChecker` and similar checkers that 
maintain state of some object or "handle". For many of the functions in ERR33-C 
no such checker exists yet and it would be very much work do make all of these 
(or not possible at all).

This change is doing another approach: It checks directly the value that is 
returned from a function that may fail, not the object that the function 
manipulates. The goal is to check if the return value of a function is checked 
in the code. This may be discovered when the value is passed to a next function 
call and the precondition of that function is violated but this is not the goal 
of this checker. It tries to find an execution path where the returned value is 
used in the code in a way that is said to be an //error check//, or in a way 
that is an //other use//. The //error check// is discovered by checking the 
statement where the value appears to discover if it is compared against an 
error code (specific to the called function that produced the value).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72705



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


[PATCH] D79932: [analyzer] Modernize analyzer's Python scripts

2020-05-14 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, dcoughlin.
Herald added subscribers: cfe-commits, ASDenysPetrov, Charusso, dkrupp, 
donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, 
xazax.hun.
Herald added a project: clang.
vsavchenko updated this revision to Diff 263963.
vsavchenko added a comment.

Add more 'super' clean-ups


Fix read/write in binary format, which crashes Python 3.
Additionally, clean up redundant (as for Python 3) code and
fix a handful of flake8 warnings.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D79932

Files:
  clang/utils/analyzer/CmpRuns.py
  clang/utils/analyzer/SATestAdd.py
  clang/utils/analyzer/SATestBuild.py
  clang/utils/analyzer/SATestUpdateDiffs.py
  clang/utils/analyzer/SATestUtils.py
  clang/utils/analyzer/SumTimerInfo.py
  clang/utils/analyzer/exploded-graph-rewriter.py

Index: clang/utils/analyzer/exploded-graph-rewriter.py
===
--- clang/utils/analyzer/exploded-graph-rewriter.py
+++ clang/utils/analyzer/exploded-graph-rewriter.py
@@ -34,7 +34,7 @@
 
 
 # Represents any program state trait that is a dictionary of key-value pairs.
-class GenericMap(object):
+class GenericMap:
 def __init__(self, items):
 self.generic_map = collections.OrderedDict(items)
 
@@ -47,9 +47,8 @@
 
 
 # A deserialized source location.
-class SourceLocation(object):
+class SourceLocation:
 def __init__(self, json_loc):
-super(SourceLocation, self).__init__()
 logging.debug('json: %s' % json_loc)
 self.line = json_loc['line']
 self.col = json_loc['column']
@@ -63,9 +62,8 @@
 
 
 # A deserialized program point.
-class ProgramPoint(object):
+class ProgramPoint:
 def __init__(self, json_pp):
-super(ProgramPoint, self).__init__()
 self.kind = json_pp['kind']
 self.tag = json_pp['tag']
 self.node_id = json_pp['node_id']
@@ -90,9 +88,8 @@
 
 
 # A single expression acting as a key in a deserialized Environment.
-class EnvironmentBindingKey(object):
+class EnvironmentBindingKey:
 def __init__(self, json_ek):
-super(EnvironmentBindingKey, self).__init__()
 # CXXCtorInitializer is not a Stmt!
 self.stmt_id = json_ek['stmt_id'] if 'stmt_id' in json_ek \
 else json_ek['init_id']
@@ -110,9 +107,8 @@
 
 
 # Deserialized description of a location context.
-class LocationContext(object):
+class LocationContext:
 def __init__(self, json_frame):
-super(LocationContext, self).__init__()
 self.lctx_id = json_frame['lctx_id']
 self.caption = json_frame['location_context']
 self.decl = json_frame['calling']
@@ -131,9 +127,8 @@
 
 # A group of deserialized Environment bindings that correspond to a specific
 # location context.
-class EnvironmentFrame(object):
+class EnvironmentFrame:
 def __init__(self, json_frame):
-super(EnvironmentFrame, self).__init__()
 self.location_context = LocationContext(json_frame)
 self.bindings = collections.OrderedDict(
 [(EnvironmentBindingKey(b),
@@ -150,9 +145,8 @@
 
 # A deserialized Environment. This class can also hold other entities that
 # are similar to Environment, such as Objects Under Construction.
-class GenericEnvironment(object):
+class GenericEnvironment:
 def __init__(self, json_e):
-super(GenericEnvironment, self).__init__()
 self.frames = [EnvironmentFrame(f) for f in json_e]
 
 def diff_frames(self, prev):
@@ -181,9 +175,8 @@
 
 
 # A single binding key in a deserialized RegionStore cluster.
-class StoreBindingKey(object):
+class StoreBindingKey:
 def __init__(self, json_sk):
-super(StoreBindingKey, self).__init__()
 self.kind = json_sk['kind']
 self.offset = json_sk['offset']
 
@@ -198,9 +191,8 @@
 
 
 # A single cluster of the deserialized RegionStore.
-class StoreCluster(object):
+class StoreCluster:
 def __init__(self, json_sc):
-super(StoreCluster, self).__init__()
 self.base_region = json_sc['cluster']
 self.bindings = collections.OrderedDict(
 [(StoreBindingKey(b), b['value']) for b in json_sc['items']])
@@ -214,9 +206,8 @@
 
 
 # A deserialized RegionStore.
-class Store(object):
+class Store:
 def __init__(self, json_s):
-super(Store, self).__init__()
 self.ptr = json_s['pointer']
 self.clusters = collections.OrderedDict(
 [(c['pointer'], StoreCluster(c)) for c in json_s['items']])
@@ -235,9 +226,8 @@
 
 # Deserialized messages from a single checker in a single program state.
 # Basically a list of raw strings.
-class CheckerLines(object):
+class CheckerLines:
 def __init__(self, json_lines):
-super(CheckerLines, self).__init__()
 self.lines = json_lines
 
 def diff_lines(self, prev):
@@ -250,9 +240,8 @@
 
 
 # Deserialized messages of all checkers, separated by checker.
-clas

[PATCH] D79932: [analyzer] Modernize analyzer's Python scripts

2020-05-14 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 263963.
vsavchenko added a comment.

Add more 'super' clean-ups


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79932

Files:
  clang/utils/analyzer/CmpRuns.py
  clang/utils/analyzer/SATestAdd.py
  clang/utils/analyzer/SATestBuild.py
  clang/utils/analyzer/SATestUpdateDiffs.py
  clang/utils/analyzer/SATestUtils.py
  clang/utils/analyzer/SumTimerInfo.py
  clang/utils/analyzer/exploded-graph-rewriter.py

Index: clang/utils/analyzer/exploded-graph-rewriter.py
===
--- clang/utils/analyzer/exploded-graph-rewriter.py
+++ clang/utils/analyzer/exploded-graph-rewriter.py
@@ -34,7 +34,7 @@
 
 
 # Represents any program state trait that is a dictionary of key-value pairs.
-class GenericMap(object):
+class GenericMap:
 def __init__(self, items):
 self.generic_map = collections.OrderedDict(items)
 
@@ -47,9 +47,8 @@
 
 
 # A deserialized source location.
-class SourceLocation(object):
+class SourceLocation:
 def __init__(self, json_loc):
-super(SourceLocation, self).__init__()
 logging.debug('json: %s' % json_loc)
 self.line = json_loc['line']
 self.col = json_loc['column']
@@ -63,9 +62,8 @@
 
 
 # A deserialized program point.
-class ProgramPoint(object):
+class ProgramPoint:
 def __init__(self, json_pp):
-super(ProgramPoint, self).__init__()
 self.kind = json_pp['kind']
 self.tag = json_pp['tag']
 self.node_id = json_pp['node_id']
@@ -90,9 +88,8 @@
 
 
 # A single expression acting as a key in a deserialized Environment.
-class EnvironmentBindingKey(object):
+class EnvironmentBindingKey:
 def __init__(self, json_ek):
-super(EnvironmentBindingKey, self).__init__()
 # CXXCtorInitializer is not a Stmt!
 self.stmt_id = json_ek['stmt_id'] if 'stmt_id' in json_ek \
 else json_ek['init_id']
@@ -110,9 +107,8 @@
 
 
 # Deserialized description of a location context.
-class LocationContext(object):
+class LocationContext:
 def __init__(self, json_frame):
-super(LocationContext, self).__init__()
 self.lctx_id = json_frame['lctx_id']
 self.caption = json_frame['location_context']
 self.decl = json_frame['calling']
@@ -131,9 +127,8 @@
 
 # A group of deserialized Environment bindings that correspond to a specific
 # location context.
-class EnvironmentFrame(object):
+class EnvironmentFrame:
 def __init__(self, json_frame):
-super(EnvironmentFrame, self).__init__()
 self.location_context = LocationContext(json_frame)
 self.bindings = collections.OrderedDict(
 [(EnvironmentBindingKey(b),
@@ -150,9 +145,8 @@
 
 # A deserialized Environment. This class can also hold other entities that
 # are similar to Environment, such as Objects Under Construction.
-class GenericEnvironment(object):
+class GenericEnvironment:
 def __init__(self, json_e):
-super(GenericEnvironment, self).__init__()
 self.frames = [EnvironmentFrame(f) for f in json_e]
 
 def diff_frames(self, prev):
@@ -181,9 +175,8 @@
 
 
 # A single binding key in a deserialized RegionStore cluster.
-class StoreBindingKey(object):
+class StoreBindingKey:
 def __init__(self, json_sk):
-super(StoreBindingKey, self).__init__()
 self.kind = json_sk['kind']
 self.offset = json_sk['offset']
 
@@ -198,9 +191,8 @@
 
 
 # A single cluster of the deserialized RegionStore.
-class StoreCluster(object):
+class StoreCluster:
 def __init__(self, json_sc):
-super(StoreCluster, self).__init__()
 self.base_region = json_sc['cluster']
 self.bindings = collections.OrderedDict(
 [(StoreBindingKey(b), b['value']) for b in json_sc['items']])
@@ -214,9 +206,8 @@
 
 
 # A deserialized RegionStore.
-class Store(object):
+class Store:
 def __init__(self, json_s):
-super(Store, self).__init__()
 self.ptr = json_s['pointer']
 self.clusters = collections.OrderedDict(
 [(c['pointer'], StoreCluster(c)) for c in json_s['items']])
@@ -235,9 +226,8 @@
 
 # Deserialized messages from a single checker in a single program state.
 # Basically a list of raw strings.
-class CheckerLines(object):
+class CheckerLines:
 def __init__(self, json_lines):
-super(CheckerLines, self).__init__()
 self.lines = json_lines
 
 def diff_lines(self, prev):
@@ -250,9 +240,8 @@
 
 
 # Deserialized messages of all checkers, separated by checker.
-class CheckerMessages(object):
+class CheckerMessages:
 def __init__(self, json_m):
-super(CheckerMessages, self).__init__()
 self.items = collections.OrderedDict(
 [(m['checker'], CheckerLines(m['messages'])) for m in json_m])
 
@@ -269,9 +258,8 @@
 
 
 # A deserialized program state.
-class ProgramState(object):
+class ProgramSt

[PATCH] D79935: [clang-format] [PR44345] Long namespace closing comment is duplicated endlessly

2020-05-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay created this revision.
MyDeveloperDay added reviewers: krasimir, JakeMerdichAMD, mitchell-stellar, 
sammccall, curdeius.
MyDeveloperDay added projects: clang, clang-format.

https://bugs.llvm.org/show_bug.cgi?id=44345

When namespaces get long the namespace end comment wraps onto the next line

  namespace 
would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::
  went::mad::now {
  void foo();
  void bar();
  } // namespace
// 
would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::went::mad::now

If clang-format it applied successively it will duplicate the end comment

  namespace 
would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::
  went::mad::now {
  void foo();
  void bar();
  } // namespace
// 
would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::went::mad::now
// 
would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::went::mad::now

This revision checks to ensure the end comment is not on the next line before 
adding yet another comment


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D79935

Files:
  clang/lib/Format/NamespaceEndCommentsFixer.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -15849,6 +15849,74 @@
   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
 }
 
+TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
+  // These tests are not in NamespaceFixer because that doesn't
+  // test its interaction with line wrapping
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 80;
+  verifyFormat("namespace {\n"
+   "int i;\n"
+   "int j;\n"
+   "} // namespace",
+   Style);
+
+  verifyFormat("namespace AAA {\n"
+   "int i;\n"
+   "int j;\n"
+   "} // namespace AAA",
+   Style);
+
+  EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
+"int i;\n"
+"int j;\n"
+"} // namespace Averyveryveryverylongnamespace",
+format("namespace Averyveryveryverylongnamespace {\n"
+   "int i;\n"
+   "int j;\n"
+   "}",
+   Style));
+
+  EXPECT_EQ(
+  "namespace "
+  "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
+  "went::mad::now {\n"
+  "int i;\n"
+  "int j;\n"
+  "} // namespace\n"
+  "  // "
+  "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
+  "went::mad::now",
+  format("namespace "
+ "would::it::save::you::a::lot::of::time::if_::i::"
+ "just::gave::up::and_::went::mad::now {\n"
+ "int i;\n"
+ "int j;\n"
+ "}",
+ Style));
+
+  // This used to duplicate the comment again and again on subsequent runs
+  EXPECT_EQ(
+  "namespace "
+  "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
+  "went::mad::now {\n"
+  "int i;\n"
+  "int j;\n"
+  "} // namespace\n"
+  "  // "
+  "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
+  "went::mad::now",
+  format("namespace "
+ "would::it::save::you::a::lot::of::time::if_::i::"
+ "just::gave::up::and_::went::mad::now {\n"
+ "int i;\n"
+ "int j;\n"
+ "} // namespace\n"
+ "  // "
+ "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
+ "and_::went::mad::now",
+ Style));
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/NamespaceEndCommentsFixer.cpp
===
--- clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -121,7 +121,25 @@
   // Named namespace comments must not mention anonymous namespace.
   if (!NamespaceName.empty() && !AnonymousInComment.empty())
 return false;
-  return NamespaceNameInComment == NamespaceName;
+  if (NamespaceNameInComment == NamespaceName)
+return true;
+
+  // has namespace comment flowed onto the next line
+  // } // namespace
+  //   // verylongnamespacenamethatdidnotfitonthepreviouscommenline
+  if (!(Comment->Next && Comment->Next->is(TT_LineComment)))
+return false;
+
+  static const llvm::Regex CommentPattern = llvm::Regex(
+  "^/[/*] *( +([a-zA-Z0-9:_]+))?\\.? *(\\*/)?$", llvm::Regex::IgnoreCase);
+
+  // Pull out just the comment text
+  if (!CommentPattern.match(Comment->Next->TokenText, &Groups)) {
+return false;
+  }
+  NamespaceNameInComment = Groups.size() > 2 ? Groups[2] : "";
+
+  return (NamespaceNameInComment == NamespaceName);
 }
 
 voi

[PATCH] D79921: [OpenMP] Fix omp and clang pragmas

2020-05-14 Thread ISHIGURO, Hiroshi via Phabricator via cfe-commits
hishiguro updated this revision to Diff 263964.
hishiguro added a comment.

Fix clang-format error.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79921

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp


Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -1730,9 +1730,22 @@
   auto CondBlock = createBasicBlock("omp.inner.for.cond");
   EmitBlock(CondBlock);
   const SourceRange R = S.getSourceRange();
-  LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
- SourceLocToDebugLoc(R.getEnd()));
 
+  // If attributes are attached, push to the basic block with them.
+  const AttributedStmt *AS = nullptr;
+  if (auto *OMPD = dyn_cast(&S)) {
+const CapturedStmt *CS = OMPD->getCapturedStmt(OMPD_parallel);
+const Stmt *SS = CS->getCapturedStmt();
+AS = dyn_cast_or_null(SS);
+  }
+  if (AS)
+LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(),
+   AS->getAttrs(), SourceLocToDebugLoc(R.getBegin()),
+   SourceLocToDebugLoc(R.getEnd()));
+  else
+LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
+   SourceLocToDebugLoc(R.getEnd()));
+
   // If there are any cleanups between here and the loop-exit scope,
   // create a block to stage a loop exit along.
   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();


Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -1730,9 +1730,22 @@
   auto CondBlock = createBasicBlock("omp.inner.for.cond");
   EmitBlock(CondBlock);
   const SourceRange R = S.getSourceRange();
-  LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
- SourceLocToDebugLoc(R.getEnd()));
 
+  // If attributes are attached, push to the basic block with them.
+  const AttributedStmt *AS = nullptr;
+  if (auto *OMPD = dyn_cast(&S)) {
+const CapturedStmt *CS = OMPD->getCapturedStmt(OMPD_parallel);
+const Stmt *SS = CS->getCapturedStmt();
+AS = dyn_cast_or_null(SS);
+  }
+  if (AS)
+LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(),
+   AS->getAttrs(), SourceLocToDebugLoc(R.getBegin()),
+   SourceLocToDebugLoc(R.getEnd()));
+  else
+LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()),
+   SourceLocToDebugLoc(R.getEnd()));
+
   // If there are any cleanups between here and the loop-exit scope,
   // create a block to stage a loop exit along.
   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D79704: [Analyzer] [NFC] Parameter Regions

2020-05-14 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware marked an inline comment as done.
baloghadamsoftware added a comment.

Good news: I executed an analysis with all open-source checks enabled for 
several open-source projects: //BitCoint//, //CURL//, //OpenSSL//, 
//PostGreS//, //TMux//, //Xerces// using the patched and the non-patched 
version of //Clang//. There is no difference in the set of bug reports. Only 
one error message became more detailed for //BitCoin// which uses //Boost//: 
instead of `Potential memory leak` I get `Potential leak of memory pointed to 
by 'Finder.m_Pred.m_Storage.m_dynSet'` in line `135` of //Boost// header 
`algorithm/string/detail/classification.hpp` and almost the same without 
`Finder.` in line 139.




Comment at: clang/lib/StaticAnalyzer/Core/MemRegion.cpp:191
+const ParmVarDecl *ParamRegion::getDecl() const {
+  const Decl *D = getStackFrame()->getDecl();
+

NoQ wrote:
> This doesn't work when the callee is unknown.
Please give me an example where the callee is unknown. As I wrote, originally I 
put a `getExpr()` method here as well and `getType()` fell back to it if it 
could not find the `Decl()`. However, it was never invoked on the whole test 
suite. (I put an `assert(false)` into it, and did not get a crash.


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

https://reviews.llvm.org/D79704



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


[PATCH] D79918: [clangd] Don't create as much garbage while building Dex index.

2020-05-14 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 263967.
sammccall added a comment.

Use a faster hash function, which seems to be worth something in the 
neighbourhood of 4%.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79918

Files:
  clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp
  clang-tools-extra/clangd/index/dex/Dex.cpp
  clang-tools-extra/clangd/index/dex/Trigram.cpp
  clang-tools-extra/clangd/index/dex/Trigram.h
  clang-tools-extra/clangd/test/Inputs/requests.json
  clang-tools-extra/clangd/unittests/DexTests.cpp

Index: clang-tools-extra/clangd/unittests/DexTests.cpp
===
--- clang-tools-extra/clangd/unittests/DexTests.cpp
+++ clang-tools-extra/clangd/unittests/DexTests.cpp
@@ -366,38 +366,46 @@
   return tokensAre(Trigrams, Token::Kind::Trigram);
 }
 
+std::vector identifierTrigramTokens(llvm::StringRef S) {
+  std::vector Trigrams;
+  generateIdentifierTrigrams(S, Trigrams);
+  std::vector Tokens;
+  for (Trigram T : Trigrams)
+Tokens.emplace_back(Token::Kind::Trigram, T.str());
+  return Tokens;
+}
+
 TEST(DexTrigrams, IdentifierTrigrams) {
-  EXPECT_THAT(generateIdentifierTrigrams("X86"),
-  trigramsAre({"x86", "x", "x8"}));
+  EXPECT_THAT(identifierTrigramTokens("X86"), trigramsAre({"x86", "x", "x8"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("nl"), trigramsAre({"nl", "n"}));
+  EXPECT_THAT(identifierTrigramTokens("nl"), trigramsAre({"nl", "n"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("n"), trigramsAre({"n"}));
+  EXPECT_THAT(identifierTrigramTokens("n"), trigramsAre({"n"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("clangd"),
+  EXPECT_THAT(identifierTrigramTokens("clangd"),
   trigramsAre({"c", "cl", "cla", "lan", "ang", "ngd"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("abc_def"),
+  EXPECT_THAT(identifierTrigramTokens("abc_def"),
   trigramsAre({"a", "ab", "ad", "abc", "abd", "ade", "bcd", "bde",
"cde", "def"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("a_b_c_d_e_"),
+  EXPECT_THAT(identifierTrigramTokens("a_b_c_d_e_"),
   trigramsAre({"a", "a_", "ab", "abc", "bcd", "cde"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("unique_ptr"),
+  EXPECT_THAT(identifierTrigramTokens("unique_ptr"),
   trigramsAre({"u", "un", "up", "uni", "unp", "upt", "niq", "nip",
"npt", "iqu", "iqp", "ipt", "que", "qup", "qpt",
"uep", "ept", "ptr"}));
 
   EXPECT_THAT(
-  generateIdentifierTrigrams("TUDecl"),
+  identifierTrigramTokens("TUDecl"),
   trigramsAre({"t", "tu", "td", "tud", "tde", "ude", "dec", "ecl"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("IsOK"),
+  EXPECT_THAT(identifierTrigramTokens("IsOK"),
   trigramsAre({"i", "is", "io", "iso", "iok", "sok"}));
 
   EXPECT_THAT(
-  generateIdentifierTrigrams("abc_defGhij__klm"),
+  identifierTrigramTokens("abc_defGhij__klm"),
   trigramsAre({"a",   "ab",  "ad",  "abc", "abd", "ade", "adg", "bcd",
"bde", "bdg", "cde", "cdg", "def", "deg", "dgh", "dgk",
"efg", "egh", "egk", "fgh", "fgk", "ghi", "ghk", "gkl",
Index: clang-tools-extra/clangd/test/Inputs/requests.json
===
--- clang-tools-extra/clangd/test/Inputs/requests.json
+++ clang-tools-extra/clangd/test/Inputs/requests.json
@@ -1,7 +1,7 @@
-[{"Limit":100,"ProximityPaths":["/usr/home/user/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp"],"Query":"OMP","RestrictForCodeCompletion":true,"Scopes":["clang::"], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"s","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"sy","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"sys","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"sys","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"Dex","RestrictForCodeCompletion":true,"Scopes":["clang::clangd::", "clang::", "clang::clangd::dex::"],"AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"Variable","RestrictForCodeCompletion":true,"Scopes":[""], "AnyScope":false}]
+[{"Limit":100,"ProximityPaths":["/usr/home/user/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp"],"Query":"OMP","RestrictForCodeCompletion":true,"Scopes":["clang::"], "AnyScope":false, "PreferredTypes":[]},
+{"Limit":100,"ProximityPaths":[],"Query":"s","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false, "PreferredTypes":[]},
+{"Limit":100,"ProximityPaths":[],"Query":"sy","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "A

[PATCH] D72705: [analyzer] Added new checker 'alpha.unix.ErrorReturn'.

2020-05-14 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

It is a way of find some of the cases with the mentioned way of tracking what 
operations are allowed after what operations with or without error check, on a 
specific stream. Instead of a stream a symbol that is passed to the function at 
a specific argument can be used (to generalize for other than streams). If the 
code would work this way, the check to discover the "error check statement" is 
still needed, like now in the checker.

But I think it is no problem to say that the return value should be checked 
always (for the specific functions). The fact that a function has failed and 
the return value was not checked is in itself a bug and should not discovered 
only when a later function is called. This is not always possible. For example 
at `strtol` type of functions we can only find if the return value is checked 
for special error return value. A failing `strtol` may not cause any 
discoverable abnormal conditions later.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72705



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


[PATCH] D79918: [clangd] Don't create as much garbage while building Dex index.

2020-05-14 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev accepted this revision.
kbobyrev added a comment.
This revision is now accepted and ready to land.

LGTM, thank you for the patch!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79918



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


[clang-tools-extra] 2045189 - [clangd] Setting recovery-ast flag in buildCompilerInvocation, NFC.

2020-05-14 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2020-05-14T13:16:59+02:00
New Revision: 2045189043d4e2748ed82915dd7bdf3e96728738

URL: 
https://github.com/llvm/llvm-project/commit/2045189043d4e2748ed82915dd7bdf3e96728738
DIFF: 
https://github.com/llvm/llvm-project/commit/2045189043d4e2748ed82915dd7bdf3e96728738.diff

LOG: [clangd] Setting recovery-ast flag in buildCompilerInvocation, NFC.

This saves some duplicated code (in buildPreamble and buildAST).

Added: 


Modified: 
clang-tools-extra/clangd/Compiler.cpp
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/Preamble.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Compiler.cpp 
b/clang-tools-extra/clangd/Compiler.cpp
index 04d48b08865d..ee9b187258b2 100644
--- a/clang-tools-extra/clangd/Compiler.cpp
+++ b/clang-tools-extra/clangd/Compiler.cpp
@@ -82,6 +82,10 @@ buildCompilerInvocation(const ParseInputs &Inputs, 
clang::DiagnosticConsumer &D,
   CI->getPreprocessorOpts().PCHThroughHeader.clear();
   CI->getPreprocessorOpts().PCHWithHdrStop = false;
   CI->getPreprocessorOpts().PCHWithHdrStopCreate = false;
+
+  // Recovery expression currently only works for C++.
+  if (CI->getLangOpts()->CPlusPlus)
+CI->getLangOpts()->RecoveryAST = Inputs.Opts.BuildRecoveryAST;
   return CI;
 }
 

diff  --git a/clang-tools-extra/clangd/ParsedAST.cpp 
b/clang-tools-extra/clangd/ParsedAST.cpp
index e63f105b1b6c..e7678f3d69e9 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -262,9 +262,6 @@ ParsedAST::build(llvm::StringRef Filename, const 
ParseInputs &Inputs,
   const PrecompiledPreamble *PreamblePCH =
   Preamble ? &Preamble->Preamble : nullptr;
 
-  // Recovery expression currently only works for C++.
-  if (CI->getLangOpts()->CPlusPlus)
-CI->getLangOpts()->RecoveryAST = Inputs.Opts.BuildRecoveryAST;
   // This is on-by-default in windows to allow parsing SDK headers, but it
   // breaks many features. Disable it for the main-file (not preamble).
   CI->getLangOpts()->DelayedTemplateParsing = false;

diff  --git a/clang-tools-extra/clangd/Preamble.cpp 
b/clang-tools-extra/clangd/Preamble.cpp
index 640a2c66b3c9..9d9c5eff8c68 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -219,10 +219,6 @@ buildPreamble(PathRef FileName, CompilerInvocation CI,
   // to read back. We rely on dynamic index for the comments instead.
   CI.getPreprocessorOpts().WriteCommentListToPCH = false;
 
-  // Recovery expression currently only works for C++.
-  if (CI.getLangOpts()->CPlusPlus)
-CI.getLangOpts()->RecoveryAST = Inputs.Opts.BuildRecoveryAST;
-
   CppFilePreambleCallbacks SerializedDeclsCollector(FileName, 
PreambleCallback);
   if (Inputs.FS->setCurrentWorkingDirectory(Inputs.CompileCommand.Directory)) {
 log("Couldn't set working directory when building the preamble.");



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


[PATCH] D79916: Map -O to -O1 instead of -O2

2020-05-14 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a reviewer: echristo.
hans added a comment.

Actually it was http://llvm.org/r82131 that mapped -O to -O2 (I just refactored 
it). Originally it seems it was mapped to -O1.

Because this seems to have done quite intentionally, I'm a little vary of 
changing it back. I'm not sure who would be a good person to have insights here 
though.

+echristo maybe?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79916



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


[clang-tools-extra] 735ab46 - [clangd] Don't create as much garbage while building Dex index.

2020-05-14 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2020-05-14T13:35:44+02:00
New Revision: 735ab46cb4148c92d636c912832a32509252b579

URL: 
https://github.com/llvm/llvm-project/commit/735ab46cb4148c92d636c912832a32509252b579
DIFF: 
https://github.com/llvm/llvm-project/commit/735ab46cb4148c92d636c912832a32509252b579.diff

LOG: [clangd] Don't create as much garbage while building Dex index.

Summary:
The Token objects are relatively expensive and we were spending a lot of
CPU creating them for each trigram emitted. Instead, use a tiny trigram
structure until we're ready to finalize the index.

This improves the new BuildDex benchmark by 20%. This code is hot and on
the critical path in clangd: it runs after a new preamble is built.

Reviewers: kbobyrev

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp
clang-tools-extra/clangd/index/dex/Dex.cpp
clang-tools-extra/clangd/index/dex/Trigram.cpp
clang-tools-extra/clangd/index/dex/Trigram.h
clang-tools-extra/clangd/test/Inputs/requests.json
clang-tools-extra/clangd/unittests/DexTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp 
b/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp
index 439ac9c65b9c..26a70de8ee51 100644
--- a/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp
+++ b/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp
@@ -83,6 +83,12 @@ static void DexQueries(benchmark::State &State) {
 }
 BENCHMARK(DexQueries);
 
+static void DexBuild(benchmark::State &State) {
+  for (auto _ : State)
+buildDex();
+}
+BENCHMARK(DexBuild);
+
 } // namespace
 } // namespace clangd
 } // namespace clang

diff  --git a/clang-tools-extra/clangd/index/dex/Dex.cpp 
b/clang-tools-extra/clangd/index/dex/Dex.cpp
index a663e5387ece..8082ffd75ad9 100644
--- a/clang-tools-extra/clangd/index/dex/Dex.cpp
+++ b/clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -39,28 +39,60 @@ namespace {
 const Token RestrictedForCodeCompletion =
 Token(Token::Kind::Sentinel, "Restricted For Code Completion");
 
-// Returns the tokens which are given symbol's characteristics. Currently, the
-// generated tokens only contain fuzzy matching trigrams and symbol's scope,
-// but in the future this will also return path proximity tokens and other
-// types of tokens such as symbol type (if applicable).
-// Returns the tokens which are given symbols's characteristics. For example,
-// trigrams and scopes.
-// FIXME(kbobyrev): Support more token types:
-// * Namespace proximity
-std::vector generateSearchTokens(const Symbol &Sym) {
-  std::vector Result = generateIdentifierTrigrams(Sym.Name);
-  Result.emplace_back(Token::Kind::Scope, Sym.Scope);
-  // Skip token generation for symbols with unknown declaration location.
-  if (!llvm::StringRef(Sym.CanonicalDeclaration.FileURI).empty())
-for (const auto &ProximityURI :
- generateProximityURIs(Sym.CanonicalDeclaration.FileURI))
-  Result.emplace_back(Token::Kind::ProximityURI, ProximityURI);
-  if (Sym.Flags & Symbol::IndexedForCodeCompletion)
-Result.emplace_back(RestrictedForCodeCompletion);
-  if (!Sym.Type.empty())
-Result.emplace_back(Token::Kind::Type, Sym.Type);
-  return Result;
-}
+// Helper to efficiently assemble the inverse index (token -> matching docs).
+// The output is a nice uniform structure keyed on Token, but constructing
+// the Token object every time we want to insert into the map is wasteful.
+// Instead we have various maps keyed on things that are cheap to compute,
+// and produce the Token keys once at the end.
+class IndexBuilder {
+  llvm::DenseMap> TrigramDocs;
+  std::vector RestrictedCCDocs;
+  llvm::StringMap> TypeDocs;
+  llvm::StringMap> ScopeDocs;
+  llvm::StringMap> ProximityDocs;
+  std::vector TrigramScratch;
+
+public:
+  // Add the tokens which are given symbol's characteristics.
+  // This includes fuzzy matching trigrams, symbol's scope, etc.
+  // FIXME(kbobyrev): Support more token types:
+  // * Namespace proximity
+  void add(const Symbol &Sym, DocID D) {
+generateIdentifierTrigrams(Sym.Name, TrigramScratch);
+for (Trigram T : TrigramScratch)
+  TrigramDocs[T].push_back(D);
+ScopeDocs[Sym.Scope].push_back(D);
+if (!llvm::StringRef(Sym.CanonicalDeclaration.FileURI).empty())
+  for (const auto &ProximityURI :
+   generateProximityURIs(Sym.CanonicalDeclaration.FileURI))
+ProximityDocs[ProximityURI].push_back(D);
+if (Sym.Flags & Symbol::IndexedForCodeCompletion)
+  RestrictedCCDocs.push_back(D);
+if (!Sym.Type.empty())
+  TypeDocs[Sym.Type].push_back(D);
+  }
+
+  // Assemble the final compressed posting lists for the added symbols.
+  llvm::DenseMap build() {
+llvm::DenseMap Result(/*InitialReser

[clang-tools-extra] 17ba631 - [clangd] Remove extra qualification

2020-05-14 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2020-05-14T14:06:05+02:00
New Revision: 17ba631d1317f294460036cc430dd158ad3d

URL: 
https://github.com/llvm/llvm-project/commit/17ba631d1317f294460036cc430dd158ad3d
DIFF: 
https://github.com/llvm/llvm-project/commit/17ba631d1317f294460036cc430dd158ad3d.diff

LOG: [clangd] Remove extra qualification

Added: 


Modified: 
clang-tools-extra/clangd/index/dex/Trigram.h

Removed: 




diff  --git a/clang-tools-extra/clangd/index/dex/Trigram.h 
b/clang-tools-extra/clangd/index/dex/Trigram.h
index 28cd4718c350..2abb01006fd3 100644
--- a/clang-tools-extra/clangd/index/dex/Trigram.h
+++ b/clang-tools-extra/clangd/index/dex/Trigram.h
@@ -87,7 +87,7 @@ std::vector generateQueryTrigrams(llvm::StringRef 
Query);
 } // namespace clang
 
 namespace llvm {
-template <> struct llvm::DenseMapInfo {
+template <> struct DenseMapInfo {
   using Trigram = clang::clangd::dex::Trigram;
   static inline Trigram getEmptyKey() {
 return Trigram(Trigram::Sentinel::Empty);



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


[clang-tools-extra] 0e5706d - [clangd] Correct the elog message, NFC.

2020-05-14 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2020-05-14T14:15:21+02:00
New Revision: 0e5706d018762f4ab4d895ba268bb6444ae04884

URL: 
https://github.com/llvm/llvm-project/commit/0e5706d018762f4ab4d895ba268bb6444ae04884
DIFF: 
https://github.com/llvm/llvm-project/commit/0e5706d018762f4ab4d895ba268bb6444ae04884.diff

LOG: [clangd] Correct the elog message, NFC.

Added: 


Modified: 
clang-tools-extra/clangd/CodeComplete.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 4c7f1457518c..0abe023c57a5 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -1777,7 +1777,7 @@ SignatureHelp signatureHelp(PathRef FileName,
 const SymbolIndex *Index) {
   auto Offset = positionToOffset(Contents, Pos);
   if (!Offset) {
-elog("Code completion position was invalid {0}", Offset.takeError());
+elog("Signature help position was invalid {0}", Offset.takeError());
 return SignatureHelp();
   }
   SignatureHelp Result;



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


[PATCH] D79754: [OpenMP][AMDGCN] Support OpenMP offloading for AMDGCN architecture - Part 1

2020-05-14 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam marked 5 inline comments as done.
saiislam added inline comments.



Comment at: clang/lib/AST/Decl.cpp:3224
 
+  if (Context.getTargetInfo().getTriple().isAMDGCN() &&
+  Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&

jdoerfert wrote:
> sameerds wrote:
> > arsenm wrote:
> > > This is also identical to the cuda handling above, can you merge them
> > It's not identical, because CUDA is filtering out host code and its check 
> > is target independent.
> > 
> > But then, Saiyed, it seems that the new patch disallows library builtins on 
> > all languages that reach this point, both on host and device code. Is that 
> > the intention? Does this point in the flow preclude any side-effects 
> > outside of "OpenMP on AMDGCN"?
> Yes, wasn't there an idea to have isGPU()?
@sameerds  this function returns a value indicating whether input function 
corresponds to a builtin function (returns BuiltinID), or not (returns 0) i.e. 
all conditions returning 0 are the exceptions where a valid BuiltinID can't be 
returned. The new condition only applies to non-OpenCL (line 3213) builtin 
functions which are not printf and malloc, and have been targeted for amdgcn.



Comment at: clang/lib/AST/Decl.cpp:3224
 
+  if (Context.getTargetInfo().getTriple().isAMDGCN() &&
+  Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&

saiislam wrote:
> jdoerfert wrote:
> > sameerds wrote:
> > > arsenm wrote:
> > > > This is also identical to the cuda handling above, can you merge them
> > > It's not identical, because CUDA is filtering out host code and its check 
> > > is target independent.
> > > 
> > > But then, Saiyed, it seems that the new patch disallows library builtins 
> > > on all languages that reach this point, both on host and device code. Is 
> > > that the intention? Does this point in the flow preclude any side-effects 
> > > outside of "OpenMP on AMDGCN"?
> > Yes, wasn't there an idea to have isGPU()?
> @sameerds  this function returns a value indicating whether input function 
> corresponds to a builtin function (returns BuiltinID), or not (returns 0) 
> i.e. all conditions returning 0 are the exceptions where a valid BuiltinID 
> can't be returned. The new condition only applies to non-OpenCL (line 3213) 
> builtin functions which are not printf and malloc, and have been targeted for 
> amdgcn.
@jdoerfert  Can you please elaborate on isGPU() idea? I am not aware about it.
Guessing by the name, I have added isGPU() as a wrapper over isNVPTX() and 
isAMDGCN() in the next revision.



Comment at: clang/lib/AST/Decl.cpp:3225
+  if (Context.getTargetInfo().getTriple().isAMDGCN() &&
+  Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
+  !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))

this condition is not required because it has already been checked in line 
#3200 earlier.



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:3162
+  Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
   Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime);
 

sameerds wrote:
> jdoerfert wrote:
> > Can we please not call it CUDA mode for non-CUDA targets? Or do you expect 
> > the compilation to "identify" as CUDA compilation?
> I suspect it's just a lot of water under the bridge. All over Clang, HIP has 
> traditionally co-opted CUDA code without introducing new identifiers, like 
> "-fcuda-is-device". It won't be easy to redo that now, and definitely looks 
> out of scope for this change. A typical HIP compilation usually does identify 
> itself as a HIP compilation like setting the isHIP flag. This allows the 
> frontend to distinguish between CUDA and HIP when it matters.
@jdoerfert [[ https://clang.llvm.org/docs/OpenMPSupport.html#data-sharing-modes 
| OpenMP support document of clang ]] defines two data sharing modes for cuda 
devices: CUDA and Generic mode. NVPTX and AMDGCN both are cuda devices. Doesn't 
it make sense to not refactor CUDA mode as of now?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79754



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


[PATCH] D75169: [ARM] Enforcing calling convention for half-precision FP arguments and returns for big-endian AArch32

2020-05-14 Thread Diogo N. Sampaio via Phabricator via cfe-commits
dnsampaio added a comment.

In D75169#1952159 , @pratlucas wrote:

> > Why not just make half as an argument do the right thing for that case?
>
> That would be the ideal approach, but currently there's a limitation on the 
> backend's calling convention lowering that gets in the way.
>  The lowering of calls in `SelectionDAGBuilder` includes a target-independent 
> step that is responsible for spliting or promoting each argument into "legal 
> registers" and takes place before the targets' calling convention lowering.
>  As `f16` is not a legal type on many of the `AAPCS_VFP` targets, it gets 
> promoted to `f32` before the target's lowering code has a chance to define 
> how to handle it.
>  Ideally, this stpe should only take place if lowering calling conventions 
> after type legalization - there's a FIXME there already capturing that -, but 
> that would involve a major rewriting that would impact multiple targets.
>  Inserting a hacky target-dependent fix in this step also didn't look very 
> good.
>  Do you see other alternatives for handling it? If not, which approach would 
> you suggest?


Would it be possible to pass a `half` argument and fix-it-up at 
`CodeGenPrepare`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75169



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


[PATCH] D79938: [clangd] Add a flag to preserve type for recovery expression.

2020-05-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman, jkorous, MaskRay, 
ilya-biryukov.
Herald added a project: clang.
hokein marked an inline comment as done.
hokein added inline comments.



Comment at: clang-tools-extra/clangd/CodeComplete.cpp:1072
   ParseInput.Contents = std::string(Input.Contents);
+  // FIXME: setup the recoveryAST and recoveryASTType in ParseInput properly.
 

unfortunately, we don't have the `ParseOptions` structure in code completion 
code path, maybe we can add two flags in `SemaCompleteInput`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D79938

Files:
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/Compiler.cpp
  clang-tools-extra/clangd/Compiler.h
  clang-tools-extra/clangd/tool/ClangdMain.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp

Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -57,6 +57,7 @@
   Inputs.FS = buildTestFS(Files);
   Inputs.Opts = ParseOptions();
   Inputs.Opts.BuildRecoveryAST = true;
+  Inputs.Opts.PreserveRecoveryASTType = true;
   Inputs.Opts.ClangTidyOpts.Checks = ClangTidyChecks;
   Inputs.Opts.ClangTidyOpts.WarningsAsErrors = ClangTidyWarningsAsErrors;
   Inputs.Index = ExternalIndex;
Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -158,6 +158,19 @@
   EXPECT_DECLS("UnresolvedLookupExpr", "int f()", "int f(int, int)");
 }
 
+TEST_F(TargetDeclTest, RecoveryType) {
+  Code = R"cpp(
+// error-ok: testing behavior on broken code
+struct S { int member; };
+S overloaded(int);
+void foo() {
+  // No overload matches, but we have recovery-expr with the correct type.
+  overloaded().[[member]];
+}
+  )cpp";
+  EXPECT_DECLS("MemberExpr", "int member");
+}
+
 TEST_F(TargetDeclTest, UsingDecl) {
   Code = R"cpp(
 namespace foo {
Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -752,6 +752,19 @@
   EXPECT_THAT(Results, ElementsAre(Named("ifndef")));
 }
 
+// FIXME: enable it.
+TEST(CompletionTest, DISABLED_CompletionRecoveryASTType) {
+  auto Results = completions(R"cpp(
+struct S { int member; };
+S overloaded(int);
+void foo() {
+  // No overload matches, but we have recovery-expr with the correct type.
+  overloaded().^
+})cpp")
+ .Completions;
+  EXPECT_THAT(Results, ElementsAre(Named("member")));
+}
+
 TEST(CompletionTest, DynamicIndexIncludeInsertion) {
   MockFSProvider FS;
   MockCompilationDatabase CDB;
Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -289,6 +289,14 @@
 init(false),
 Hidden,
 };
+opt RecoveryASTType{
+"recovery-ast-type",
+cat(Features),
+desc("Preserve the type for recovery AST. Note that "
+ "this feature is experimental and may lead to crashes"),
+init(false),
+Hidden,
+};
 
 opt WorkerThreadsCount{
 "j",
@@ -636,6 +644,7 @@
   Opts.StaticIndex = StaticIdx.get();
   Opts.AsyncThreadsCount = WorkerThreadsCount;
   Opts.BuildRecoveryAST = RecoveryAST;
+  Opts.PreserveRecoveryASTType = RecoveryASTType;
 
   clangd::CodeCompleteOptions CCOpts;
   CCOpts.IncludeIneligibleResults = IncludeIneligibleResults;
Index: clang-tools-extra/clangd/Compiler.h
===
--- clang-tools-extra/clangd/Compiler.h
+++ clang-tools-extra/clangd/Compiler.h
@@ -39,6 +39,7 @@
   tidy::ClangTidyOptions ClangTidyOpts;
   bool SuggestMissingIncludes = false;
   bool BuildRecoveryAST = false;
+  bool PreserveRecoveryASTType = false;
 };
 
 /// Information required to run clang, e.g. to parse AST or do code completion.
Index: clang-tools-extra/clangd/Compiler.cpp
===
--- clang-tools-extra/clangd/Compiler.cpp
+++ clang-tools-extra/clangd/Compiler.cpp
@@ -84,8 +84,10 @@
   CI->getPreprocessorOpts().PCHWithHdrStopCreate = false;
 
   // Recovery expression currently only works for C++.
-  if (CI->getLangOpts()->CPlusPlus)
+  if (CI->getLangOpts(

[PATCH] D79378: PR34581: Don't remove an 'if (p)' guarding a call to 'operator delete(p)' under -Oz.

2020-05-14 Thread Diogo N. Sampaio via Phabricator via cfe-commits
dnsampaio accepted this revision.
dnsampaio added a comment.
This revision is now accepted and ready to land.

LGTM, as far @rjmccall 's concern about documentation is addressed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79378



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


[PATCH] D79754: [OpenMP][AMDGCN] Support OpenMP offloading for AMDGCN architecture - Part 1

2020-05-14 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam updated this revision to Diff 263972.
saiislam marked an inline comment as done.
saiislam added a comment.

Added test cases. Added a wrapper isGPU() for isNVPTX()/isAMDGCN().


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79754

Files:
  clang/lib/AST/Decl.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Driver/openmp-offload-gpu.c
  clang/test/OpenMP/target_parallel_no_exceptions.cpp
  llvm/include/llvm/ADT/Triple.h

Index: llvm/include/llvm/ADT/Triple.h
===
--- llvm/include/llvm/ADT/Triple.h
+++ llvm/include/llvm/ADT/Triple.h
@@ -692,6 +692,12 @@
 return getArch() == Triple::nvptx || getArch() == Triple::nvptx64;
   }
 
+  /// Tests whether the target is AMDGCN
+  bool isAMDGCN() const { return getArch() == Triple::amdgcn; }
+
+  /// Tests whether the target is a GPU i.e. NVPTX or AMDGCN
+  bool isGPU() const { return isNVPTX() || isAMDGCN(); }
+
   bool isAMDGPU() const {
 return getArch() == Triple::r600 || getArch() == Triple::amdgcn;
   }
Index: clang/test/OpenMP/target_parallel_no_exceptions.cpp
===
--- clang/test/OpenMP/target_parallel_no_exceptions.cpp
+++ clang/test/OpenMP/target_parallel_no_exceptions.cpp
@@ -1,6 +1,7 @@
 /// Make sure no exception messages are inclided in the llvm output.
 // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc
 // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix CHK-EXCEPTION
+// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple x86_64-unknown-unknown -fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix CHK-EXCEPTION
 
 void test_increment() {
 #pragma omp target
Index: clang/test/Driver/openmp-offload-gpu.c
===
--- clang/test/Driver/openmp-offload-gpu.c
+++ clang/test/Driver/openmp-offload-gpu.c
@@ -6,6 +6,7 @@
 // REQUIRES: x86-registered-target
 // REQUIRES: powerpc-registered-target
 // REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
 
 /// ###
 
@@ -249,30 +250,49 @@
 // HAS_DEBUG-SAME: "--return-at-end"
 // HAS_DEBUG: nvlink
 // HAS_DEBUG-SAME: "-g"
+// CUDA_MODE: clang{{.*}}"-cc1"{{.*}}"-triple" "{{nvptx64-nvidia-cuda|amdgcn-amd-amdhsa}}"
+// CUDA_MODE-SAME: "-fopenmp-cuda-mode"
+// NO_CUDA_MODE-NOT: "-{{fno-|f}}openmp-cuda-mode"
 
 // RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -fopenmp-cuda-mode 2>&1 \
 // RUN:   | FileCheck -check-prefix=CUDA_MODE %s
 // RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -fno-openmp-cuda-mode -fopenmp-cuda-mode 2>&1 \
 // RUN:   | FileCheck -check-prefix=CUDA_MODE %s
-// CUDA_MODE: clang{{.*}}"-cc1"{{.*}}"-triple" "nvptx64-nvidia-cuda"
-// CUDA_MODE-SAME: "-fopenmp-cuda-mode"
 // RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -fno-openmp-cuda-mode 2>&1 \
 // RUN:   | FileCheck -check-prefix=NO_CUDA_MODE %s
 // RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -fopenmp-cuda-mode -fno-openmp-cuda-mode 2>&1 \
 // RUN:   | FileCheck -check-prefix=NO_CUDA_MODE %s
-// NO_CUDA_MODE-NOT: "-{{fno-|f}}openmp-cuda-mode"
+
+// RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target -march=gfx906 %s -fopenmp-cuda-mode 2>&1 \
+// RUN:   | FileCheck -check-prefix=CUDA_MODE %s
+// RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target -march=gfx906 %s -fno-openmp-cuda-mode -fopenmp-cuda-mode 2>&1 \
+// RUN:   | FileCheck -check-prefix=CUDA_MODE %s
+// RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target -march=gfx906 %s -fno-openmp-cuda-mode 2>&1 \
+// RUN:   | FileCheck -check-prefix=NO_CUDA_MODE %s
+// RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target -march=gfx906 %s -fopenmp-cuda-mode -fno-openmp-cuda-mode 2>&1 \
+// RUN:   | FileCheck -check-prefix=NO_CUDA_MODE %s
+
+// FULL_RUNTIME: clang{{.*}}"-cc1"{{.*}}"-triple" "{{nvptx64-nvidia-cuda|amdgcn-amd-amdhsa}}"
+// FULL_RUNTIME-SAME: "-fopenmp-cuda-force-full-runtime"
+// NO_FULL_RUNTIME-NOT: "-{{f

[PATCH] D79704: [Analyzer] [NFC] Parameter Regions

2020-05-14 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/MemRegion.cpp:191
+const ParmVarDecl *ParamRegion::getDecl() const {
+  const Decl *D = getStackFrame()->getDecl();
+

baloghadamsoftware wrote:
> NoQ wrote:
> > This doesn't work when the callee is unknown.
> Please give me an example where the callee is unknown. As I wrote, originally 
> I put a `getExpr()` method here as well and `getType()` fell back to it if it 
> could not find the `Decl()`. However, it was never invoked on the whole test 
> suite. (I put an `assert(false)` into it, and did not get a crash.
> Please give me an example where the callee is unknown.

>>! In D79704#2034571, @NoQ wrote:
>>>! In D79704#2032947, @Szelethus wrote:
>> Could you give a specific code example? 
> 
> ```lang=c++
> struct S {
>   S() {
> this; // What region does 'this' point to...
>   }
> };
> 
> void foo(void (*bar)(S)) {
>   bar(S()); // ...in this invocation?
> }
> ```


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

https://reviews.llvm.org/D79704



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


[PATCH] D79938: [clangd] Add a flag to preserve type for recovery expression.

2020-05-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein marked an inline comment as done.
hokein added inline comments.



Comment at: clang-tools-extra/clangd/CodeComplete.cpp:1072
   ParseInput.Contents = std::string(Input.Contents);
+  // FIXME: setup the recoveryAST and recoveryASTType in ParseInput properly.
 

unfortunately, we don't have the `ParseOptions` structure in code completion 
code path, maybe we can add two flags in `SemaCompleteInput`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79938



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


[PATCH] D79932: [analyzer] Modernize analyzer's Python scripts

2020-05-14 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

Thanks!!

Note that there are no tests for these scripts. It's probably not too bad 
because these scripts *are* the tests but we might as well benefit from some 
quicker LIT tests that'll respond to our mistakes faster than buildbot re-runs.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79932



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


[PATCH] D78280: [Analyzer][StreamChecker] Track streams that were not found to be opened.

2020-05-14 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.

I like this idea, except the word `OpenEncountered`, but that might be a matter 
of taste. Please try this patch on several open-source projects, such as 
//BitCoin//, //CURL//, //OpenSSL//, //PostGreS//, //TMux// and //Xerces//. Then 
compare the results whether we have more or less true and false positives.




Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:36
+  /// (False if the stream was first encountered in a non-opening function.)
+  bool OpenEncountered;
 

Maybe `SawOpened` or `ExplicitlyOpened`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78280



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


[PATCH] D79918: [clangd] Don't create as much garbage while building Dex index.

2020-05-14 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG735ab46cb414: [clangd] Don't create as much garbage 
while building Dex index. (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79918

Files:
  clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp
  clang-tools-extra/clangd/index/dex/Dex.cpp
  clang-tools-extra/clangd/index/dex/Trigram.cpp
  clang-tools-extra/clangd/index/dex/Trigram.h
  clang-tools-extra/clangd/test/Inputs/requests.json
  clang-tools-extra/clangd/unittests/DexTests.cpp

Index: clang-tools-extra/clangd/unittests/DexTests.cpp
===
--- clang-tools-extra/clangd/unittests/DexTests.cpp
+++ clang-tools-extra/clangd/unittests/DexTests.cpp
@@ -366,38 +366,46 @@
   return tokensAre(Trigrams, Token::Kind::Trigram);
 }
 
+std::vector identifierTrigramTokens(llvm::StringRef S) {
+  std::vector Trigrams;
+  generateIdentifierTrigrams(S, Trigrams);
+  std::vector Tokens;
+  for (Trigram T : Trigrams)
+Tokens.emplace_back(Token::Kind::Trigram, T.str());
+  return Tokens;
+}
+
 TEST(DexTrigrams, IdentifierTrigrams) {
-  EXPECT_THAT(generateIdentifierTrigrams("X86"),
-  trigramsAre({"x86", "x", "x8"}));
+  EXPECT_THAT(identifierTrigramTokens("X86"), trigramsAre({"x86", "x", "x8"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("nl"), trigramsAre({"nl", "n"}));
+  EXPECT_THAT(identifierTrigramTokens("nl"), trigramsAre({"nl", "n"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("n"), trigramsAre({"n"}));
+  EXPECT_THAT(identifierTrigramTokens("n"), trigramsAre({"n"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("clangd"),
+  EXPECT_THAT(identifierTrigramTokens("clangd"),
   trigramsAre({"c", "cl", "cla", "lan", "ang", "ngd"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("abc_def"),
+  EXPECT_THAT(identifierTrigramTokens("abc_def"),
   trigramsAre({"a", "ab", "ad", "abc", "abd", "ade", "bcd", "bde",
"cde", "def"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("a_b_c_d_e_"),
+  EXPECT_THAT(identifierTrigramTokens("a_b_c_d_e_"),
   trigramsAre({"a", "a_", "ab", "abc", "bcd", "cde"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("unique_ptr"),
+  EXPECT_THAT(identifierTrigramTokens("unique_ptr"),
   trigramsAre({"u", "un", "up", "uni", "unp", "upt", "niq", "nip",
"npt", "iqu", "iqp", "ipt", "que", "qup", "qpt",
"uep", "ept", "ptr"}));
 
   EXPECT_THAT(
-  generateIdentifierTrigrams("TUDecl"),
+  identifierTrigramTokens("TUDecl"),
   trigramsAre({"t", "tu", "td", "tud", "tde", "ude", "dec", "ecl"}));
 
-  EXPECT_THAT(generateIdentifierTrigrams("IsOK"),
+  EXPECT_THAT(identifierTrigramTokens("IsOK"),
   trigramsAre({"i", "is", "io", "iso", "iok", "sok"}));
 
   EXPECT_THAT(
-  generateIdentifierTrigrams("abc_defGhij__klm"),
+  identifierTrigramTokens("abc_defGhij__klm"),
   trigramsAre({"a",   "ab",  "ad",  "abc", "abd", "ade", "adg", "bcd",
"bde", "bdg", "cde", "cdg", "def", "deg", "dgh", "dgk",
"efg", "egh", "egk", "fgh", "fgk", "ghi", "ghk", "gkl",
Index: clang-tools-extra/clangd/test/Inputs/requests.json
===
--- clang-tools-extra/clangd/test/Inputs/requests.json
+++ clang-tools-extra/clangd/test/Inputs/requests.json
@@ -1,7 +1,7 @@
-[{"Limit":100,"ProximityPaths":["/usr/home/user/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp"],"Query":"OMP","RestrictForCodeCompletion":true,"Scopes":["clang::"], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"s","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"sy","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"sys","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"sys","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"Dex","RestrictForCodeCompletion":true,"Scopes":["clang::clangd::", "clang::", "clang::clangd::dex::"],"AnyScope":false},
-{"Limit":100,"ProximityPaths":[],"Query":"Variable","RestrictForCodeCompletion":true,"Scopes":[""], "AnyScope":false}]
+[{"Limit":100,"ProximityPaths":["/usr/home/user/clang-tools-extra/clangd/benchmarks/IndexBenchmark.cpp"],"Query":"OMP","RestrictForCodeCompletion":true,"Scopes":["clang::"], "AnyScope":false, "PreferredTypes":[]},
+{"Limit":100,"ProximityPaths":[],"Query":"s","RestrictForCodeCompletion":true,"Scopes":["llvm::", ""], "AnyScope":false, "PreferredTypes":[]},
+{"Limit":100,"ProximityPaths":[],"Query":"sy","RestrictForCodeCompletion":tru

[clang] cb1eeb4 - [Analyzer][VLASizeChecker] Check VLA size in typedef and sizeof.

2020-05-14 Thread Balázs Kéri via cfe-commits

Author: Balázs Kéri
Date: 2020-05-14T14:30:05+02:00
New Revision: cb1eeb42c03c31d4dadd00dbaec693e6d7516099

URL: 
https://github.com/llvm/llvm-project/commit/cb1eeb42c03c31d4dadd00dbaec693e6d7516099
DIFF: 
https://github.com/llvm/llvm-project/commit/cb1eeb42c03c31d4dadd00dbaec693e6d7516099.diff

LOG: [Analyzer][VLASizeChecker] Check VLA size in typedef and sizeof.

Summary:
The check of VLA size was done previously for variable declarations
(of VLA type) only. Now it is done for typedef (and type-alias)
and sizeof expressions with VLA too.

Reviewers: Szelethus, martong

Reviewed By: Szelethus, martong

Subscribers: rnkovacs, xazax.hun, baloghadamsoftware, szepet, a.sidorin, 
mikhail.ramalho, Szelethus, donat.nagy, dkrupp, gamesh411, Charusso, martong, 
ASDenysPetrov, cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
clang/test/Analysis/vla.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
index 0c7961a2a28b..3bd2520f013a 100644
--- a/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
@@ -30,10 +30,26 @@ using namespace ento;
 using namespace taint;
 
 namespace {
-class VLASizeChecker : public Checker< check::PreStmt > {
+class VLASizeChecker
+: public Checker,
+ check::PreStmt> {
   mutable std::unique_ptr BT;
   enum VLASize_Kind { VLA_Garbage, VLA_Zero, VLA_Tainted, VLA_Negative };
 
+  /// Check a VLA for validity.
+  /// Every dimension of the array is checked for validity, and
+  /// dimension sizes are collected into 'VLASizes'. 'VLALast' is set to the
+  /// innermost VLA that was encountered.
+  /// In "int vla[x][2][y][3]" this will be the array for index "y" (with type
+  /// int[3]). 'VLASizes' contains 'x', '2', and 'y'. Returns null or a new
+  /// state where the size is validated for every dimension.
+  ProgramStateRef checkVLA(CheckerContext &C, ProgramStateRef State,
+   const VariableArrayType *VLA,
+   const VariableArrayType *&VLALast,
+   llvm::SmallVector &VLASizes) const;
+
+  /// Check one VLA dimension for validity.
+  /// Returns null or a new state where the size is validated.
   ProgramStateRef checkVLASize(CheckerContext &C, ProgramStateRef State,
const Expr *SizeE) const;
 
@@ -43,9 +59,37 @@ class VLASizeChecker : public Checker< 
check::PreStmt > {
 
 public:
   void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
+  void checkPreStmt(const UnaryExprOrTypeTraitExpr *UETTE,
+CheckerContext &C) const;
 };
 } // end anonymous namespace
 
+ProgramStateRef
+VLASizeChecker::checkVLA(CheckerContext &C, ProgramStateRef State,
+ const VariableArrayType *VLA,
+ const VariableArrayType *&VLALast,
+ llvm::SmallVector &VLASizes) const {
+  assert(VLA && "Function should be called with non-null VLA argument.");
+
+  VLALast = nullptr;
+  // Walk over the VLAs for every dimension until a non-VLA is found.
+  // There is a VariableArrayType for every dimension (fixed or variable) until
+  // the most inner array that is variably modified.
+  while (VLA) {
+const Expr *SizeE = VLA->getSizeExpr();
+State = checkVLASize(C, State, SizeE);
+if (!State)
+  return nullptr;
+VLASizes.push_back(SizeE);
+VLALast = VLA;
+VLA = C.getASTContext().getAsVariableArrayType(VLA->getElementType());
+  };
+  assert(VLALast &&
+ "Array should have at least one variably-modified dimension.");
+
+  return State;
+}
+
 ProgramStateRef VLASizeChecker::checkVLASize(CheckerContext &C,
  ProgramStateRef State,
  const Expr *SizeE) const {
@@ -146,36 +190,34 @@ void VLASizeChecker::checkPreStmt(const DeclStmt *DS, 
CheckerContext &C) const {
   if (!DS->isSingleDecl())
 return;
 
-  const VarDecl *VD = dyn_cast(DS->getSingleDecl());
-  if (!VD)
-return;
-
   ASTContext &Ctx = C.getASTContext();
   SValBuilder &SVB = C.getSValBuilder();
   ProgramStateRef State = C.getState();
+  QualType TypeToCheck;
+
+  const VarDecl *VD = dyn_cast(DS->getSingleDecl());
+
+  if (VD)
+TypeToCheck = VD->getType().getCanonicalType();
+  else if (const auto *TND = dyn_cast(DS->getSingleDecl()))
+TypeToCheck = TND->getUnderlyingType().getCanonicalType();
+  else
+return;
 
-  const VariableArrayType *VLA = Ctx.getAsVariableArrayType(VD->getType());
+  const VariableArrayType *VLA = Ctx.getAsVariableArrayType(TypeToCheck);
   if (!VLA)
 return;
 
+  // Check the VLA si

[PATCH] D79754: [OpenMP][AMDGCN] Support OpenMP offloading for AMDGCN architecture - Part 1

2020-05-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added inline comments.



Comment at: llvm/include/llvm/ADT/Triple.h:700
 return getArch() == Triple::r600 || getArch() == Triple::amdgcn;
   }
 

sameerds wrote:
> yaxunl wrote:
> > jdoerfert wrote:
> > > What's the difference between an AMDGPU and AMDGCN?
> > AMDGPU inlude r600 and amdgcn. r600 are old AMD GPUs. They do not support 
> > flat address space therefore cannot support CUDA or HIP.
> As a separate topic, does that mean that Clang should reject r600 at an 
> earlier entry point itself?
I think HIP checks triple and rejects triple other than amdgcn


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79754



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


[PATCH] D79921: [OpenMP] Fix omp and clang pragmas

2020-05-14 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

Tests?




Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:1736
+  const AttributedStmt *AS = nullptr;
+  if (auto *OMPD = dyn_cast(&S)) {
+const CapturedStmt *CS = OMPD->getCapturedStmt(OMPD_parallel);

1. Cast it to `OMPExecutableDirective` here, it should be enough.
2. No need for conditional casting, use `cast(...)`. Or 
you can change the function itself to accept `const OMPExecutableDirective &S` 
instead of `const Stmt &S`.



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:1737
+  if (auto *OMPD = dyn_cast(&S)) {
+const CapturedStmt *CS = OMPD->getCapturedStmt(OMPD_parallel);
+const Stmt *SS = CS->getCapturedStmt();

Use `getInnermostCapturedStmt()` instead.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79921



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


[PATCH] D79072: [Analyzer][VLASizeChecker] Check VLA size in typedef and sizeof.

2020-05-14 Thread Balázs Kéri via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcb1eeb42c03c: [Analyzer][VLASizeChecker] Check VLA size in 
typedef and sizeof. (authored by balazske).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79072

Files:
  clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/test/Analysis/vla.c

Index: clang/test/Analysis/vla.c
===
--- clang/test/Analysis/vla.c
+++ clang/test/Analysis/vla.c
@@ -89,6 +89,17 @@
 check_negative_sized_VLA_11_sub(x);
 }
 
+void check_VLA_typedef() {
+  int x = -1;
+  typedef int VLA[x]; // expected-warning{{Declared variable-length array (VLA) has negative size}}
+}
+
+size_t check_VLA_sizeof() {
+  int x = -1;
+  size_t s = sizeof(int[x]); // expected-warning{{Declared variable-length array (VLA) has negative size}}
+  return s;
+}
+
 // Multi-dimensional arrays.
 
 void check_zero_sized_VLA_multi1(int x) {
Index: clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -573,6 +573,18 @@
 
 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
ExplodedNodeSet &Dst) {
+  if (isa(*DS->decl_begin())) {
+// C99 6.7.7 "Any array size expressions associated with variable length
+// array declarators are evaluated each time the declaration of the typedef
+// name is reached in the order of execution."
+// The checkers should know about typedef to be able to handle VLA size
+// expressions.
+ExplodedNodeSet DstPre;
+getCheckerManager().runCheckersForPreStmt(DstPre, Pred, DS, *this);
+getCheckerManager().runCheckersForPostStmt(Dst, DstPre, DS, *this);
+return;
+  }
+
   // Assumption: The CFG has one DeclStmt per Decl.
   const VarDecl *VD = dyn_cast_or_null(*DS->decl_begin());
 
Index: clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
@@ -30,10 +30,26 @@
 using namespace taint;
 
 namespace {
-class VLASizeChecker : public Checker< check::PreStmt > {
+class VLASizeChecker
+: public Checker,
+ check::PreStmt> {
   mutable std::unique_ptr BT;
   enum VLASize_Kind { VLA_Garbage, VLA_Zero, VLA_Tainted, VLA_Negative };
 
+  /// Check a VLA for validity.
+  /// Every dimension of the array is checked for validity, and
+  /// dimension sizes are collected into 'VLASizes'. 'VLALast' is set to the
+  /// innermost VLA that was encountered.
+  /// In "int vla[x][2][y][3]" this will be the array for index "y" (with type
+  /// int[3]). 'VLASizes' contains 'x', '2', and 'y'. Returns null or a new
+  /// state where the size is validated for every dimension.
+  ProgramStateRef checkVLA(CheckerContext &C, ProgramStateRef State,
+   const VariableArrayType *VLA,
+   const VariableArrayType *&VLALast,
+   llvm::SmallVector &VLASizes) const;
+
+  /// Check one VLA dimension for validity.
+  /// Returns null or a new state where the size is validated.
   ProgramStateRef checkVLASize(CheckerContext &C, ProgramStateRef State,
const Expr *SizeE) const;
 
@@ -43,9 +59,37 @@
 
 public:
   void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
+  void checkPreStmt(const UnaryExprOrTypeTraitExpr *UETTE,
+CheckerContext &C) const;
 };
 } // end anonymous namespace
 
+ProgramStateRef
+VLASizeChecker::checkVLA(CheckerContext &C, ProgramStateRef State,
+ const VariableArrayType *VLA,
+ const VariableArrayType *&VLALast,
+ llvm::SmallVector &VLASizes) const {
+  assert(VLA && "Function should be called with non-null VLA argument.");
+
+  VLALast = nullptr;
+  // Walk over the VLAs for every dimension until a non-VLA is found.
+  // There is a VariableArrayType for every dimension (fixed or variable) until
+  // the most inner array that is variably modified.
+  while (VLA) {
+const Expr *SizeE = VLA->getSizeExpr();
+State = checkVLASize(C, State, SizeE);
+if (!State)
+  return nullptr;
+VLASizes.push_back(SizeE);
+VLALast = VLA;
+VLA = C.getASTContext().getAsVariableArrayType(VLA->getElementType());
+  };
+  assert(VLALast &&
+ "Array should have at least one variably-modified dimension.");
+
+  return State;
+}
+
 ProgramStateRef VLASizeChecker::checkVLASize(CheckerContext &C,
  ProgramStateRef State,
  

[clang] c98872e - [analyzer] Modernize analyzer's Python scripts

2020-05-14 Thread Valeriy Savchenko via cfe-commits

Author: Valeriy Savchenko
Date: 2020-05-14T15:55:37+03:00
New Revision: c98872e3a3c0fc4390e0892866d7e844df929179

URL: 
https://github.com/llvm/llvm-project/commit/c98872e3a3c0fc4390e0892866d7e844df929179
DIFF: 
https://github.com/llvm/llvm-project/commit/c98872e3a3c0fc4390e0892866d7e844df929179.diff

LOG: [analyzer] Modernize analyzer's Python scripts

Summary:
Fix read/write in binary format, which crashes Python 3.
Additionally, clean up redundant (as for Python 3) code and
fix a handful of flake8 warnings.

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

Added: 


Modified: 
clang/utils/analyzer/CmpRuns.py
clang/utils/analyzer/SATestAdd.py
clang/utils/analyzer/SATestBuild.py
clang/utils/analyzer/SATestUpdateDiffs.py
clang/utils/analyzer/SATestUtils.py
clang/utils/analyzer/SumTimerInfo.py
clang/utils/analyzer/exploded-graph-rewriter.py

Removed: 




diff  --git a/clang/utils/analyzer/CmpRuns.py b/clang/utils/analyzer/CmpRuns.py
index 3fab6ef520c4..28e9258f593a 100755
--- a/clang/utils/analyzer/CmpRuns.py
+++ b/clang/utils/analyzer/CmpRuns.py
@@ -39,7 +39,8 @@
 
 STATS_REGEXP = re.compile(r"Statistics: (\{.+\})", re.MULTILINE | re.DOTALL)
 
-class Colors(object):
+
+class Colors:
 """
 Color for terminal highlight.
 """
@@ -47,18 +48,21 @@ class Colors(object):
 GREEN = '\x1b[6;30;42m'
 CLEAR = '\x1b[0m'
 
-# Information about analysis run:
-# path - the analysis output directory
-# root - the name of the root directory, which will be disregarded when
-# determining the source file name
-class SingleRunInfo(object):
+
+class SingleRunInfo:
+"""
+Information about analysis run:
+path - the analysis output directory
+root - the name of the root directory, which will be disregarded when
+determining the source file name
+"""
 def __init__(self, path, root="", verboseLog=None):
 self.path = path
 self.root = root.rstrip("/\\")
 self.verboseLog = verboseLog
 
 
-class AnalysisDiagnostic(object):
+class AnalysisDiagnostic:
 def __init__(self, data, report, htmlReport):
 self._data = data
 self._loc = self._data['location']
@@ -80,7 +84,7 @@ def getRootFileName(self):
 p = path[0]
 if 'location' in p:
 fIdx = p['location']['file']
-else: # control edge
+else:  # control edge
 fIdx = path[0]['edges'][0]['start'][0]['file']
 out = self._report.files[fIdx]
 root = self._report.run.root
@@ -139,14 +143,14 @@ def getRawData(self):
 return self._data
 
 
-class AnalysisReport(object):
+class AnalysisReport:
 def __init__(self, run, files):
 self.run = run
 self.files = files
 self.diagnostics = []
 
 
-class AnalysisRun(object):
+class AnalysisRun:
 def __init__(self, info):
 self.path = info.path
 self.root = info.root
@@ -303,12 +307,14 @@ def compareResults(A, B, opts):
 
 return res
 
+
 def computePercentile(l, percentile):
 """
 Return computed percentile.
 """
 return sorted(l)[int(round(percentile * len(l) + 0.5)) - 1]
 
+
 def deriveStats(results):
 # Assume all keys are the same in each statistics bucket.
 combined_data = defaultdict(list)
@@ -355,6 +361,7 @@ def compareStats(resultsA, resultsB):
 report = Colors.RED + report + Colors.CLEAR
 print("\t %s %s" % (kkey, report))
 
+
 def dumpScanBuildResultsDiff(dirA, dirB, opts, deleteEmpty=True,
  Stdout=sys.stdout):
 # Load the run results.
@@ -367,7 +374,7 @@ def dumpScanBuildResultsDiff(dirA, dirB, opts, 
deleteEmpty=True,
 
 # Open the verbose log, if given.
 if opts.verboseLog:
-auxLog = open(opts.verboseLog, "wb")
+auxLog = open(opts.verboseLog, "w")
 else:
 auxLog = None
 
@@ -405,6 +412,7 @@ def dumpScanBuildResultsDiff(dirA, dirB, opts, 
deleteEmpty=True,
 
 return foundDiffs, len(resultsA.diagnostics), len(resultsB.diagnostics)
 
+
 def generate_option_parser():
 parser = OptionParser("usage: %prog [options] [dir A] [dir B]")
 parser.add_option("", "--rootA", dest="rootA",

diff  --git a/clang/utils/analyzer/SATestAdd.py 
b/clang/utils/analyzer/SATestAdd.py
index 52089f4e0660..e0e267bb259b 100755
--- a/clang/utils/analyzer/SATestAdd.py
+++ b/clang/utils/analyzer/SATestAdd.py
@@ -52,8 +52,8 @@
 
 def isExistingProject(PMapFile, projectID):
 PMapReader = csv.reader(PMapFile)
-for I in PMapReader:
-if projectID == I[0]:
+for ProjectInfo in PMapReader:
+if projectID == ProjectInfo[0]:
 return True
 return False
 
@@ -71,21 +71,24 @@ def addNewProject(ID, BuildMode):
 sys.exit(-1)
 
 # Build the project.
+# TODO: Repair this call.  We give it a wrong amount wrong arguments and it
+#   is not trivial to con

[clang] 7b8e306 - [clang] Fix bug in #pragma float_control(push/pop)

2020-05-14 Thread Melanie Blower via cfe-commits

Author: Melanie Blower
Date: 2020-05-14T05:58:11-07:00
New Revision: 7b8e3065606cb555e7528e3b59d5e164ecf008fa

URL: 
https://github.com/llvm/llvm-project/commit/7b8e3065606cb555e7528e3b59d5e164ecf008fa
DIFF: 
https://github.com/llvm/llvm-project/commit/7b8e3065606cb555e7528e3b59d5e164ecf008fa.diff

LOG: [clang] Fix bug in #pragma float_control(push/pop)

Summary: #pragma float_control(pop) was failing to restore the expected
floating point settings because the settings were not correctly preserved
at #pragma float_control(push).

Added: 


Modified: 
clang/lib/Sema/SemaAttr.cpp
clang/test/CodeGen/fp-floatcontrol-pragma.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index 222aaf3049ae..977e92475182 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -457,8 +457,12 @@ void Sema::ActOnPragmaFloatControl(SourceLocation Loc,
 FpPragmaStack.Act(Loc, Action, StringRef(), NewValue);
 break;
   case PFC_Push:
-Action = Sema::PSK_Push_Set;
-FpPragmaStack.Act(Loc, Action, StringRef(), 
NewFPFeatures.getAsOpaqueInt());
+if (FpPragmaStack.Stack.empty()) {
+  FpPragmaStack.Act(Loc, Sema::PSK_Set, StringRef(),
+CurFPFeatures.getAsOpaqueInt());
+}
+FpPragmaStack.Act(Loc, Sema::PSK_Push_Set, StringRef(),
+  NewFPFeatures.getAsOpaqueInt());
 break;
   case PFC_Pop:
 if (FpPragmaStack.Stack.empty()) {

diff  --git a/clang/test/CodeGen/fp-floatcontrol-pragma.cpp 
b/clang/test/CodeGen/fp-floatcontrol-pragma.cpp
index a80a4d377660..ca3a3a46aab2 100644
--- a/clang/test/CodeGen/fp-floatcontrol-pragma.cpp
+++ b/clang/test/CodeGen/fp-floatcontrol-pragma.cpp
@@ -1,6 +1,68 @@
 // RUN: %clang_cc1 -DEXCEPT=1 -fcxx-exceptions -triple x86_64-linux-gnu 
-emit-llvm -o - %s | FileCheck -check-prefix=CHECK-NS %s
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s | FileCheck %s
 // RUN: %clang_cc1 -verify -DFENV_ON=1 -triple x86_64-linux-gnu -emit-llvm -o 
- %s | FileCheck %s
+// RUN: %clang_cc1 -triple %itanium_abi_triple -O3 -emit-llvm -o - %s | 
FileCheck -check-prefix=CHECK-O3 %s
+
+// Verify float_control(precise, off) enables fast math flags on fp operations.
+float fp_precise_1(float a, float b, float c) {
+// CHECK-O3: _Z12fp_precise_1fff
+// CHECK-O3: %[[M:.+]] = fmul fast float{{.*}}
+// CHECK-O3: fadd fast float %[[M]], %c
+#pragma float_control(precise, off)
+  return a * b + c;
+}
+
+// Is float_control state cleared on exiting compound statements?
+float fp_precise_2(float a, float b, float c) {
+  // CHECK-O3: _Z12fp_precise_2fff
+  // CHECK-O3: %[[M:.+]] = fmul float{{.*}}
+  // CHECK-O3: fadd float %[[M]], %c
+  {
+#pragma float_control(precise, off)
+  }
+  return a * b + c;
+}
+
+// Does float_control survive template instantiation?
+class Foo {};
+Foo operator+(Foo, Foo);
+
+template 
+T template_muladd(T a, T b, T c) {
+#pragma float_control(precise, off)
+  return a * b + c;
+}
+
+float fp_precise_3(float a, float b, float c) {
+  // CHECK-O3: _Z12fp_precise_3fff
+  // CHECK-O3: %[[M:.+]] = fmul fast float{{.*}}
+  // CHECK-O3: fadd fast float %[[M]], %c
+  return template_muladd(a, b, c);
+}
+
+template 
+class fp_precise_4 {
+  float method(float a, float b, float c) {
+#pragma float_control(precise, off)
+return a * b + c;
+  }
+};
+
+template class fp_precise_4;
+// CHECK-O3: _ZN12fp_precise_4IiE6methodEfff
+// CHECK-O3: %[[M:.+]] = fmul fast float{{.*}}
+// CHECK-O3: fadd fast float %[[M]], %c
+
+// Check file-scoped float_control
+#pragma float_control(push)
+#pragma float_control(precise, off)
+float fp_precise_5(float a, float b, float c) {
+  // CHECK-O3: _Z12fp_precise_5fff
+  // CHECK-O3: %[[M:.+]] = fmul fast float{{.*}}
+  // CHECK-O3: fadd fast float %[[M]], %c
+  return a * b + c;
+}
+#pragma float_control(pop)
 
 float fff(float x, float y) {
 // CHECK-LABEL: define float @_Z3f{{.*}}
@@ -41,6 +103,14 @@ float check_precise(float x, float y) {
   return z;
 }
 
+float fma_test2(float a, float b, float c) {
+// CHECK-LABEL define float @_Z9fma_test2fff{{.*}}
+#pragma float_control(precise, off)
+  float x = a * b + c;
+  //CHECK: fmuladd
+  return x;
+}
+
 float fma_test1(float a, float b, float c) {
 // CHECK-LABEL define float @_Z9fma_test1fff{{.*}}
 #pragma float_control(precise, on)



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


[PATCH] D75591: [OpenMP] Add firstprivate as a default data-sharing attribute to clang

2020-05-14 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

Do you have the tests for static locals and static data members with 
`default(firstprivate)`?




Comment at: clang/lib/Parse/ParseOpenMP.cpp:2787
+  if (getLangOpts().OpenMP < 51 && Kind == OMPC_default &&
+  static_cast(Val.getValue().Type) ==
+  OMP_DEFAULT_firstprivate) {

No need for cast here. 



Comment at: clang/lib/Parse/ParseOpenMP.cpp:2789
+  OMP_DEFAULT_firstprivate) {
+// if (getLangOpts().OpenMP < 51 && Val.getValue().Type == 2) {
+Diag(Val.getValue().LOpen, diag::err_omp_invalid_dsa)

Remove this commented line of code.



Comment at: clang/lib/Parse/ParseOpenMP.cpp:2793
+<< getOpenMPClauseName(OMPC_default) << "5.1";
+  }
   return Actions.ActOnOpenMPSimpleClause(

There should be `return nullptr;` after the `Diag()`



Comment at: clang/lib/Sema/SemaOpenMP.cpp:3434-3435
+  if (Stack->getDefaultDSA() == DSA_firstprivate &&
+  VD->getStorageDuration() == SD_Static &&
+  CanonicalVD->getDeclContext()->isFileContext() &&
   !Stack->isLoopControlVariable(VD).first) {

Hmm, maybe move this check to `getDSA()`? If you do it, you can just modify the 
check on line 3322 
```
  if (DVar.CKind == OMPC_unknown && (Stack->getDefaultDSA() == DSA_none || 
(Stack->getDefaultDSA() == DSA_firstprivate && 
!Stack->isLoopControlVariable(VD).first)) &&
  isImplicitOrExplicitTaskingRegion(DKind) &&
  VarsWithInheritedDSA.count(VD) == 0) {
VarsWithInheritedDSA[VD] = E;
return;
  }
```



Comment at: clang/lib/Sema/SemaOpenMP.cpp:3441-3446
+  // Create implicit firstprivate variables as necessary under
+  // default(firstprivate).
+  if (Stack->getDefaultDSA() == DSA_firstprivate) {
 ImplicitFirstprivate.push_back(E);
 return;
   }

Hmm, not sure that this check is needed here, the next if statement should 
handle it already, no? `DVar.CKind` is set to `OMPC_firstprivate` and the next 
check must work.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75591



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


[PATCH] D79932: [analyzer] Modernize analyzer's Python scripts

2020-05-14 Thread Valeriy Savchenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc98872e3a3c0: [analyzer] Modernize analyzer's Python 
scripts (authored by vsavchenko).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79932

Files:
  clang/utils/analyzer/CmpRuns.py
  clang/utils/analyzer/SATestAdd.py
  clang/utils/analyzer/SATestBuild.py
  clang/utils/analyzer/SATestUpdateDiffs.py
  clang/utils/analyzer/SATestUtils.py
  clang/utils/analyzer/SumTimerInfo.py
  clang/utils/analyzer/exploded-graph-rewriter.py

Index: clang/utils/analyzer/exploded-graph-rewriter.py
===
--- clang/utils/analyzer/exploded-graph-rewriter.py
+++ clang/utils/analyzer/exploded-graph-rewriter.py
@@ -34,7 +34,7 @@
 
 
 # Represents any program state trait that is a dictionary of key-value pairs.
-class GenericMap(object):
+class GenericMap:
 def __init__(self, items):
 self.generic_map = collections.OrderedDict(items)
 
@@ -47,9 +47,8 @@
 
 
 # A deserialized source location.
-class SourceLocation(object):
+class SourceLocation:
 def __init__(self, json_loc):
-super(SourceLocation, self).__init__()
 logging.debug('json: %s' % json_loc)
 self.line = json_loc['line']
 self.col = json_loc['column']
@@ -63,9 +62,8 @@
 
 
 # A deserialized program point.
-class ProgramPoint(object):
+class ProgramPoint:
 def __init__(self, json_pp):
-super(ProgramPoint, self).__init__()
 self.kind = json_pp['kind']
 self.tag = json_pp['tag']
 self.node_id = json_pp['node_id']
@@ -90,9 +88,8 @@
 
 
 # A single expression acting as a key in a deserialized Environment.
-class EnvironmentBindingKey(object):
+class EnvironmentBindingKey:
 def __init__(self, json_ek):
-super(EnvironmentBindingKey, self).__init__()
 # CXXCtorInitializer is not a Stmt!
 self.stmt_id = json_ek['stmt_id'] if 'stmt_id' in json_ek \
 else json_ek['init_id']
@@ -110,9 +107,8 @@
 
 
 # Deserialized description of a location context.
-class LocationContext(object):
+class LocationContext:
 def __init__(self, json_frame):
-super(LocationContext, self).__init__()
 self.lctx_id = json_frame['lctx_id']
 self.caption = json_frame['location_context']
 self.decl = json_frame['calling']
@@ -131,9 +127,8 @@
 
 # A group of deserialized Environment bindings that correspond to a specific
 # location context.
-class EnvironmentFrame(object):
+class EnvironmentFrame:
 def __init__(self, json_frame):
-super(EnvironmentFrame, self).__init__()
 self.location_context = LocationContext(json_frame)
 self.bindings = collections.OrderedDict(
 [(EnvironmentBindingKey(b),
@@ -150,9 +145,8 @@
 
 # A deserialized Environment. This class can also hold other entities that
 # are similar to Environment, such as Objects Under Construction.
-class GenericEnvironment(object):
+class GenericEnvironment:
 def __init__(self, json_e):
-super(GenericEnvironment, self).__init__()
 self.frames = [EnvironmentFrame(f) for f in json_e]
 
 def diff_frames(self, prev):
@@ -181,9 +175,8 @@
 
 
 # A single binding key in a deserialized RegionStore cluster.
-class StoreBindingKey(object):
+class StoreBindingKey:
 def __init__(self, json_sk):
-super(StoreBindingKey, self).__init__()
 self.kind = json_sk['kind']
 self.offset = json_sk['offset']
 
@@ -198,9 +191,8 @@
 
 
 # A single cluster of the deserialized RegionStore.
-class StoreCluster(object):
+class StoreCluster:
 def __init__(self, json_sc):
-super(StoreCluster, self).__init__()
 self.base_region = json_sc['cluster']
 self.bindings = collections.OrderedDict(
 [(StoreBindingKey(b), b['value']) for b in json_sc['items']])
@@ -214,9 +206,8 @@
 
 
 # A deserialized RegionStore.
-class Store(object):
+class Store:
 def __init__(self, json_s):
-super(Store, self).__init__()
 self.ptr = json_s['pointer']
 self.clusters = collections.OrderedDict(
 [(c['pointer'], StoreCluster(c)) for c in json_s['items']])
@@ -235,9 +226,8 @@
 
 # Deserialized messages from a single checker in a single program state.
 # Basically a list of raw strings.
-class CheckerLines(object):
+class CheckerLines:
 def __init__(self, json_lines):
-super(CheckerLines, self).__init__()
 self.lines = json_lines
 
 def diff_lines(self, prev):
@@ -250,9 +240,8 @@
 
 
 # Deserialized messages of all checkers, separated by checker.
-class CheckerMessages(object):
+class CheckerMessages:
 def __init__(self, json_m):
-super(CheckerMessages, self).__init__()
 self.items = collections.OrderedDict(
 [(m['checker'], CheckerLines(m['messages'])) for m in json_m])
 
@@ -269,9 +258,8 @@
 
 
 # 

[clang] d061685 - [analyzer] Make NonNullParamChecker as dependency for StdCLibraryFunctionsChecker

2020-05-14 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2020-05-14T15:28:40+02:00
New Revision: d061685a8304eb0b6adacd24f8dd2c2ef6dfee39

URL: 
https://github.com/llvm/llvm-project/commit/d061685a8304eb0b6adacd24f8dd2c2ef6dfee39
DIFF: 
https://github.com/llvm/llvm-project/commit/d061685a8304eb0b6adacd24f8dd2c2ef6dfee39.diff

LOG: [analyzer] Make NonNullParamChecker as dependency for 
StdCLibraryFunctionsChecker

Summary:
If a given parameter in a FunctionDecl has a nonull attribute then the NonNull
constraint in StdCLibraryFunctionsChecker has the same effect as
NonNullParamChecker. I think it is better to emit diagnostics from the simpler
checker. By making NonNullParamChecker as a dependency, in these cases it will
be the first to emit a diagnostic and to stop the analysis on that path.

Reviewers: Szelethus, NoQ, baloghadamsoftware, balazske, steakhal

Subscribers: whisperity, xazax.hun, szepet, rnkovacs, a.sidorin, 
mikhail.ramalho, donat.nagy, dkrupp, gamesh411, Charusso, ASDenysPetrov, 
cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/test/Analysis/analyzer-enabled-checkers.c

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index c35f8b115f16..b4caaa0f18cb 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -293,13 +293,14 @@ let ParentPackage = APIModeling in {
 
 def StdCLibraryFunctionsChecker : Checker<"StdCLibraryFunctions">,
   HelpText<"Improve modeling of the C standard library functions">,
+  Dependencies<[NonNullParamChecker, CallAndMessageChecker]>,
   Documentation;
 
 def StdCLibraryFunctionArgsChecker : Checker<"StdCLibraryFunctionArgs">,
   HelpText<"Check constraints of arguments of C standard library functions, "
"such as whether the parameter of isalpha is in the range [0, 255] "
"or is EOF.">,
-  Dependencies<[StdCLibraryFunctionsChecker, CallAndMessageChecker]>,
+  Dependencies<[StdCLibraryFunctionsChecker]>,
   Documentation;
 
 def TrustNonnullChecker : Checker<"TrustNonnull">,

diff  --git a/clang/test/Analysis/analyzer-enabled-checkers.c 
b/clang/test/Analysis/analyzer-enabled-checkers.c
index 6f719ec15d4f..0e44b1147f04 100644
--- a/clang/test/Analysis/analyzer-enabled-checkers.c
+++ b/clang/test/Analysis/analyzer-enabled-checkers.c
@@ -6,15 +6,15 @@
 
 // CHECK:  OVERVIEW: Clang Static Analyzer Enabled Checkers List
 // CHECK-EMPTY:
-// CHECK-NEXT: apiModeling.StdCLibraryFunctions
+// CHECK-NEXT: core.NonNullParamChecker
 // CHECK-NEXT: core.CallAndMessage
+// CHECK-NEXT: apiModeling.StdCLibraryFunctions
 // CHECK-NEXT: apiModeling.StdCLibraryFunctionArgs
 // CHECK-NEXT: apiModeling.TrustNonnull
 // CHECK-NEXT: apiModeling.llvm.CastValue
 // CHECK-NEXT: apiModeling.llvm.ReturnValue
 // CHECK-NEXT: core.DivideZero
 // CHECK-NEXT: core.DynamicTypePropagation
-// CHECK-NEXT: core.NonNullParamChecker
 // CHECK-NEXT: core.NonnilStringConstants
 // CHECK-NEXT: core.NullDereference
 // CHECK-NEXT: core.StackAddrEscapeBase



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


[clang] ff4492c - [analyzer] StdLibraryFunctionsChecker: Add option to display loaded summaries

2020-05-14 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2020-05-14T15:40:58+02:00
New Revision: ff4492c89feb54e6ddfd6edaea59c98776963208

URL: 
https://github.com/llvm/llvm-project/commit/ff4492c89feb54e6ddfd6edaea59c98776963208
DIFF: 
https://github.com/llvm/llvm-project/commit/ff4492c89feb54e6ddfd6edaea59c98776963208.diff

LOG: [analyzer] StdLibraryFunctionsChecker: Add option to display loaded 
summaries

Reviewers: NoQ, Szelethus, baloghadamsoftware, balazske

Subscribers: whisperity, xazax.hun, szepet, rnkovacs, a.sidorin, 
mikhail.ramalho, donat.nagy, dkrupp, gamesh411, Charusso, steakhal, 
ASDenysPetrov, cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
clang/test/Analysis/analyzer-config.c
clang/test/Analysis/std-c-library-functions.c

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index b4caaa0f18cb..5cf32ac03436 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -294,6 +294,14 @@ let ParentPackage = APIModeling in {
 def StdCLibraryFunctionsChecker : Checker<"StdCLibraryFunctions">,
   HelpText<"Improve modeling of the C standard library functions">,
   Dependencies<[NonNullParamChecker, CallAndMessageChecker]>,
+  CheckerOptions<[
+CmdLineOption
+  ]>,
   Documentation;
 
 def StdCLibraryFunctionArgsChecker : Checker<"StdCLibraryFunctionArgs">,

diff  --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index b9719a086668..b8d52f096e1c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -300,6 +300,8 @@ class StdLibraryFunctionsChecker
   DefaultBool ChecksEnabled[CK_NumCheckKinds];
   CheckerNameRef CheckNames[CK_NumCheckKinds];
 
+  bool DisplayLoadedSummaries = false;
+
 private:
   Optional findFunctionSummary(const FunctionDecl *FD,
 CheckerContext &C) const;
@@ -639,8 +641,12 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
   struct AddToFunctionSummaryMap {
 const ASTContext &ACtx;
 FunctionSummaryMapType ⤅
-AddToFunctionSummaryMap(const ASTContext &ACtx, FunctionSummaryMapType 
&FSM)
-: ACtx(ACtx), Map(FSM) {}
+bool DisplayLoadedSummaries;
+AddToFunctionSummaryMap(const ASTContext &ACtx, FunctionSummaryMapType 
&FSM,
+bool DisplayLoadedSummaries)
+: ACtx(ACtx), Map(FSM), DisplayLoadedSummaries(DisplayLoadedSummaries) 
{
+}
+
 // Add a summary to a FunctionDecl found by lookup. The lookup is performed
 // by the given Name, and in the global scope. The summary will be attached
 // to the found FunctionDecl only if the signatures match.
@@ -655,6 +661,11 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 auto Res = Map.insert({FD->getCanonicalDecl(), S});
 assert(Res.second && "Function already has a summary set!");
 (void)Res;
+if (DisplayLoadedSummaries) {
+  llvm::errs() << "Loaded summary for: ";
+  FD->print(llvm::errs());
+  llvm::errs() << "\n";
+}
 return;
   }
 }
@@ -665,7 +676,7 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
   for (const Summary &S : Summaries)
 operator()(Name, S);
 }
-  } addToFunctionSummaryMap(ACtx, FunctionSummaryMap);
+  } addToFunctionSummaryMap(ACtx, FunctionSummaryMap, DisplayLoadedSummaries);
 
   // We are finally ready to define specifications for all supported functions.
   //
@@ -937,7 +948,10 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 }
 
 void ento::registerStdCLibraryFunctionsChecker(CheckerManager &mgr) {
-  mgr.registerChecker();
+  auto *Checker = mgr.registerChecker();
+  Checker->DisplayLoadedSummaries =
+  mgr.getAnalyzerOptions().getCheckerBooleanOption(
+  Checker, "DisplayLoadedSummaries");
 }
 
 bool ento::shouldRegisterStdCLibraryFunctionsChecker(const CheckerManager 
&mgr) {

diff  --git a/clang/test/Analysis/analyzer-config.c 
b/clang/test/Analysis/analyzer-config.c
index 226c02012c59..b94f618d7492 100644
--- a/clang/test/Analysis/analyzer-config.c
+++ b/clang/test/Analysis/analyzer-config.c
@@ -11,6 +11,7 @@
 // CHECK-NEXT: alpha.security.MmapWriteExec:MmapProtExec = 0x04
 // CHECK-NEXT: alpha.security.MmapWriteExec:MmapProtRead = 0x01
 // CHECK-NEXT: alpha.security.taint.TaintPropagation:Config = ""
+// CHECK-NEXT: apiModeling.StdCLibraryFunctions:DisplayLoadedSummaries = false
 // CHECK-NEXT: apply-fixits

[clang] 7c37684 - [analyzer] Improve PlacementNewChecker

2020-05-14 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2020-05-14T15:50:39+02:00
New Revision: 7c3768495e8c1599dc30986f7bd47d5e91f303f2

URL: 
https://github.com/llvm/llvm-project/commit/7c3768495e8c1599dc30986f7bd47d5e91f303f2
DIFF: 
https://github.com/llvm/llvm-project/commit/7c3768495e8c1599dc30986f7bd47d5e91f303f2.diff

LOG: [analyzer] Improve PlacementNewChecker

Summary:
1. Added insufficient storage check for arrays
2. Added align support check

Based on https://reviews.llvm.org/D76229

Reviewers: aaron.ballman, lebedev.ri, NoQ, martong

Reviewed By: martong

Subscribers: xazax.hun, baloghadamsoftware, szepet, rnkovacs, a.sidorin, 
mikhail.ramalho, Szelethus, donat.nagy, dkrupp, Charusso, ASDenysPetrov, 
cfe-commits

Tags: #clang

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

Patch by Karasev Nikita!

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp
clang/test/Analysis/placement-new.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp
index 43ed0ffb238d..fec9fb59b2eb 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp
@@ -25,22 +25,47 @@ class PlacementNewChecker : public 
Checker> {
   void checkPreStmt(const CXXNewExpr *NE, CheckerContext &C) const;
 
 private:
+  bool checkPlaceCapacityIsSufficient(const CXXNewExpr *NE,
+  CheckerContext &C) const;
+
+  bool checkPlaceIsAlignedProperly(const CXXNewExpr *NE,
+   CheckerContext &C) const;
+
   // Returns the size of the target in a placement new expression.
   // E.g. in "new (&s) long" it returns the size of `long`.
-  SVal getExtentSizeOfNewTarget(const CXXNewExpr *NE, ProgramStateRef State,
-CheckerContext &C) const;
+  SVal getExtentSizeOfNewTarget(const CXXNewExpr *NE, CheckerContext &C,
+bool &IsArray) const;
   // Returns the size of the place in a placement new expression.
   // E.g. in "new (&s) long" it returns the size of `s`.
-  SVal getExtentSizeOfPlace(const Expr *NE, ProgramStateRef State,
-CheckerContext &C) const;
-  BugType BT{this, "Insufficient storage for placement new",
- categories::MemoryError};
+  SVal getExtentSizeOfPlace(const CXXNewExpr *NE, CheckerContext &C) const;
+
+  void emitBadAlignReport(const Expr *P, CheckerContext &C,
+  unsigned AllocatedTAlign,
+  unsigned StorageTAlign) const;
+  unsigned getStorageAlign(CheckerContext &C, const ValueDecl *VD) const;
+
+  void checkElementRegionAlign(const ElementRegion *R, CheckerContext &C,
+   const Expr *P, unsigned AllocatedTAlign) const;
+
+  void checkFieldRegionAlign(const FieldRegion *R, CheckerContext &C,
+ const Expr *P, unsigned AllocatedTAlign) const;
+
+  bool isVarRegionAlignedProperly(const VarRegion *R, CheckerContext &C,
+  const Expr *P,
+  unsigned AllocatedTAlign) const;
+
+  BugType SBT{this, "Insufficient storage for placement new",
+  categories::MemoryError};
+  BugType ABT{this, "Bad align storage for placement new",
+  categories::MemoryError};
 };
 } // namespace
 
-SVal PlacementNewChecker::getExtentSizeOfPlace(const Expr *Place,
-   ProgramStateRef State,
+SVal PlacementNewChecker::getExtentSizeOfPlace(const CXXNewExpr *NE,
CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  const Expr *Place = NE->getPlacementArg(0);
+
   const MemRegion *MRegion = C.getSVal(Place).getAsRegion();
   if (!MRegion)
 return UnknownVal();
@@ -63,13 +88,16 @@ SVal PlacementNewChecker::getExtentSizeOfPlace(const Expr 
*Place,
 }
 
 SVal PlacementNewChecker::getExtentSizeOfNewTarget(const CXXNewExpr *NE,
-   ProgramStateRef State,
-   CheckerContext &C) const {
+   CheckerContext &C,
+   bool &IsArray) const {
+  ProgramStateRef State = C.getState();
   SValBuilder &SvalBuilder = C.getSValBuilder();
   QualType ElementType = NE->getAllocatedType();
   ASTContext &AstContext = C.getASTContext();
   CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
+  IsArray = false;
   if (NE->isArray()) {
+IsArray = true;
 const Expr *SizeExpr = *NE->getArraySize();
 SVal ElementCount = C.getSVal(SizeExpr);
 if (auto ElementCountNL = ElementCount.getAs()) {
@@ -91,38 +119,212 @@ SVal PlacementNewChecker::getExtentSizeO

[PATCH] D79942: [clang] Add an API to retrieve implicit constructor arguments.

2020-05-14 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
mboehme added a project: clang.
Herald added a subscriber: cfe-commits.

This is needed in Swift for C++ interop.

As part of this change, I've had to make some changes to the interface of 
CGCXXABI to return the additional parameters separately rather than adding them 
directly to a `CallArgList`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D79942

Files:
  clang/include/clang/CodeGen/CodeGenABITypes.h
  clang/lib/CodeGen/CGCXXABI.cpp
  clang/lib/CodeGen/CGCXXABI.h
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGClass.cpp
  clang/lib/CodeGen/CodeGenABITypes.cpp
  clang/lib/CodeGen/ItaniumCXXABI.cpp
  clang/lib/CodeGen/MicrosoftCXXABI.cpp

Index: clang/lib/CodeGen/MicrosoftCXXABI.cpp
===
--- clang/lib/CodeGen/MicrosoftCXXABI.cpp
+++ clang/lib/CodeGen/MicrosoftCXXABI.cpp
@@ -206,7 +206,7 @@
   // lacks a definition for the destructor, non-base destructors must always
   // delegate to or alias the base destructor.
 
-  AddedStructorArgs
+  AddedStructorArgCounts
   buildStructorSignature(GlobalDecl GD,
  SmallVectorImpl &ArgTys) override;
 
@@ -253,10 +253,11 @@
 
   void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
 
-  AddedStructorArgs
-  addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
- CXXCtorType Type, bool ForVirtualBase,
- bool Delegating, CallArgList &Args) override;
+  AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
+   const CXXConstructorDecl *D,
+   CXXCtorType Type,
+   bool ForVirtualBase,
+   bool Delegating) override;
 
   void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
   CXXDtorType Type, bool ForVirtualBase,
@@ -1261,10 +1262,10 @@
   }
 }
 
-CGCXXABI::AddedStructorArgs
+CGCXXABI::AddedStructorArgCounts
 MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
 SmallVectorImpl &ArgTys) {
-  AddedStructorArgs Added;
+  AddedStructorArgCounts Added;
   // TODO: 'for base' flag
   if (isa(GD.getDecl()) &&
   GD.getDtorType() == Dtor_Deleting) {
@@ -1553,9 +1554,9 @@
   }
 }
 
-CGCXXABI::AddedStructorArgs MicrosoftCXXABI::addImplicitConstructorArgs(
+CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(
 CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
-bool ForVirtualBase, bool Delegating, CallArgList &Args) {
+bool ForVirtualBase, bool Delegating) {
   assert(Type == Ctor_Complete || Type == Ctor_Base);
 
   // Check if we need a 'most_derived' parameter.
@@ -1570,13 +1571,10 @@
   } else {
 MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
   }
-  RValue RV = RValue::get(MostDerivedArg);
   if (FPT->isVariadic()) {
-Args.insert(Args.begin() + 1, CallArg(RV, getContext().IntTy));
-return AddedStructorArgs::prefix(1);
+return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});
   }
-  Args.add(RV, getContext().IntTy);
-  return AddedStructorArgs::suffix(1);
+  return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});
 }
 
 void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
@@ -4009,7 +4007,7 @@
   CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
 
   // Insert any ABI-specific implicit constructor arguments.
-  AddedStructorArgs ExtraArgs =
+  AddedStructorArgCounts ExtraArgs =
   addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
  /*ForVirtualBase=*/false,
  /*Delegating=*/false, Args);
Index: clang/lib/CodeGen/ItaniumCXXABI.cpp
===
--- clang/lib/CodeGen/ItaniumCXXABI.cpp
+++ clang/lib/CodeGen/ItaniumCXXABI.cpp
@@ -203,7 +203,7 @@
 
   void EmitCXXConstructors(const CXXConstructorDecl *D) override;
 
-  AddedStructorArgs
+  AddedStructorArgCounts
   buildStructorSignature(GlobalDecl GD,
  SmallVectorImpl &ArgTys) override;
 
@@ -222,10 +222,11 @@
 
   void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
 
-  AddedStructorArgs
-  addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D,
- CXXCtorType Type, bool ForVirtualBase,
- bool Delegating, CallArgList &Args) override;
+  AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
+   const CXXConstructorDecl *D,
+   CXXCtorType Type,
+   bool ForVirtualBase,
+  

[PATCH] D79330: [Analyzer][VLASizeChecker] Check for VLA size overflow.

2020-05-14 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

Is it worth to improve the checker by emitting a warning only if a `sizeof` is 
used on a `typedef`-ed VLA type where the size is too large (and at a VLA 
declaration with size overflow)? Or can this be done in a later change?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79330



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


[PATCH] D69520: [libc++] Disallow dynamic -> static span conversions

2020-05-14 Thread Louis Dionne via Phabricator via cfe-commits
ldionne commandeered this revision.
ldionne edited reviewers, added: jdoerrie; removed: ldionne.
ldionne added a comment.
Herald added subscribers: broadwaylamb, jkorous.

In D69520#1878360 , @miscco wrote:

> I believe this is superseded by the implementation of P1976R2 in D74577 
> 


@miscco  Can you please look at the tests in this patch and salvage any test 
you might have omitted from your own patch?

@jdoerrie I'm sorry there was some confusion and duplicate work, but thanks for 
your contribution nonetheless!


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

https://reviews.llvm.org/D69520



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


[PATCH] D79704: [Analyzer] [NFC] Parameter Regions

2020-05-14 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware marked an inline comment as done.
baloghadamsoftware added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/MemRegion.cpp:191
+const ParmVarDecl *ParamRegion::getDecl() const {
+  const Decl *D = getStackFrame()->getDecl();
+

NoQ wrote:
> baloghadamsoftware wrote:
> > NoQ wrote:
> > > This doesn't work when the callee is unknown.
> > Please give me an example where the callee is unknown. As I wrote, 
> > originally I put a `getExpr()` method here as well and `getType()` fell 
> > back to it if it could not find the `Decl()`. However, it was never invoked 
> > on the whole test suite. (I put an `assert(false)` into it, and did not get 
> > a crash.
> > Please give me an example where the callee is unknown.
> 
> >>! In D79704#2034571, @NoQ wrote:
> >>>! In D79704#2032947, @Szelethus wrote:
> >> Could you give a specific code example? 
> > 
> > ```lang=c++
> > struct S {
> >   S() {
> > this; // What region does 'this' point to...
> >   }
> > };
> > 
> > void foo(void (*bar)(S)) {
> >   bar(S()); // ...in this invocation?
> > }
> > ```
OK, but it still does not crash the analyzer, even if I enable creation of 
stack frames for all the callees, even for those without definition. What else 
should I do to enforce the crash (null pointer dereference)? Try to use 
`getParameterLocation()` in a unit test?


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

https://reviews.llvm.org/D79704



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


[PATCH] D76996: [analyzer] Improve PlacementNewChecker

2020-05-14 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Thanks, just committed.


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

https://reviews.llvm.org/D76996



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


[PATCH] D79420: [analyzer] Make NonNullParamChecker as dependency for StdCLibraryFunctionsChecker

2020-05-14 Thread Gabor Marton via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd061685a8304: [analyzer] Make NonNullParamChecker as 
dependency for… (authored by martong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79420

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/test/Analysis/analyzer-enabled-checkers.c


Index: clang/test/Analysis/analyzer-enabled-checkers.c
===
--- clang/test/Analysis/analyzer-enabled-checkers.c
+++ clang/test/Analysis/analyzer-enabled-checkers.c
@@ -6,15 +6,15 @@
 
 // CHECK:  OVERVIEW: Clang Static Analyzer Enabled Checkers List
 // CHECK-EMPTY:
-// CHECK-NEXT: apiModeling.StdCLibraryFunctions
+// CHECK-NEXT: core.NonNullParamChecker
 // CHECK-NEXT: core.CallAndMessage
+// CHECK-NEXT: apiModeling.StdCLibraryFunctions
 // CHECK-NEXT: apiModeling.StdCLibraryFunctionArgs
 // CHECK-NEXT: apiModeling.TrustNonnull
 // CHECK-NEXT: apiModeling.llvm.CastValue
 // CHECK-NEXT: apiModeling.llvm.ReturnValue
 // CHECK-NEXT: core.DivideZero
 // CHECK-NEXT: core.DynamicTypePropagation
-// CHECK-NEXT: core.NonNullParamChecker
 // CHECK-NEXT: core.NonnilStringConstants
 // CHECK-NEXT: core.NullDereference
 // CHECK-NEXT: core.StackAddrEscapeBase
Index: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
===
--- clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -293,13 +293,14 @@
 
 def StdCLibraryFunctionsChecker : Checker<"StdCLibraryFunctions">,
   HelpText<"Improve modeling of the C standard library functions">,
+  Dependencies<[NonNullParamChecker, CallAndMessageChecker]>,
   Documentation;
 
 def StdCLibraryFunctionArgsChecker : Checker<"StdCLibraryFunctionArgs">,
   HelpText<"Check constraints of arguments of C standard library functions, "
"such as whether the parameter of isalpha is in the range [0, 255] "
"or is EOF.">,
-  Dependencies<[StdCLibraryFunctionsChecker, CallAndMessageChecker]>,
+  Dependencies<[StdCLibraryFunctionsChecker]>,
   Documentation;
 
 def TrustNonnullChecker : Checker<"TrustNonnull">,


Index: clang/test/Analysis/analyzer-enabled-checkers.c
===
--- clang/test/Analysis/analyzer-enabled-checkers.c
+++ clang/test/Analysis/analyzer-enabled-checkers.c
@@ -6,15 +6,15 @@
 
 // CHECK:  OVERVIEW: Clang Static Analyzer Enabled Checkers List
 // CHECK-EMPTY:
-// CHECK-NEXT: apiModeling.StdCLibraryFunctions
+// CHECK-NEXT: core.NonNullParamChecker
 // CHECK-NEXT: core.CallAndMessage
+// CHECK-NEXT: apiModeling.StdCLibraryFunctions
 // CHECK-NEXT: apiModeling.StdCLibraryFunctionArgs
 // CHECK-NEXT: apiModeling.TrustNonnull
 // CHECK-NEXT: apiModeling.llvm.CastValue
 // CHECK-NEXT: apiModeling.llvm.ReturnValue
 // CHECK-NEXT: core.DivideZero
 // CHECK-NEXT: core.DynamicTypePropagation
-// CHECK-NEXT: core.NonNullParamChecker
 // CHECK-NEXT: core.NonnilStringConstants
 // CHECK-NEXT: core.NullDereference
 // CHECK-NEXT: core.StackAddrEscapeBase
Index: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
===
--- clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -293,13 +293,14 @@
 
 def StdCLibraryFunctionsChecker : Checker<"StdCLibraryFunctions">,
   HelpText<"Improve modeling of the C standard library functions">,
+  Dependencies<[NonNullParamChecker, CallAndMessageChecker]>,
   Documentation;
 
 def StdCLibraryFunctionArgsChecker : Checker<"StdCLibraryFunctionArgs">,
   HelpText<"Check constraints of arguments of C standard library functions, "
"such as whether the parameter of isalpha is in the range [0, 255] "
"or is EOF.">,
-  Dependencies<[StdCLibraryFunctionsChecker, CallAndMessageChecker]>,
+  Dependencies<[StdCLibraryFunctionsChecker]>,
   Documentation;
 
 def TrustNonnullChecker : Checker<"TrustNonnull">,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D78118: [analyzer] StdLibraryFunctionsChecker: Add option to display loaded summaries

2020-05-14 Thread Gabor Marton via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGff4492c89feb: [analyzer] StdLibraryFunctionsChecker: Add 
option to display loaded summaries (authored by martong).

Changed prior to commit:
  https://reviews.llvm.org/D78118?vs=260930&id=263992#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78118

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/std-c-library-functions.c

Index: clang/test/Analysis/std-c-library-functions.c
===
--- clang/test/Analysis/std-c-library-functions.c
+++ clang/test/Analysis/std-c-library-functions.c
@@ -30,6 +30,35 @@
 // RUN:   -triple thumbv7-a15-linux \
 // RUN:   -verify
 
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:DisplayLoadedSummaries=true \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -triple i686-unknown-linux 2>&1 | FileCheck %s
+
+//  CHECK: Loaded summary for: int isalnum(int)
+// CHECK-NEXT: Loaded summary for: int isalpha(int)
+// CHECK-NEXT: Loaded summary for: int isascii(int)
+// CHECK-NEXT: Loaded summary for: int isblank(int)
+// CHECK-NEXT: Loaded summary for: int isdigit(int)
+// CHECK-NEXT: Loaded summary for: int isgraph(int)
+// CHECK-NEXT: Loaded summary for: int islower(int)
+// CHECK-NEXT: Loaded summary for: int isprint(int)
+// CHECK-NEXT: Loaded summary for: int ispunct(int)
+// CHECK-NEXT: Loaded summary for: int isspace(int)
+// CHECK-NEXT: Loaded summary for: int isupper(int)
+// CHECK-NEXT: Loaded summary for: int isxdigit(int)
+// CHECK-NEXT: Loaded summary for: int getc(FILE *)
+// CHECK-NEXT: Loaded summary for: int fgetc(FILE *)
+// CHECK-NEXT: Loaded summary for: int getchar()
+// CHECK-NEXT: Loaded summary for: ssize_t read(int, void *, size_t)
+// CHECK-NEXT: Loaded summary for: ssize_t write(int, const void *, size_t)
+// CHECK-NEXT: Loaded summary for: unsigned int fread(void *restrict, size_t, size_t, FILE *)
+// CHECK-NEXT: Loaded summary for: unsigned int fwrite(const void *restrict, size_t, size_t, FILE *restrict)
+// CHECK-NEXT: Loaded summary for: ssize_t getline(char **, size_t *, FILE *)
+
 void clang_analyzer_eval(int);
 
 int glob;
Index: clang/test/Analysis/analyzer-config.c
===
--- clang/test/Analysis/analyzer-config.c
+++ clang/test/Analysis/analyzer-config.c
@@ -11,6 +11,7 @@
 // CHECK-NEXT: alpha.security.MmapWriteExec:MmapProtExec = 0x04
 // CHECK-NEXT: alpha.security.MmapWriteExec:MmapProtRead = 0x01
 // CHECK-NEXT: alpha.security.taint.TaintPropagation:Config = ""
+// CHECK-NEXT: apiModeling.StdCLibraryFunctions:DisplayLoadedSummaries = false
 // CHECK-NEXT: apply-fixits = false
 // CHECK-NEXT: avoid-suppressing-null-argument-paths = false
 // CHECK-NEXT: c++-allocator-inlining = true
@@ -106,4 +107,4 @@
 // CHECK-NEXT: unroll-loops = false
 // CHECK-NEXT: widen-loops = false
 // CHECK-NEXT: [stats]
-// CHECK-NEXT: num-entries = 103
+// CHECK-NEXT: num-entries = 104
Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -300,6 +300,8 @@
   DefaultBool ChecksEnabled[CK_NumCheckKinds];
   CheckerNameRef CheckNames[CK_NumCheckKinds];
 
+  bool DisplayLoadedSummaries = false;
+
 private:
   Optional findFunctionSummary(const FunctionDecl *FD,
 CheckerContext &C) const;
@@ -639,8 +641,12 @@
   struct AddToFunctionSummaryMap {
 const ASTContext &ACtx;
 FunctionSummaryMapType ⤅
-AddToFunctionSummaryMap(const ASTContext &ACtx, FunctionSummaryMapType &FSM)
-: ACtx(ACtx), Map(FSM) {}
+bool DisplayLoadedSummaries;
+AddToFunctionSummaryMap(const ASTContext &ACtx, FunctionSummaryMapType &FSM,
+bool DisplayLoadedSummaries)
+: ACtx(ACtx), Map(FSM), DisplayLoadedSummaries(DisplayLoadedSummaries) {
+}
+
 // Add a summary to a FunctionDecl found by lookup. The lookup is performed
 // by the given Name, and in the global scope. The summary will be attached
 // to the found FunctionDecl only if the signatures match.
@@ -655,6 +661,11 @@
 auto Res = Map.insert({FD->getCanonicalDecl(), S});
 assert(Res.second && "Function already has a summary set!");
 (void)Res;
+if (DisplayLoadedSummaries) {
+  llvm::errs() << "Loaded summa

[PATCH] D76996: [analyzer] Improve PlacementNewChecker

2020-05-14 Thread Gabor Marton via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7c3768495e8c: [analyzer] Improve PlacementNewChecker 
(authored by martong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76996

Files:
  clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp
  clang/test/Analysis/placement-new.cpp

Index: clang/test/Analysis/placement-new.cpp
===
--- clang/test/Analysis/placement-new.cpp
+++ clang/test/Analysis/placement-new.cpp
@@ -155,3 +155,309 @@
   (void)dp;
 }
 } // namespace testHierarchy
+
+namespace testArrayTypesAllocation {
+void f1() {
+  struct S {
+short a;
+  };
+
+  // bad (not enough space).
+  const unsigned N = 32;
+  alignas(S) unsigned char buffer1[sizeof(S) * N]; // expected-note {{'buffer1' initialized here}}
+  ::new (buffer1) S[N];// expected-warning{{Storage provided to placement new is only 64 bytes, whereas the allocated array type requires more space for internal needs}} expected-note 1 {{}}
+}
+
+void f2() {
+  struct S {
+short a;
+  };
+
+  // maybe ok but we need to warn.
+  const unsigned N = 32;
+  alignas(S) unsigned char buffer2[sizeof(S) * N + sizeof(int)]; // expected-note {{'buffer2' initialized here}}
+  ::new (buffer2) S[N];  // expected-warning{{68 bytes is possibly not enough for array allocation which requires 64 bytes. Current overhead requires the size of 4 bytes}} expected-note 1 {{}}
+}
+} // namespace testArrayTypesAllocation
+
+namespace testStructAlign {
+void f1() {
+  struct X {
+char a[9];
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // bad (struct X is aligned to char).
+  ::new (&Xi.a) long; // expected-warning{{Storage type is aligned to 1 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f2() {
+  struct X {
+char a;
+char b;
+long c;
+  } Xi;
+
+  // ok (struct X is aligned to long).
+  ::new (&Xi.a) long;
+}
+
+void f3() {
+  struct X {
+char a;
+char b;
+long c;
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // bad (struct X is aligned to long but field 'b' is aligned to 1 because of its offset)
+  ::new (&Xi.b) long; // expected-warning{{Storage type is aligned to 1 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f4() {
+  struct X {
+char a;
+struct alignas(alignof(short)) Y {
+  char b;
+  char c;
+} y;
+long d;
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // bad. 'b' is aligned to short
+  ::new (&Xi.y.b) long; // expected-warning{{Storage type is aligned to 2 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f5() {
+  short b[10]; // expected-note {{'b' initialized here}}
+
+  ::new (&b) long; // expected-warning{{Storage type is aligned to 2 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f6() {
+  short b[10]; // expected-note {{'b' initialized here}}
+
+  // bad (same as previous but checks ElementRegion case)
+  ::new (&b[0]) long; // expected-warning{{Storage type is aligned to 2 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f7() {
+  alignas(alignof(long)) short b[10];
+
+  // ok. aligned to long(ok). offset 4*2(ok)
+  ::new (&b[4]) long;
+}
+
+void f8() {
+  alignas(alignof(long)) short b[10]; // expected-note {{'b' initialized here}}
+
+  // ok. aligned to long(ok). offset 3*2(ok)
+  ::new (&b[3]) long; // expected-warning{{Storage type is aligned to 6 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f9() {
+  struct X {
+char a;
+alignas(alignof(long)) char b[20];
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // ok. aligned to long(ok). offset 8*1(ok)
+  ::new (&Xi.b[8]) long;
+
+  // bad. aligned to long(ok). offset 1*1(ok)
+  ::new (&Xi.b[1]) long; // expected-warning{{Storage type is aligned to 1 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f10() {
+  struct X {
+char a[8];
+alignas(2) char b;
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // bad (struct X is aligned to 2).
+  ::new (&Xi.a) long; // expected-warning{{Storage type is aligned to 2 bytes but allocated type is aligned to 8 bytes}} expected-note 1 {{}}
+}
+
+void f11() {
+  struct X {
+char a;
+char b;
+struct Y {
+  long c;
+} d;
+  } Xi;
+
+  // ok (struct X is aligned to long).
+  ::new (&Xi.a) long;
+}
+
+void f12() {
+  struct alignas(alignof(long)) X {
+char a;
+char b;
+  } Xi;
+
+  // ok (struct X is aligned to long).
+  ::new (&Xi.a) long;
+}
+
+void test13() {
+  struct Y {
+char a[10];
+  };
+
+  struct X {
+Y b[10];
+  } Xi; // expected-note {{'Xi' initialized here}}
+
+  // bad. X,A are aligned to 'char'
+  ::new (&Xi.b[0

[clang] 5f1f4a5 - Prohibit capture of _ExtInt in inline assembly.

2020-05-14 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2020-05-14T07:21:09-07:00
New Revision: 5f1f4a5d0157c11e0a88d9a273f49c8f866b01ef

URL: 
https://github.com/llvm/llvm-project/commit/5f1f4a5d0157c11e0a88d9a273f49c8f866b01ef
DIFF: 
https://github.com/llvm/llvm-project/commit/5f1f4a5d0157c11e0a88d9a273f49c8f866b01ef.diff

LOG: Prohibit capture of _ExtInt in inline assembly.

The backends don't seem to properly handle the _ExtInt type in inline
assembly with crashes occurring in many. While the ones I tested seem to
work for powers of 2 < 64 (and some any multiple of 64 greater than
that), it seemed like a better idea to just use of this type in inline
assembly prohibited.

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticCommonKinds.td
clang/lib/Sema/SemaStmtAsm.cpp
clang/test/SemaCXX/ext-int.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticCommonKinds.td 
b/clang/include/clang/Basic/DiagnosticCommonKinds.td
index 5d8c939283b5..73f55784234e 100644
--- a/clang/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/clang/include/clang/Basic/DiagnosticCommonKinds.td
@@ -240,6 +240,9 @@ let CategoryName = "Inline Assembly Issue" in {
   def err_asm_invalid_type_in_input : Error<
 "invalid type %0 in asm input for constraint '%1'">;
 
+  def err_asm_invalid_type : Error<
+"invalid type %0 in asm %select{input|output}1">;
+
   def warn_stack_clash_protection_inline_asm : Warning<
 "Unable to protect inline asm that clobbers stack pointer against stack 
clash">,
 InGroup>;

diff  --git a/clang/lib/Sema/SemaStmtAsm.cpp b/clang/lib/Sema/SemaStmtAsm.cpp
index 82a308f35c21..10fa24682f9c 100644
--- a/clang/lib/Sema/SemaStmtAsm.cpp
+++ b/clang/lib/Sema/SemaStmtAsm.cpp
@@ -296,6 +296,14 @@ StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, 
bool IsSimple,
 checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false))
   return StmtError();
 
+// Disallow _ExtInt, since the backends tend to have 
diff iculties with
+// non-normal sizes.
+if (OutputExpr->getType()->isExtIntType())
+  return StmtError(
+  Diag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_type)
+  << OutputExpr->getType() << 0 /*Input*/
+  << OutputExpr->getSourceRange());
+
 OutputConstraintInfos.push_back(Info);
 
 // If this is dependent, just continue.
@@ -420,6 +428,12 @@ StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, 
bool IsSimple,
   }
 }
 
+if (InputExpr->getType()->isExtIntType())
+  return StmtError(
+  Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type)
+  << InputExpr->getType() << 1 /*Output*/
+  << InputExpr->getSourceRange());
+
 InputConstraintInfos.push_back(Info);
 
 const Type *Ty = Exprs[i]->getType().getTypePtr();
@@ -892,6 +906,15 @@ StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, 
SourceLocation LBraceLoc,
 SourceLocation EndLoc) {
   bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
   setFunctionHasBranchProtectedScope();
+
+  for (uint64_t I = 0; I < NumOutputs + NumInputs; ++I) {
+if (Exprs[I]->getType()->isExtIntType())
+  return StmtError(
+  Diag(Exprs[I]->getBeginLoc(), diag::err_asm_invalid_type)
+  << Exprs[I]->getType() << (I < NumOutputs)
+  << Exprs[I]->getSourceRange());
+  }
+
   MSAsmStmt *NS =
 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
 /*IsVolatile*/ true, AsmToks, NumOutputs, 
NumInputs,

diff  --git a/clang/test/SemaCXX/ext-int.cpp b/clang/test/SemaCXX/ext-int.cpp
index cf94fd17162a..a5e87eb878d3 100644
--- a/clang/test/SemaCXX/ext-int.cpp
+++ b/clang/test/SemaCXX/ext-int.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s -Wimplicit-int-conversion -triple 
x86_64-gnu-linux
+// RUN: %clang_cc1 -fsyntax-only -verify %s -Wimplicit-int-conversion -triple 
x86_64-gnu-linux -fasm-blocks
 
 template
 struct HasExtInt {
@@ -276,3 +276,12 @@ void ImplicitCasts(_ExtInt(31) s31, _ExtInt(33) s33, int 
i) {
   i = s33;
 }
 
+
+void NotAllowedInInlineAsm(_ExtInt(9) in, _ExtInt(9) out) {
+  __asm { mov eax, in} // expected-error{{invalid type '_ExtInt(9)' in asm 
input}}
+  __asm { mov out, eax} // expected-error{{invalid type '_ExtInt(9)' in asm 
output}}
+
+  asm("" : "=g" (in));// expected-error{{invalid type '_ExtInt(9)' in asm 
input}}
+  asm("" :: "r" (out));// expected-error{{invalid type '_ExtInt(9)' in asm 
output}}
+
+}



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


[PATCH] D79903: FastMathFlags.allowContract should be init from FPFeatures.allowFPContractAcrossStatement

2020-05-14 Thread Melanie Blower via Phabricator via cfe-commits
mibintc marked 2 inline comments as done.
mibintc added inline comments.



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:2943
+  if (Opts.FastRelaxedMath)
+Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
   Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);

rjmccall wrote:
> mibintc wrote:
> > rjmccall wrote:
> > > mibintc wrote:
> > > > I changed this because the FAST version of this test 
> > > > clang/test/CodeGenOpenCL/relaxed-fpmath.cl wants the 'fast' attribute 
> > > > on the instruction dump.  All the LLVM FMF bits must be set for the 
> > > > fast attribute print.  By default, the value for OpenCL is 
> > > > ffp-contract=on
> > > Is there an overall behavior change for OpenCL across these patches?
> > I think the answer to your question is no.  Here is more details: OpenCL 
> > sets the default behavior to ffp-contract=on.  In 
> > https://reviews.llvm.org/D72841 I added the function UpdateFastMathFlags, 
> > that function set the llvm FMF.allowContract bit to be ( ffp-contract=on or 
> > ffp-contract=fast).  This patch just drops the check on ffp-contract=on.   
> > I didn't wind back to see how the llvm fast attribute was being set for 
> > this [opencl] test case originally. 
> Well, to what extent are there (including this patch) overall test changes 
> for the OpenCL tests, and what are tthey?
In the #pragma float_control patch https://reviews.llvm.org/D72841, I changed 2 
CodeGen/OpenCL tests: relaxed-fp-math.cl in the non-FAST cases to show the 
contract bit.  Also 1 line in single-precision-constant.cl for the same reason, 
to show the contract bit.  This patch undoes those test changes. I'll do more 
investigation to understand why the fast bit isn't being set in the FAST case 
in relaxed-fpmath.cl without the change to CompilerInovcaton



Comment at: clang/lib/Sema/SemaAttr.cpp:460
   case PFC_Push:
-Action = Sema::PSK_Push_Set;
-FpPragmaStack.Act(Loc, Action, StringRef(), 
NewFPFeatures.getAsOpaqueInt());
+if (FpPragmaStack.Stack.empty()) {
+  FpPragmaStack.Act(Loc, Sema::PSK_Set, StringRef(),

rjmccall wrote:
> mibintc wrote:
> > When i was adding a test, I realized that pragma float_control(push) then 
> > pop wasn't working as expected. If the stack is empty, which is most of the 
> > time, first need to push the current fp features onto the stack so they can 
> > be restored at the pop
> It seems that the way `PragmaStack` is supposed to be used is that we're 
> supposed to be using its `CurrentValue` instead of having a separate 
> `CurFPFeatures`.  But mostly it looks like there's a lot of functionality 
> associated with `PragmaStack` that we aren't using at all because this is a 
> substantially simpler mode; we could really just be using a 
> `SmallVector`.
> 
> Anyway, I guess this fix works, although it should be done in a separate 
> patch.
I'll submit it in a separate patch. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79903



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


[PATCH] D79423: [analyzer][NFC] StdLibraryFunctionsChecker: Add empty Signatures

2020-05-14 Thread Gabor Marton via Phabricator via cfe-commits
martong planned changes to this revision.
martong added a comment.

We had a separate discussion with @xazax.hun. Let me summarize the outcome. We 
agreed that we should try our best to provide signatures for all functions 
(this affects child patches, particularly the POSIX related D79433 
). Probably, we are not going to need this 
patch anymore, once we will have done that work.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79423



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


[PATCH] D78280: [Analyzer][StreamChecker] Track streams that were not found to be opened.

2020-05-14 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: clang/test/Analysis/stream.c:11-13
+void check_feread_noopen(FILE *fp) {
+  fread(0, 0, 0, fp);
+}

What do these tests test?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78280



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


[PATCH] D79433: [analyzer] StdLibraryFunctionsChecker: Add summaries for POSIX

2020-05-14 Thread Gabor Marton via Phabricator via cfe-commits
martong planned changes to this revision.
martong added a comment.

With @xazax.hun we agreed that we should try our best to provide signatures for 
all functions. This includes two major changes:

1. Add signatures to each summary here, possibly with `Irrelevant` types.
2. Add the ability to lookup types. This will result that we can change the 
majority `Irrelevant` types to concrete types.

Note, we still cannot get rid of `Irrelevant` types because of platform 
dependent typedefs and macros. E.g. `ssize_t` or `__CONST_SOCKADDR_ARG`. Check 
out glibc 2.27 implementation for `struct sockaddr *` below. The only solution 
for such cases is to use an `Irrelevant` type.

  #if defined __cplusplus || !__GNUC_PREREQ (2, 7) || !defined __USE_GNU
  # define __SOCKADDR_ARG   struct sockaddr *__restrict
  # define __CONST_SOCKADDR_ARG const struct sockaddr *
  #else
  /* Add more `struct sockaddr_AF' types here as necessary.
 These are all the ones I found on NetBSD and Linux.  */
  # define __SOCKADDR_ALLTYPES \
__SOCKADDR_ONETYPE (sockaddr) \
__SOCKADDR_ONETYPE (sockaddr_at) \
__SOCKADDR_ONETYPE (sockaddr_ax25) \
__SOCKADDR_ONETYPE (sockaddr_dl) \
__SOCKADDR_ONETYPE (sockaddr_eon) \
__SOCKADDR_ONETYPE (sockaddr_in) \
__SOCKADDR_ONETYPE (sockaddr_in6) \
__SOCKADDR_ONETYPE (sockaddr_inarp) \
__SOCKADDR_ONETYPE (sockaddr_ipx) \
__SOCKADDR_ONETYPE (sockaddr_iso) \
__SOCKADDR_ONETYPE (sockaddr_ns) \
__SOCKADDR_ONETYPE (sockaddr_un) \
__SOCKADDR_ONETYPE (sockaddr_x25)
  
  # define __SOCKADDR_ONETYPE(type) struct type *__restrict __##type##__;
  typedef union { __SOCKADDR_ALLTYPES
  } __SOCKADDR_ARG __attribute__ ((__transparent_union__));
  # undef __SOCKADDR_ONETYPE
  # define __SOCKADDR_ONETYPE(type) const struct type *__restrict __##type##__;
  typedef union { __SOCKADDR_ALLTYPES
  } __CONST_SOCKADDR_ARG __attribute__ ((__transparent_union__));
  # undef __SOCKADDR_ONETYPE
  #endif


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79433



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


[PATCH] D74813: Function block naming - add hash of parameter type to end of block name

2020-05-14 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington added a comment.

In D74813#2035051 , @alexbdv wrote:

> Could I please get a review on this ? Thanks :) !


I still think it makes more sense to directly encode the type instead of 
hashing it. I'm happy to make the demangler changes for whatever we land on, so 
feel free to ignore that part of it.


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

https://reviews.llvm.org/D74813



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


[PATCH] D78280: [Analyzer][StreamChecker] Track streams that were not found to be opened.

2020-05-14 Thread Balázs Kéri via Phabricator via cfe-commits
balazske marked an inline comment as done.
balazske added a comment.

Currently priority of this change is lower than D78374 
.
If a similar change is done a "escaped" stream state will be needed too.




Comment at: clang/test/Analysis/stream.c:11-13
+void check_feread_noopen(FILE *fp) {
+  fread(0, 0, 0, fp);
+}

NoQ wrote:
> What do these tests test?
There should be no warning about resource leak (file not closed). This may be 
not the best approach to show what the checker does. Some other detectable 
problem should be added to show that the functions are not ignored by the 
checker.
(I do not like that the buffer argument is 0 here, probably other checker 
should check this.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78280



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


[clang] 0c5db3e - Fix test from 5f1f4a5

2020-05-14 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2020-05-14T08:22:08-07:00
New Revision: 0c5db3e4aa197bab6e4d9f8c02ca0edf4fa9dce3

URL: 
https://github.com/llvm/llvm-project/commit/0c5db3e4aa197bab6e4d9f8c02ca0edf4fa9dce3
DIFF: 
https://github.com/llvm/llvm-project/commit/0c5db3e4aa197bab6e4d9f8c02ca0edf4fa9dce3.diff

LOG: Fix test from 5f1f4a5

My test needs a requires target clause to support inline assembly.  This
patch splits out the asm tests into a separate test so we don't skip the
rest of the conditions.

Added: 
clang/test/SemaCXX/ext-int-asm.cpp

Modified: 
clang/test/SemaCXX/ext-int.cpp

Removed: 




diff  --git a/clang/test/SemaCXX/ext-int-asm.cpp 
b/clang/test/SemaCXX/ext-int-asm.cpp
new file mode 100644
index ..c7434d29eff3
--- /dev/null
+++ b/clang/test/SemaCXX/ext-int-asm.cpp
@@ -0,0 +1,11 @@
+// REQUIRES: x86-registered-target
+// RUN: %clang_cc1 -fsyntax-only -verify %s -Wimplicit-int-conversion -triple 
x86_64-gnu-linux -fasm-blocks
+
+void NotAllowedInInlineAsm(_ExtInt(9) in, _ExtInt(9) out) {
+  __asm { mov eax, in} // expected-error{{invalid type '_ExtInt(9)' in asm 
input}}
+  __asm { mov out, eax} // expected-error{{invalid type '_ExtInt(9)' in asm 
output}}
+
+  asm("" : "=g" (in));// expected-error{{invalid type '_ExtInt(9)' in asm 
input}}
+  asm("" :: "r" (out));// expected-error{{invalid type '_ExtInt(9)' in asm 
output}}
+
+}

diff  --git a/clang/test/SemaCXX/ext-int.cpp b/clang/test/SemaCXX/ext-int.cpp
index a5e87eb878d3..14f11a6bb961 100644
--- a/clang/test/SemaCXX/ext-int.cpp
+++ b/clang/test/SemaCXX/ext-int.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s -Wimplicit-int-conversion -triple 
x86_64-gnu-linux -fasm-blocks
+// RUN: %clang_cc1 -fsyntax-only -verify %s -Wimplicit-int-conversion -triple 
x86_64-gnu-linux
 
 template
 struct HasExtInt {
@@ -275,13 +275,3 @@ void ImplicitCasts(_ExtInt(31) s31, _ExtInt(33) s33, int 
i) {
   // expected-warning@+1{{implicit conversion loses integer precision}}
   i = s33;
 }
-
-
-void NotAllowedInInlineAsm(_ExtInt(9) in, _ExtInt(9) out) {
-  __asm { mov eax, in} // expected-error{{invalid type '_ExtInt(9)' in asm 
input}}
-  __asm { mov out, eax} // expected-error{{invalid type '_ExtInt(9)' in asm 
output}}
-
-  asm("" : "=g" (in));// expected-error{{invalid type '_ExtInt(9)' in asm 
input}}
-  asm("" :: "r" (out));// expected-error{{invalid type '_ExtInt(9)' in asm 
output}}
-
-}



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


[PATCH] D79693: [test][ARM][CMSE] Use -ffreestanding for arm_cmse.h tests

2020-05-14 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added a comment.

Ping, @chill. It seems you checked these files in under D70817 
. The way they were written has issues as 
indicated by the patch description. Please take a look; thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79693



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


[PATCH] D79945: [Sema] Comparison of pointers to complete and incomplete types

2020-05-14 Thread Benson Chu via Phabricator via cfe-commits
pestctrl created this revision.
pestctrl added a reviewer: rsmith.
pestctrl added a project: clang.

Clang is missing one of the conditions for C99 6.5.9p2, where comparison 
between pointers must either both point to incomplete types or both point to 
complete types. This patch adds an extra check to the clause where two pointers 
are of compatible types.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D79945

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/compare.c


Index: clang/test/Sema/compare.c
===
--- clang/test/Sema/compare.c
+++ clang/test/Sema/compare.c
@@ -405,3 +405,12 @@
   if (x == y) x = y; // no warning
   if (y == x) y = x; // no warning
 }
+
+int incomplete[];
+int complete[5];
+
+void test13() {
+  if (&incomplete < &complete) { // expected-error {{ordered comparison of 
complete and incomplete pointers}}
+return;
+  }
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -11426,8 +11426,15 @@
 // C99 6.5.9p2 and C99 6.5.8p2
 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
RCanPointeeTy.getUnqualifiedType())) {
-  // Valid unless a relational comparison of function pointers
-  if (IsRelational && LCanPointeeTy->isFunctionType()) {
+  // Pointers both need to point to complete or incomplete types
+  if (LCanPointeeTy->isIncompleteType() !=
+  RCanPointeeTy->isIncompleteType()) {
+Diag(Loc,
+ diag::err_typecheck_comparison_of_complete_and_incomplete_types)
+<< LHSType << RHSType << LHS.get()->getSourceRange()
+<< RHS.get()->getSourceRange();
+  } else if (IsRelational && LCanPointeeTy->isFunctionType()) {
+// Valid unless a relational comparison of function pointers
 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
   << LHSType << RHSType << LHS.get()->getSourceRange()
   << RHS.get()->getSourceRange();
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6461,6 +6461,8 @@
   "ordered comparison between pointer and zero (%0 and %1)">;
 def err_typecheck_three_way_comparison_of_pointer_and_zero : Error<
   "three-way comparison between pointer and zero">;
+def err_typecheck_comparison_of_complete_and_incomplete_types : Error<
+  "ordered comparison of complete and incomplete pointers (%0 and %1)">;
 def ext_typecheck_ordered_comparison_of_function_pointers : ExtWarn<
   "ordered comparison of function pointers (%0 and %1)">,
   InGroup>;


Index: clang/test/Sema/compare.c
===
--- clang/test/Sema/compare.c
+++ clang/test/Sema/compare.c
@@ -405,3 +405,12 @@
   if (x == y) x = y; // no warning
   if (y == x) y = x; // no warning
 }
+
+int incomplete[];
+int complete[5];
+
+void test13() {
+  if (&incomplete < &complete) { // expected-error {{ordered comparison of complete and incomplete pointers}}
+return;
+  }
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -11426,8 +11426,15 @@
 // C99 6.5.9p2 and C99 6.5.8p2
 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
RCanPointeeTy.getUnqualifiedType())) {
-  // Valid unless a relational comparison of function pointers
-  if (IsRelational && LCanPointeeTy->isFunctionType()) {
+  // Pointers both need to point to complete or incomplete types
+  if (LCanPointeeTy->isIncompleteType() !=
+  RCanPointeeTy->isIncompleteType()) {
+Diag(Loc,
+ diag::err_typecheck_comparison_of_complete_and_incomplete_types)
+<< LHSType << RHSType << LHS.get()->getSourceRange()
+<< RHS.get()->getSourceRange();
+  } else if (IsRelational && LCanPointeeTy->isFunctionType()) {
+// Valid unless a relational comparison of function pointers
 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
   << LHSType << RHSType << LHS.get()->getSourceRange()
   << RHS.get()->getSourceRange();
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6461,6 +6461,8 @@
   "ordered comparison between pointer and zero (%0 and %1)">;
 def err_typecheck_three_way_comparison_of_pointer_and_zero : Error<
   "three-way comparison betwe

[PATCH] D76077: [ARM] Add __bf16 as new Bfloat16 C Type

2020-05-14 Thread David Majnemer via Phabricator via cfe-commits
majnemer added inline comments.



Comment at: clang/include/clang-c/Index.h:3254
   CXType_FirstBuiltin = CXType_Void,
   CXType_LastBuiltin = CXType_ULongAccum,
 

Should this be:
  CXType_LastBuiltin = CXType_BFloat16,




Comment at: clang/lib/AST/ItaniumMangle.cpp:3186
+case BuiltinType::Half:  EltName = "float16_t"; break;
+case BuiltinType::BFloat16:  EltName = "bfloat16x1_t"; break;
 default:

Why is this x1?



Comment at: clang/lib/Sema/SemaOverload.cpp:1873-1874
 // We of course allow this conversion if long double is really double.
+if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
+  return false;
 if (&S.Context.getFloatTypeSemantics(FromType) !=

This probably needs an explanation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76077



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


[PATCH] D79675: [OpenMP][OMPBuilder] Adding Privatization Requirements to OMPIRBuilder

2020-05-14 Thread Fady Ghanim via Phabricator via cfe-commits
fghanim marked 7 inline comments as done.
fghanim added inline comments.



Comment at: llvm/include/llvm/Frontend/OpenMP/OMPConstants.h:101
+extern Type *IntPtrTy;
+extern Type *SizeTy;
+

jdoerfert wrote:
> jdoerfert wrote:
> > I can totally see why we need `int` and `size_t` but I'm not sure about the 
> > others.
> > `void` is universally translated to `i8*` Adding a pointer to a type should 
> > be done in OMPKinds.def, something like:
> > ```
> > #define __OMP_PTR_TYPE(NAME, BASE) OMP_TYPE(NAME, Base->getPointerTo());
> > __OMP_PTR_TYPE(VoidPtr, Int8)
> > __OMP_PTR_TYPE(VoidPtrPtr, VoidPtr)
> > ```
> My proposed scheme for the pointers was integrated in D79739 and will be 
> commited shortly.
Kept a couple a Ineed in OMPConstants. will add them in OMPKinds.def after the 
other patch lands.



Comment at: llvm/include/llvm/Frontend/OpenMP/OMPKinds.def:234
 __OMP_RTL(__kmpc_critical, false, Void, IdentPtr, Int32, KmpCriticalNamePtrTy)
-__OMP_RTL(__kmpc_critical_with_hint, false, Void, IdentPtr, Int32, 
KmpCriticalNamePtrTy, Int32)
+__OMP_RTL(__kmpc_critical_with_hint, false, Void, IdentPtr, Int32, 
KmpCriticalNamePtrTy, IntPtrTy)
 __OMP_RTL(__kmpc_end_critical, false, Void, IdentPtr, Int32, 
KmpCriticalNamePtrTy)

jdoerfert wrote:
> fghanim wrote:
> > jdoerfert wrote:
> > > I think this was correct before:
> > > ```
> > >   KMP_EXPORT void __kmpc_critical_with_hint(ident_t *, kmp_int32 
> > > global_tid, kmp_critical_name *, uint32_t hint);
> > > ```
> > Nop, it's supposed to be whatever `IntPtrTy` is in the frontend (i.e. 32 
> > for 32bit, 64 for 64bit).
> > 
> > `IntPtrTy` is actually a union with `sizety` in `CodeGenModule`
> I'm confused. I copied the declaration above from the runtime. It doesn't 
> contain an `IntPtrTy` or similar. I agree that `IntPtrTy` is machine 
> dependent and we need your initializers. What I tried to say is that at least 
> one declaration in the runtime has `__kmpc_critical_with_hint` with an int32 
> as last argument. That said, the runtime is not shy of incompatible 
> declarations for functions.
I cannot speak for what's in the runtime. However, in clang, this currently is 
defined to use `IntPtrTy`. If you go check, I have a todo in the current 
implementation for critical to come back and fix it.



Comment at: llvm/include/llvm/Frontend/OpenMP/OMPKinds.def:240
+__OMP_RTL(__kmpc_threadprivate_cached, false, VoidPtr, IdentPtr, Int32, 
VoidPtr, SizeTy, Void3Ptr)
+__OMP_RTL(__kmpc_threadprivate_register, false, Void, IdentPtr, VoidPtr, 
KmpcCtorTy, KmpcCopyCtorTy, KmpcDtorTy)
+

jdoerfert wrote:
> Can you add attributes (below) for these and call them in 
> `llvm/test/Transforms/OpenMP/add_attributes.ll` [if not already present]. 
> These changes and the additional types should go in a separate patch.
Added in D79739



Comment at: llvm/lib/Frontend/OpenMP/OMPConstants.cpp:122
+  }
+}
+

jdoerfert wrote:
> fghanim wrote:
> > jdoerfert wrote:
> > > (I doubt we need the `initVoidPtr` function but if we do, the condition 
> > > looks wrong)
> > Forgot to refractor when I changed names.
> > 
> > Regarding `void*` , I am not sure how it is defined in fortran. That's why 
> > I made it possible to initialize it separately.
> I see. Let's cross that bridge once we get to it.
Modified it a bit and removed usage from initialization. If fortran people 
don't end using it, then we can remove it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79675



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


[PATCH] D79675: [OpenMP][OMPBuilder] Adding Privatization Requirements to OMPIRBuilder

2020-05-14 Thread Fady Ghanim via Phabricator via cfe-commits
fghanim updated this revision to Diff 264006.
fghanim marked an inline comment as done.
fghanim added a comment.

- removed many Definitions from OMPKinds.def due to being added in D79739 

- made changes based on reviewer comments
- added unit test for `CreateCopyinClauseBlocks()`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79675

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPConstants.h
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
  llvm/lib/Frontend/OpenMP/OMPConstants.cpp
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp

Index: llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
===
--- llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
+++ llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
@@ -779,4 +779,41 @@
   EXPECT_EQ(CriticalEndCI->getArgOperand(2)->getType(), CriticalNamePtrTy);
 }
 
+TEST_F(OpenMPIRBuilderTest, CopyinBlocks) {
+  using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
+  OpenMPIRBuilder OMPBuilder(*M);
+  OMPBuilder.initialize();
+  F->setName("func");
+  IRBuilder<> Builder(BB);
+
+  OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
+
+  AllocaInst *PrivAI = Builder.CreateAlloca(F->arg_begin()->getType());
+  IntegerType* Int32 = Type::getInt32Ty(M->getContext());
+  AllocaInst* MasterAddress = Builder.CreateAlloca(Int32->getPointerTo());
+	AllocaInst* PrivAddress = Builder.CreateAlloca(Int32->getPointerTo());
+
+  BasicBlock *EntryBB = BB;
+
+  OMPBuilder.CreateCopyinClauseBlocks(Builder.saveIP(), MasterAddress, PrivAddress, Int32, /*BranchtoEnd*/true);
+
+  BranchInst* EntryBr = dyn_cast_or_null(EntryBB->getTerminator());
+
+  EXPECT_NE(EntryBr, nullptr);
+  EXPECT_TRUE(EntryBr->isConditional());
+
+  BasicBlock* NotMasterBB = EntryBr->getSuccessor(0);
+  BasicBlock* CopyinEnd = EntryBr->getSuccessor(1);
+  CmpInst* CMP = dyn_cast_or_null(EntryBr->getCondition());
+
+  EXPECT_NE(CMP, nullptr);
+  EXPECT_NE(NotMasterBB, nullptr);
+  EXPECT_NE(CopyinEnd, nullptr);
+
+  BranchInst* NotMasterBr = dyn_cast_or_null(NotMasterBB->getTerminator());
+  EXPECT_NE(NotMasterBr, nullptr);
+  EXPECT_FALSE(NotMasterBr->isConditional());
+  EXPECT_EQ(CopyinEnd,NotMasterBr->getSuccessor(0));
+}
+
 } // namespace
Index: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -93,6 +93,18 @@
 
 void OpenMPIRBuilder::initialize() { initializeTypes(M); }
 
+void OpenMPIRBuilder::setIntPtrTy(IntegerType *IntPtrTy) {
+  initializeIntPtrTy(IntPtrTy);
+}
+
+void OpenMPIRBuilder::setSizeTy(IntegerType *SizeTy) {
+  initializeSizeTy(SizeTy);
+}
+
+void OpenMPIRBuilder::setVoidPtrTy(PointerType *VoidPtrTy) {
+  initializeVoidPtrTy(VoidPtrTy);
+}
+
 void OpenMPIRBuilder::finalize() {
   for (OutlineInfo &OI : OutlineInfos) {
 assert(!OI.Blocks.empty() &&
@@ -576,9 +588,6 @@
  "Unexpected finalization stack state!");
 
   Instruction *PRegPreFiniTI = PRegPreFiniBB->getTerminator();
-  assert(PRegPreFiniTI->getNumSuccessors() == 1 &&
- PRegPreFiniTI->getSuccessor(0) == PRegExitBB &&
- "Unexpected CFG structure!");
 
   InsertPointTy PreFiniIP(PRegPreFiniBB, PRegPreFiniTI->getIterator());
   FiniCB(PreFiniIP);
@@ -912,6 +921,106 @@
   ExitCall->getIterator());
 }
 
+OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::CreateCopyinClauseBlocks(
+InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr,
+llvm::IntegerType *IntPtrTy, bool BranchtoEnd) {
+  if (!IP.isSet())
+return IP;
+
+  IRBuilder<>::InsertPointGuard IPG(Builder);
+
+  // creates the following CFG structure
+  //	   OMP_Entry : (MasterAddr != PrivateAddr)?
+  //   F T
+  //   |  \
+  //   | copin.not.master
+  //   |  /
+  //   v /
+  //   copyin.not.master.end
+  //		 |
+  // v
+  //   OMP.Entry.Next
+
+  BasicBlock *OMP_Entry = IP.getBlock();
+  Function *CurFn = OMP_Entry->getParent();
+  BasicBlock *CopyBegin =
+  BasicBlock::Create(M.getContext(), "copyin.not.master", CurFn);
+  BasicBlock *CopyEnd = nullptr;
+
+  // If entry block is terminated, split to preserve the branch to following
+  // basic block (i.e. OMP.Entry.Next), otherwise, leave everything as is.
+  if (isa_and_nonnull(OMP_Entry->getTerminator())) {
+CopyEnd = OMP_Entry->splitBasicBlock(OMP_Entry->getTerminator(),
+ "copyin.not.master.end");
+OMP_Entry->getTerminator()->eraseFromParent();
+  } else {
+CopyEnd =
+BasicBlock::Create(M.getContext(), "copyin.not.master.end", CurFn);
+  }
+
+  Builder.SetInsertPoint(OMP_Entry);

[PATCH] D76077: [ARM] Add __bf16 as new Bfloat16 C Type

2020-05-14 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:518
+Clang supports three half-precision (16-bit) floating point types: ``__fp16``,
+``_Float16`` and ``__bf16``.  These types are supported in all language modes.
 

Not my field of expertise, and sorry if I've missed this somewhere, but was 
wondering if this (i.e. all language modes) means we need C++ name mangling 
support for bfloat? In the AArch64 backend I saw this:

  getBFloat16Mangling() const override { return "u6__bf16"; }

But that's something else I guess, and I was guessing a 2 letter mangling needs 
to be added here?

https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-builtin


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76077



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


[PATCH] D74166: [AIX][Frontend] Static init implementation for AIX considering no priority

2020-05-14 Thread Xiangling Liao via Phabricator via cfe-commits
Xiangling_L updated this revision to Diff 264009.
Xiangling_L added a comment.

Clean `clang-tidy` warnings and `clang-format` errors


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D74166

Files:
  clang/include/clang/AST/Mangle.h
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/CodeGen/CGCXXABI.h
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/CodeGen/ItaniumCXXABI.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/aix-constructor-attribute.cpp
  clang/test/CodeGen/aix-destructor-attribute.cpp
  clang/test/CodeGen/aix-init-priority-attribute.cpp
  clang/test/CodeGen/static-init.cpp

Index: clang/test/CodeGen/static-init.cpp
===
--- clang/test/CodeGen/static-init.cpp
+++ clang/test/CodeGen/static-init.cpp
@@ -1,12 +1,55 @@
-// RUN: not %clang_cc1 -triple powerpc-ibm-aix-xcoff -S -emit-llvm -x c++ %s \
-// RUN: -o /dev/null 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc-ibm-aix-xcoff -S -emit-llvm -x c++ < %s \
+// RUN: | FileCheck %s
 
-// RUN: not %clang_cc1 -triple powerpc64-ibm-aix-xcoff -S -emit-llvm -x c++ %s \
-// RUN: -o /dev/null 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64-ibm-aix-xcoff -S -emit-llvm -x c++ < %s \
+// RUN: | FileCheck %s
 
 struct test {
   test();
   ~test();
 } t;
 
-// CHECK: error in backend: Static initialization has not been implemented on XL ABI yet.
+// CHECK: @llvm.global_ctors = appending global [1 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 65535, void ()* @__sinit8000_clang_b2e4830f1c9d2d063e5ea946868f3bfd, i8* null }]
+// CHECK: @llvm.global_dtors = appending global [1 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 65535, void ()* @__sterm8000_clang_b2e4830f1c9d2d063e5ea946868f3bfd, i8* null }]
+// CHECK: define dso_local void @__cxx_global_var_init() #0 {
+// CHECK: entry:
+// CHECK:   call void @_ZN4testC1Ev(%struct.test* @t)
+// CHECK:   %0 = call i32 @atexit(void ()* @__dtor_t)
+// CHECK:   ret void
+// CHECK: }
+
+// CHECK: define dso_local void @__dtor_t() #0 {
+// CHECK: entry:
+// CHECK:   call void @_ZN4testD1Ev(%struct.test* @t)
+// CHECK:   ret void
+// CHECK: }
+
+// CHECK: declare i32 @atexit(void ()*)
+
+// CHECK: define dso_local void @__cxx_global_var_destruct_t() #0 {
+// CHECK: entry:
+// CHECK:   %0 = call i32 @unatexit(void ()* @__dtor_t)
+// CHECK:   %guard.hasSrterm = icmp eq i32 %0, 0
+// CHECK:   br i1 %guard.hasSrterm, label %destruct.check, label %destruct.end
+
+// CHECK: destruct.check:
+// CHECK:   call void @__dtor_t()
+// CHECK:   br label %destruct.end
+
+// CHECK: destruct.end:
+// CHECK:   ret void
+// CHECK: }
+
+// CHECK: declare i32 @unatexit(void ()*)
+
+// CHECK: define dso_local void @__sinit8000_clang_b2e4830f1c9d2d063e5ea946868f3bfd() #0 {
+// CHECK: entry:
+// CHECK:   call void @__cxx_global_var_init()
+// CHECK:   ret void
+// CHECK: }
+
+// CHECK: define dso_local void @__sterm8000_clang_b2e4830f1c9d2d063e5ea946868f3bfd() #0 {
+// CHECK: entry:
+// CHECK:   call void @__cxx_global_var_destruct_t()
+// CHECK:   ret void
+// CHECK: }
Index: clang/test/CodeGen/aix-init-priority-attribute.cpp
===
--- /dev/null
+++ clang/test/CodeGen/aix-init-priority-attribute.cpp
@@ -0,0 +1,16 @@
+// RUN: not %clang_cc1 -triple powerpc-ibm-aix-xcoff -x c++ -emit-llvm < %s \
+// RUN: 2>&1 | FileCheck %s
+// RUN: not %clang_cc1 -triple powerpc64-ibm-aix-xcoff -x c++ -emit-llvm < %s \
+// RUN: 2>&1 | FileCheck %s
+
+class test {
+  int a;
+public:
+  test(int c) {a = c;}
+  ~test() {a = 0;}
+};
+
+__attribute__((init_priority(2000)))
+test t(1);
+
+// CHECK: fatal error: error in backend: 'init_priority' attribute unsupported on AIX yet
Index: clang/test/CodeGen/aix-destructor-attribute.cpp
===
--- /dev/null
+++ clang/test/CodeGen/aix-destructor-attribute.cpp
@@ -0,0 +1,17 @@
+// RUN: not %clang_cc1 -triple powerpc-ibm-aix-xcoff -x c++ -emit-llvm < %s \
+// RUN: 2>&1 | FileCheck %s
+// RUN: not %clang_cc1 -triple powerpc64-ibm-aix-xcoff -x c++ -emit-llvm < %s \
+// RUN: 2>&1 | FileCheck %s
+
+int bar() __attribute__((destructor(180)));
+
+class test {
+  int a;
+public:
+  test(int c) {a = c;}
+  ~test() {a = 0;}
+};
+
+test t(1);
+
+// CHECK: fatal error: error in backend: 'destructor' attribute unsupported on AIX yet
Index: clang/test/CodeGen/aix-constructor-attribute.cpp
===
--- /dev/null
+++ clang/test/CodeGen/aix-constructor-attribute.cpp
@@ -0,0 +1,17 @@
+// RUN: not %clang_cc1 -triple powerpc-ibm-aix-xcoff -x c++ -emit-llvm < %s \
+// RUN: 2>&1 | FileCheck %s
+// RUN: not %clang_cc1 -triple powerpc64-ibm-aix-xcoff -x c++ -emit-llvm < %s \
+// RUN: 2>&1 | FileCheck %s
+
+

[PATCH] D79704: [Analyzer] [NFC] Parameter Regions

2020-05-14 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

In D79704#2034571 , @NoQ wrote:

> In D79704#2032947 , @Szelethus wrote:
>
> > In D79704#2032271 , @NoQ wrote:
> >
> > > Blanket reply! `ParamRegion` is not a `DeclRegion` because it does not 
> > > necessarily have a corresponding `Decl`. For instance, when calling a 
> > > function through an unknown function pointer, you don't have the 
> > > declaration of a function, let alone its parameters.
> >
> >
> > Well hold on for a second then -- how is this, if it is, different for 
> > member pointers? Aren't they represented with a `VarRegion`?
>
>
> They aren't even `Loc`!
>
> We currently don't have a representation for an unknown pointer-to-member. A 
> known pointer-to-member is represented by a `FieldDecl` (not sure about 
> static members) but it's still a `NonLoc` and as such isn't a region at all. 
> Because, well, you can't dereference a pointer-to-member; you can only apply 
> it to a base pointer like an offset. The mental model is "an offset". 
> Therefore it's `NonLoc`.
>
> Pointers to member functions are a different thing; they're function pointers 
> so they're kinda regions.
>
> >> But for parameters of C++ object type you still need your `ParamRegion` 
> >> because arguments are constructed into it.
> > 
> > Could you give a specific code example?
>
>
>
>   struct S {
> S() {
>   this; // What region does 'this' point to...
> }
>   };
>  
>   void foo(void (*bar)(S)) {
> bar(S()); // ...in this invocation?
>   }
>


I remember this coming up so many times, and I'm an inch away from getting it 
but I'm not there just yet ^-^ Sorry if you have to repeat yourself too many 
times.

The example you have shown sounds like a case we could (should?) abstract away. 
If we model in accordance to the AST as closely as possible, `ParamRegion` 
should totally be a `VarRegion`. If something tricky like this came up, the 
`getDecl` function should just return with a nullptr, shouldn't it? The code 
changes make me feel like we're doing a lot of chore (and make it super easy to 
forget checking for parameters explicitly). The gain, which is I guess 
correctness, seems negligible, and I'm not sure this is actually correct, as I 
mentioned in D79704#inline-730731 
. I don't see why the most 
defining feature of a `DeclRegion` is supposed to be an always existing `Decl`, 
rather than a mirror of the AST.


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

https://reviews.llvm.org/D79704



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


[PATCH] D79693: [test][ARM][CMSE] Use -ffreestanding for arm_cmse.h tests

2020-05-14 Thread Momchil Velikov via Phabricator via cfe-commits
chill added a comment.

I'm sorry, I don't understand the issue. Certainly it's the compiler (driver) 
responsibility to setup include paths according to the selected target.
How do you trigger a problem?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79693



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


[PATCH] D70351: [clang][WIP][clang-scan-deps] Add an experimental C API.

2020-05-14 Thread Kousik Kumar via Phabricator via cfe-commits
kousikk added a comment.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70351



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


[PATCH] D79715: [clang-format] Update GoogleStyle for C# code to match Google's internal C# style guide

2020-05-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

Assuming you either work for google and understand their style or are qualified 
to say this is their style then this LGTM

What I couldn't see from the link was where the google C# style guide was?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79715



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


[PATCH] D79465: [clang-format] Fix line lengths w/ comments in align

2020-05-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added inline comments.



Comment at: clang/lib/Format/WhitespaceManager.cpp:417
+LineLengthAfter += Changes[j].TokenLength;
+}
 unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter;

could you help us here with a comment, I don't understand what they mean by 
Change.IsInsideToken?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79465



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


[PATCH] D34252: Add arbitrary file/path support to clang-format style file selection

2020-05-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

I think we can abandon this revision now we support --style=file:


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

https://reviews.llvm.org/D34252



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


[PATCH] D79000: [clang-format] C# property formatting can be controlled by config options

2020-05-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

I'm ok with your suggestion if you want to land this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79000



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


[clang] 235fb7d - AMDGPU/OpenCL: Accept -nostdlib in place of -nogpulib

2020-05-14 Thread Matt Arsenault via cfe-commits

Author: Matt Arsenault
Date: 2020-05-14T12:33:31-04:00
New Revision: 235fb7dc24b1cf7034dfc76bb853ffb4ac5dec5d

URL: 
https://github.com/llvm/llvm-project/commit/235fb7dc24b1cf7034dfc76bb853ffb4ac5dec5d
DIFF: 
https://github.com/llvm/llvm-project/commit/235fb7dc24b1cf7034dfc76bb853ffb4ac5dec5d.diff

LOG: AMDGPU/OpenCL: Accept -nostdlib in place of -nogpulib

-nogpulib makes sense when there is a host (where -nostdlib would
 apply) and offload target. Accept nostdlib when there is no offload
 target as an alias.

Added: 
clang/test/Driver/rocm-detect.hip

Modified: 
clang/lib/Driver/ToolChains/AMDGPU.cpp
clang/test/Driver/rocm-not-found.cl

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index fd81fec5f452..193ccad98f52 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -361,6 +361,12 @@ void ROCMToolChain::addClangTargetOptions(
   AMDGPUToolChain::addClangTargetOptions(DriverArgs, CC1Args,
  DeviceOffloadingKind);
 
+  // For the OpenCL case where there is no offload target, accept -nostdlib to
+  // disable bitcode linking.
+  if (DeviceOffloadingKind == Action::OFK_None &&
+  DriverArgs.hasArg(options::OPT_nostdlib))
+return;
+
   if (DriverArgs.hasArg(options::OPT_nogpulib))
 return;
 

diff  --git a/clang/test/Driver/rocm-detect.hip 
b/clang/test/Driver/rocm-detect.hip
new file mode 100644
index ..82ed7138098a
--- /dev/null
+++ b/clang/test/Driver/rocm-detect.hip
@@ -0,0 +1,27 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// Make sure the appropriate device specific library is available.
+
+// We don't include every target in the test directory, so just pick a valid
+// target not included in the test.
+
+// RUN: %clang -### -v -target x86_64-linux-gnu --cuda-gpu-arch=gfx902 \
+// RUN:   --rocm-path=%S/Inputs/rocm-device-libs %s 2>&1 \
+// RUN:   | FileCheck -check-prefixes=COMMON,GFX902-DEFAULTLIBS %s
+
+// Should not interpret -nostdlib as disabling offload libraries.
+// RUN: %clang -### -v -target x86_64-linux-gnu --cuda-gpu-arch=gfx902 
-nostdlib \
+// RUN:   --rocm-path=%S/Inputs/rocm-device-libs %s 2>&1 \
+// RUN:   | FileCheck -check-prefixes=COMMON,GFX902-DEFAULTLIBS %s
+
+
+// RUN: %clang -### -v -target x86_64-linux-gnu --cuda-gpu-arch=gfx902 
-nogpulib \
+// RUN:   --rocm-path=%S/Inputs/rocm-device-libs %s 2>&1 \
+// RUN:   | FileCheck -check-prefixes=COMMON,GFX902,NODEFAULTLIBS %s
+
+
+// GFX902-DEFAULTLIBS: error: cannot find device library for gfx902. Provide 
path to 
diff erent ROCm installation via --rocm-path, or pass -nogpulib to build 
without linking default libraries.
+
+// NODEFAULTLIBS-NOT: error: cannot find

diff  --git a/clang/test/Driver/rocm-not-found.cl 
b/clang/test/Driver/rocm-not-found.cl
index 49b6c7efcf99..8ecc4b0ef105 100644
--- a/clang/test/Driver/rocm-not-found.cl
+++ b/clang/test/Driver/rocm-not-found.cl
@@ -7,5 +7,7 @@
 // RUN: %clang -### --rocm-path=%s/no-rocm-there -target amdgcn--amdhsa %s 
2>&1 | FileCheck %s --check-prefix ERR
 // ERR: cannot find ROCm installation. Provide its path via --rocm-path, or 
pass -nogpulib.
 
+// Accept nogpulib or nostdlib for OpenCL.
 // RUN: %clang -### -nogpulib --rocm-path=%s/no-rocm-there %s 2>&1 | FileCheck 
%s --check-prefix OK
+// RUN: %clang -### -nostdlib --rocm-path=%s/no-rocm-there %s 2>&1 | FileCheck 
%s --check-prefix OK
 // OK-NOT: cannot find ROCm installation.



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


[PATCH] D79676: [Clang][OpenMP][OMPBuilder] Moving OMP allocation and cache creation code to OMPBuilderCBHelpers

2020-05-14 Thread Fady Ghanim via Phabricator via cfe-commits
fghanim marked 4 inline comments as done.
fghanim added inline comments.



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:878
+  [this, VDInit, OriginalAddr, VD, ThisFirstprivateIsLastprivate,
+   OrigVD, &Lastprivates, IRef, &OMPBuilder]() {
 // Emit private VarDecl with copy init.

jdoerfert wrote:
> Is this needed?
All these are changes that I forgot to remove after I created a special version 
for `EmitOMPFirstprivateClause`  in D79677 for the OMPBuilder



Comment at: clang/lib/CodeGen/CodeGenFunction.h:1581
+++I;
+
+  return &*I;

jdoerfert wrote:
> What is wrong with `BB->getFirstNonPHIOrDbgOrLifetime()`? If it is to avoid 
> too many test changes, please add a TODO. I think from a functional 
> perspective there is no need to advance it after the first set of allocas 
> that may be separated from the phis by non-allocas?
Nothing wrong with it. The first while loop, I just came across a case that I 
don't remember at the moment that had an instruction that wasn't an alloca, and 
I wanted to skip over that.
the second while, is to get to the first non-alloca instruction. The purpose is 
to be able to insert new allocas, after already generated allocas.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79676



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


[PATCH] D79676: [Clang][OpenMP][OMPBuilder] Moving OMP allocation and cache creation code to OMPBuilderCBHelpers

2020-05-14 Thread Fady Ghanim via Phabricator via cfe-commits
fghanim updated this revision to Diff 264012.
fghanim marked an inline comment as done.
fghanim added a comment.

updating in response to review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79676

Files:
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/CodeGen/CodeGenFunction.h

Index: clang/lib/CodeGen/CodeGenFunction.h
===
--- clang/lib/CodeGen/CodeGenFunction.h
+++ clang/lib/CodeGen/CodeGenFunction.h
@@ -26,6 +26,7 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprOpenMP.h"
+#include "clang/AST/StmtOpenMP.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/ABI.h"
 #include "clang/Basic/CapturedStmt.h"
@@ -77,6 +78,7 @@
 class ObjCAtSynchronizedStmt;
 class ObjCAutoreleasePoolStmt;
 class ReturnsNonNullAttr;
+class OMPExecutableDirective;
 
 namespace analyze_os_log {
 class OSLogBufferLayout;
@@ -256,114 +258,6 @@
 unsigned Index;
   };
 
-  // Helper class for the OpenMP IR Builder. Allows reusability of code used for
-  // region body, and finalization codegen callbacks. This will class will also
-  // contain privatization functions used by the privatization call backs
-  struct OMPBuilderCBHelpers {
-
-using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
-
-/// Emit the Finalization for an OMP region
-/// \param CGF	The Codegen function this belongs to
-/// \param IP	Insertion point for generating the finalization code.
-static void FinalizeOMPRegion(CodeGenFunction &CGF, InsertPointTy IP) {
-  CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
-  assert(IP.getBlock()->end() != IP.getPoint() &&
- "OpenMP IR Builder should cause terminated block!");
-
-  llvm::BasicBlock *IPBB = IP.getBlock();
-  llvm::BasicBlock *DestBB = IPBB->getUniqueSuccessor();
-  assert(DestBB && "Finalization block should have one successor!");
-
-  // erase and replace with cleanup branch.
-  IPBB->getTerminator()->eraseFromParent();
-  CGF.Builder.SetInsertPoint(IPBB);
-  CodeGenFunction::JumpDest Dest = CGF.getJumpDestInCurrentScope(DestBB);
-  CGF.EmitBranchThroughCleanup(Dest);
-}
-
-/// Emit the body of an OMP region
-/// \param CGF	The Codegen function this belongs to
-/// \param RegionBodyStmt	The body statement for the OpenMP region being
-/// 			 generated
-/// \param CodeGenIP	Insertion point for generating the body code.
-/// \param FiniBB	The finalization basic block
-static void EmitOMPRegionBody(CodeGenFunction &CGF,
-  const Stmt *RegionBodyStmt,
-  InsertPointTy CodeGenIP,
-  llvm::BasicBlock &FiniBB) {
-  llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock();
-  if (llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator())
-CodeGenIPBBTI->eraseFromParent();
-
-  CGF.Builder.SetInsertPoint(CodeGenIPBB);
-
-  CGF.EmitStmt(RegionBodyStmt);
-
-  if (CGF.Builder.saveIP().isSet())
-CGF.Builder.CreateBr(&FiniBB);
-}
-
-/// RAII for preserving necessary info during Outlined region body codegen.
-class OutlinedRegionBodyRAII {
-
-  llvm::AssertingVH OldAllocaIP;
-  CodeGenFunction::JumpDest OldReturnBlock;
-  CodeGenFunction &CGF;
-
-public:
-  OutlinedRegionBodyRAII(CodeGenFunction &cgf, InsertPointTy &AllocaIP,
- llvm::BasicBlock &RetBB)
-  : CGF(cgf) {
-assert(AllocaIP.isSet() &&
-   "Must specify Insertion point for allocas of outlined function");
-OldAllocaIP = CGF.AllocaInsertPt;
-CGF.AllocaInsertPt = &*AllocaIP.getPoint();
-
-OldReturnBlock = CGF.ReturnBlock;
-CGF.ReturnBlock = CGF.getJumpDestInCurrentScope(&RetBB);
-  }
-
-  ~OutlinedRegionBodyRAII() {
-CGF.AllocaInsertPt = OldAllocaIP;
-CGF.ReturnBlock = OldReturnBlock;
-  }
-};
-
-/// RAII for preserving necessary info during inlined region body codegen.
-class InlinedRegionBodyRAII {
-
-  llvm::AssertingVH OldAllocaIP;
-  CodeGenFunction &CGF;
-
-public:
-  InlinedRegionBodyRAII(CodeGenFunction &cgf, InsertPointTy &AllocaIP,
-llvm::BasicBlock &FiniBB)
-  : CGF(cgf) {
-// Alloca insertion block should be in the entry block of the containing
-// function so it expects an empty AllocaIP in which case will reuse the
-// old alloca insertion point, or a new AllocaIP in the same block as
-// the old one
-assert((!AllocaIP.isSet() ||
-CGF.AllocaInsertPt->getParent() == AllocaIP.getBlock()) &&
-   "Insertion point should be in the entry block of containing "
-   "funct

[PATCH] D79948: [OPENMP50]Codegen for inscan reductions in worksharing directives.

2020-05-14 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev created this revision.
ABataev added a reviewer: jdoerfert.
Herald added subscribers: arphaman, guansong, yaxunl.
Herald added a project: clang.

Implemented codegen for reduction clauses with inscan modifiers in
worksharing constructs.

Emits the code for the directive with inscan reductions.
The code is the following:

  size num_iters = ;
   buffer[num_iters];
  for (i: 0..) {
;
buffer[i] = red;
  }
  for (int k = 0; k != ceil(log2(num_iters)); ++k)
  for (size cnt = last_iter; cnt >= pow(2, k); --k)
buffer[i] op= buffer[i-pow(2,k)];
  for (0..) {
red = InclusiveScan ? buffer[i] : buffer[i-1];
;
  }


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D79948

Files:
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/OpenMP/for_scan_codegen.cpp
  clang/test/OpenMP/scan_messages.cpp
  clang/tools/libclang/CIndex.cpp

Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2376,6 +2376,17 @@
   for (auto *E : C->reduction_ops()) {
 Visitor->AddStmt(E);
   }
+  if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
+for (auto *E : C->copy_ops()) {
+  Visitor->AddStmt(E);
+}
+for (auto *E : C->copy_array_temps()) {
+  Visitor->AddStmt(E);
+}
+for (auto *E : C->copy_array_elems()) {
+  Visitor->AddStmt(E);
+}
+  }
 }
 void OMPClauseEnqueue::VisitOMPTaskReductionClause(
 const OMPTaskReductionClause *C) {
Index: clang/test/OpenMP/scan_messages.cpp
===
--- clang/test/OpenMP/scan_messages.cpp
+++ clang/test/OpenMP/scan_messages.cpp
@@ -19,32 +19,32 @@
 #pragma omp for simd reduction(inscan, +: argc)
   for (int i = 0; i < 10; ++i)
 if (argc)
-#pragma omp scan inclusive(argc) // expected-error {{'#pragma omp scan' cannot be an immediate substatement}}
+#pragma omp scan inclusive(argc) // expected-error {{'#pragma omp scan' cannot be an immediate substatement}} expected-error {{orphaned 'omp scan' directives are prohibited; perhaps you forget to enclose the directive into a for, simd, for simd, parallel for, or parallel for simd region?}}
 if (argc) {
 #pragma omp scan inclusive(argc) // expected-error {{orphaned 'omp scan' directives are prohibited; perhaps you forget to enclose the directive into a for, simd, for simd, parallel for, or parallel for simd region?}}
 }
 #pragma omp simd reduction(inscan, +: argc)
   for (int i = 0; i < 10; ++i)
   while (argc)
-#pragma omp scan inclusive(argc) // expected-error {{'#pragma omp scan' cannot be an immediate substatement}}
+#pragma omp scan inclusive(argc) // expected-error {{'#pragma omp scan' cannot be an immediate substatement}} expected-error {{orphaned 'omp scan' directives are prohibited; perhaps you forget to enclose the directive into a for, simd, for simd, parallel for, or parallel for simd region?}}
 while (argc) {
 #pragma omp scan inclusive(argc) // expected-error {{orphaned 'omp scan' directives are prohibited; perhaps you forget to enclose the directive into a for, simd, for simd, parallel for, or parallel for simd region?}}
 }
 #pragma omp simd reduction(inscan, +: argc)
   for (int i = 0; i < 10; ++i)
   do
-#pragma omp scan inclusive(argc) // expected-error {{'#pragma omp scan' cannot be an immediate substatement}}
+#pragma omp scan inclusive(argc) // expected-error {{'#pragma omp scan' cannot be an immediate substatement}} expected-error {{orphaned 'omp scan' directives are prohibited; perhaps you forget to enclose the directive into a for, simd, for simd, parallel for, or parallel for simd region?}}
 while (argc)
   ;
-#pragma omp simd reduction(inscan, +: argc)
+#pragma omp simd reduction(inscan, +: argc) // expected-error {{the inscan reduction list item must appear as a list item in an 'inclusive' or 'exclusive' clause on an inner 'omp scan' directive}}
   for (int i = 0; i < 10; ++i)
   do {
-#pragma omp scan inclusive(argc)
+#pragma omp scan inclusive(argc) // expected-error {{orphaned 'omp scan' directives are prohibited; perhaps you forget to enclose the directive into a for, simd, for simd, parallel for, or parallel for simd region?}}
   } while (argc);
 #pragma omp simd reduction(inscan, +: argc)
   for (int i = 0; i < 10; ++i)
   switch (argc)
-#pragma omp scan inclusive(argc) // expected-error {{'#pragma omp scan' cannot be an immediate substatement}}
+#pragma omp scan inclusive(argc) // expected-error {{'#pragma omp scan' cannot be an immediate substatement}} expected-error {{orphaned 'omp scan' directives are p

[PATCH] D79693: [test][ARM][CMSE] Use -ffreestanding for arm_cmse.h tests

2020-05-14 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added a comment.

In D79693#2036599 , @chill wrote:

> How do you trigger a problem?


If your build was configured with `DEFAULT_SYSROOT` to a toolchain path that 
has a `/include` directory, then the contents of that directory would be picked 
up. The intent of the person doing the build with regards to `DEFAULT_SYSROOT` 
is to provide a sysroot for their intended targets, which may not match the 
needs of the explicit target provided here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79693



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


[PATCH] D79754: [OpenMP][AMDGCN] Support OpenMP offloading for AMDGCN architecture - Part 1

2020-05-14 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: llvm/include/llvm/ADT/Triple.h:699
+  /// Tests whether the target is a GPU i.e. NVPTX or AMDGCN
+  bool isGPU() const { return isNVPTX() || isAMDGCN(); }
+

This is skipping out r600, and probably should leave this in clang?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79754



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


[PATCH] D79677: [clang][OpenMP][OMPIRBuilder] Adding some Privatization clauses to OpenMP `parallel` Directive

2020-05-14 Thread Fady Ghanim via Phabricator via cfe-commits
fghanim marked 2 inline comments as done.
fghanim added a comment.

In D79677#2032942 , @jdoerfert wrote:

> Generally you copied the existing Clang logic, correct?


Well, Yes and no. I tried to keep as much as I can of the original 
implementation, however, some required more extensive changes.

The things added to `emitparalleldirective` are all new
Almost the latter half of the OMPBuilder version of `emitfirstprivateclause`
somethings in the the OMPBuilder version of `emitcopyinclause`
The rest had minor or smaller changes, but generally the same
the lit tests had some changes




Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:803
-  OrigVD);
-else
-  (void)CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(*this,

jdoerfert wrote:
> Wasn't this part of D79675?
> 
> (btw I tried to comprehend why this is needed and it is on my list for things 
> we replace eventually).
ignore - I originally wanted to use the original `emitfirstprivate`, before I 
had to make some changes. This is remaining from that code. The same comment / 
todo is in OMPBuilder specific version below.

I also, removed this from D79676


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79677



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


[PATCH] D79788: AMDGPU/OpenCL: Accept -nostdlib in place of -nogpulib

2020-05-14 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm closed this revision.
arsenm added a comment.

235fb7dc24b1cf7034dfc76bb853ffb4ac5dec5d 



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

https://reviews.llvm.org/D79788



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


[clang-tools-extra] 10b4931 - [test] NFC, add missing declarations and include to test files to avoid 'implicit-function-declaration' diagnostics in the tests

2020-05-14 Thread Alex Lorenz via cfe-commits

Author: Alex Lorenz
Date: 2020-05-14T10:01:50-07:00
New Revision: 10b49315faa6338eaf52bb782e7c53644ad17dab

URL: 
https://github.com/llvm/llvm-project/commit/10b49315faa6338eaf52bb782e7c53644ad17dab
DIFF: 
https://github.com/llvm/llvm-project/commit/10b49315faa6338eaf52bb782e7c53644ad17dab.diff

LOG: [test] NFC, add missing declarations and include to test files to avoid 
'implicit-function-declaration' diagnostics in the tests

Added: 


Modified: 
clang-tools-extra/test/clang-tidy/checkers/darwin-avoid-spinlock.m
compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c
compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c.gcov
compiler-rt/test/profile/instrprof-value-prof.c

Removed: 




diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/darwin-avoid-spinlock.m 
b/clang-tools-extra/test/clang-tidy/checkers/darwin-avoid-spinlock.m
index c870e0a0fed0..f395386a02f4 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/darwin-avoid-spinlock.m
+++ b/clang-tools-extra/test/clang-tidy/checkers/darwin-avoid-spinlock.m
@@ -2,6 +2,10 @@
 
 typedef int OSSpinLock;
 
+void OSSpinlockLock(OSSpinLock *l);
+void OSSpinlockTry(OSSpinLock *l);
+void OSSpinlockUnlock(OSSpinLock *l);
+
 @implementation Foo
 - (void)f {
 int i = 1;

diff  --git 
a/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c 
b/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c
index dadd8959991a..56e0538b1e83 100644
--- a/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c
+++ b/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c
@@ -1,3 +1,5 @@
+extern void __gcov_flush();
+extern int remove(const char *);
 int main(void) {
   __gcov_flush();
 

diff  --git 
a/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c.gcov 
b/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c.gcov
index 83755451631d..b0921d22461e 100644
--- 
a/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c.gcov
+++ 
b/compiler-rt/test/profile/Inputs/instrprof-gcov-__gcov_flush-multiple.c.gcov
@@ -3,19 +3,21 @@
 // CHECK-NEXT:-:0:Data:instrprof-gcov-__gcov_flush-multiple.gcda
 // CHECK-NEXT:-:0:Runs:1
 // CHECK-NEXT:-:0:Programs:1
-// CHECK-NEXT:#:1:int main(void) {
-// CHECK-NEXT:#:2:  __gcov_flush();
-// CHECK-NEXT:-:3:
-// CHECK-NEXT:#:4:  if 
(remove("instrprof-gcov-__gcov_flush-multiple.gcda") != 0) {
-// CHECK-NEXT:#:5:return 1;
-// CHECK-NEXT:-:6:  }
-// CHECK-NEXT:-:7:
-// CHECK-NEXT:#:8:  __gcov_flush();
-// CHECK-NEXT:#:9:  __gcov_flush();
-// CHECK-NEXT:-:   10:
-// CHECK-NEXT:#:   11:  if 
(remove("instrprof-gcov-__gcov_flush-multiple.gcda") != 0) {
-// CHECK-NEXT:#:   12:return 1;
-// CHECK-NEXT:-:   13:  }
-// CHECK-NEXT:-:   14:
-// CHECK-NEXT:1:   15:  return 0;
-// CHECK-NEXT:1:   16:}
+// CHECK-NEXT:-:1:extern void __gcov_flush();
+// CHECK-NEXT:-:2:extern int remove(const char *);
+// CHECK-NEXT:#:3:int main(void) {
+// CHECK-NEXT:#:4:  __gcov_flush();
+// CHECK-NEXT:-:5:
+// CHECK-NEXT:#:6:  if 
(remove("instrprof-gcov-__gcov_flush-multiple.gcda") != 0) {
+// CHECK-NEXT:#:7:return 1;
+// CHECK-NEXT:-:8:  }
+// CHECK-NEXT:-:9:
+// CHECK-NEXT:#:   10:  __gcov_flush();
+// CHECK-NEXT:#:   11:  __gcov_flush();
+// CHECK-NEXT:-:   12:
+// CHECK-NEXT:#:   13:  if 
(remove("instrprof-gcov-__gcov_flush-multiple.gcda") != 0) {
+// CHECK-NEXT:#:   14:return 1;
+// CHECK-NEXT:-:   15:  }
+// CHECK-NEXT:-:   16:
+// CHECK-NEXT:1:   17:  return 0;
+// CHECK-NEXT:1:   18:}

diff  --git a/compiler-rt/test/profile/instrprof-value-prof.c 
b/compiler-rt/test/profile/instrprof-value-prof.c
index 3a5bdbdd552e..53e5fdafc520 100644
--- a/compiler-rt/test/profile/instrprof-value-prof.c
+++ b/compiler-rt/test/profile/instrprof-value-prof.c
@@ -27,6 +27,7 @@
 #include 
 #include 
 #include 
+#include 
 typedef struct __llvm_profile_data __llvm_profile_data;
 const __llvm_profile_data *__llvm_profile_begin_data(void);
 const __llvm_profile_data *__llvm_profile_end_data(void);



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


[PATCH] D79035: [clang][AIX] Implement ABIInfo and TargetCodeGenInfo for AIX

2020-05-14 Thread Zarko Todorovski via Phabricator via cfe-commits
ZarkoCA added a comment.

I'm ok with this now. I will let @Xiangling_L approve if she's ok with it since 
she had the last few comments.


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

https://reviews.llvm.org/D79035



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


[PATCH] D79693: [test][ARM][CMSE] Use -ffreestanding for arm_cmse.h tests

2020-05-14 Thread Momchil Velikov via Phabricator via cfe-commits
chill added a comment.

I see.

I can also count (`grep -rn '#include.*https://reviews.llvm.org/D79693/new/

https://reviews.llvm.org/D79693



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


[PATCH] D79257: [OPENMP50]Codegen for uses_allocators clause.

2020-05-14 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev updated this revision to Diff 264020.
ABataev added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79257

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/lib/Sema/SemaOpenMP.cpp
  clang/test/OpenMP/target_parallel_for_simd_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_parallel_for_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_parallel_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_simd_uses_allocators_codegen.cpp
  
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_uses_allocators_codegen.cpp
  
clang/test/OpenMP/target_teams_distribute_parallel_for_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_simd_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_teams_distribute_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_teams_uses_allocators_codegen.cpp
  clang/test/OpenMP/target_uses_allocators_codegen.cpp

Index: clang/test/OpenMP/target_uses_allocators_codegen.cpp
===
--- /dev/null
+++ clang/test/OpenMP/target_uses_allocators_codegen.cpp
@@ -0,0 +1,93 @@
+// Test host codegen.
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=50 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64
+
+// expected-no-diagnostics
+#ifndef HEADER
+#define HEADER
+
+enum omp_allocator_handle_t {
+  omp_null_allocator = 0,
+  omp_default_mem_alloc = 1,
+  omp_large_cap_mem_alloc = 2,
+  omp_const_mem_alloc = 3,
+  omp_high_bw_mem_alloc = 4,
+  omp_low_lat_mem_alloc = 5,
+  omp_cgroup_mem_alloc = 6,
+  omp_pteam_mem_alloc = 7,
+  omp_thread_mem_alloc = 8,
+  KMP_ALLOCATOR_MAX_HANDLE = __UINTPTR_MAX__
+};
+
+typedef enum omp_alloctrait_key_t { omp_atk_sync_hint = 1,
+omp_atk_alignment = 2,
+omp_atk_access = 3,
+omp_atk_pool_size = 4,
+omp_atk_fallback = 5,
+omp_atk_fb_data = 6,
+omp_atk_pinned = 7,
+omp_atk_partition = 8
+} omp_alloctrait_key_t;
+typedef enum omp_alloctrait_value_t {
+  omp_atv_false = 0,
+  omp_atv_true = 1,
+  omp_atv_default = 2,
+  omp_atv_contended = 3,
+  omp_atv_uncontended = 4,
+  omp_atv_sequential = 5,
+  omp_atv_private = 6,
+  omp_atv_all = 7,
+  omp_atv_thread = 8,
+  omp_atv_pteam = 9,
+  omp_atv_cgroup = 10,
+  omp_atv_default_mem_fb = 11,
+  omp_atv_null_fb = 12,
+  omp_atv_abort_fb = 13,
+  omp_atv_allocator_fb = 14,
+  omp_atv_environment = 15,
+  omp_atv_nearest = 16,
+  omp_atv_blocked = 17,
+  omp_atv_interleaved = 18
+} omp_alloctrait_value_t;
+
+typedef struct omp_alloctrait_t {
+  omp_alloctrait_key_t key;
+  __UINTPTR_TYPE__ value;
+} omp_alloctrait_t;
+
+// Just map the traits variable as a firstprivate variable.
+// CHECK-DAG: [[SIZES:@.+]] = private unnamed_addr constant [1 x i64] [i64 160]
+// CHECK-DAG: [[MAPTYPES:@.+]] = private unnamed_addr constant [1 x i64] [i64 673]
+
+// CHECK: define {{.*}}[[FOO:@.+]]()
+void foo() {
+  omp_alloctrait_t traits[10];
+  omp_allocator_handle_t my_allocator;
+
+// CHECK: [[RES:%.+]] = call i32 @__tgt_target(i64 -1, i8* @.[[TGT_REGION:.+]].region_id, i32 1, i8** %{{.+}}, i8** %{{.+}}, i64* getelementptr inbounds ([1 x i64], [1 x i64]* [[SIZES]], i32 0, i32 0), i64* getelementptr inbounds ([1 x i64], [1 x i64]* [[MAPTYPES]], i32 0, i32 0))
+// CHECK: [[CMP:%.+]] = icmp ne i32 [[RES]], 0
+// CHECK: br i1 [[CMP]], label %[[FAILED:.+]], label %[[DONE:.+]]
+// CHECK: [[FAILED]]:
+// CHECK: call void @[[TGT_REGION]]([10 x %struct.omp_alloctrait_t]* %{{[^,]+}})
+#pragma omp target uses_allocators(omp_null_allocator, omp_thread_mem_alloc, my_allocator(traits))
+  ;
+}
+
+// CHECK: define internal void @[[TGT_REGION]]([10 x %struct.omp_alloctrait_t]* {{.+}})
+// CHECK: [[TRAITS_ADDR_REF:%.+]] = alloca [10 x %struct.omp_alloctrait_t]*,
+// CHECK: [[MY_ALLOCATOR_ADDR:%.+]] = alloca i64,
+// CHECK: [[TRAITS_ADDR:%.+]] = load [10 x %struct.omp_alloctrait_t]*, [10 x %struct.omp_alloctrait_t]** [[TRAITS_ADDR_REF]],
+// CHECK: [[TRAITS_ADDR_VOIDPTR:%.+]] = bitcast [10 x %struct.omp_alloctrait_t]* [[TRAITS_ADDR]] to i8**
+// CHECK: [[TRAITS:%.+]] = load i8*, i8** [[TRAITS_ADDR_VOIDPTR]],
+// CHECK: [[ALLOCATOR:%.+]] = call i8* @__kmpc_

[PATCH] D79919: [Driver] Pass -plugin-opt=O2 for -Os -Oz and -plugin-opt=O1 for -Og

2020-05-14 Thread Peter Collingbourne via Phabricator via cfe-commits
pcc accepted this revision.
pcc added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: clang/test/Driver/lto.c:52
+// RUN: %clang -target x86_64-unknown-linux-gnu --sysroot 
%S/Inputs/basic_cross_linux_tree %s \
+// RUN:   -fuse-ld=lld -flto -O -### 2>&1 | FileCheck --check-prefix=O1 %s
+// RUN: %clang -target x86_64-unknown-linux-gnu --sysroot 
%S/Inputs/basic_cross_linux_tree %s \

I think this one should be `--check-prefix=O2`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79919



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


[PATCH] D79715: [clang-format] Update GoogleStyle for C# code to match Google's internal C# style guide

2020-05-14 Thread Jonathan B Coe via Phabricator via cfe-commits
jbcoe planned changes to this revision.
jbcoe added a comment.

I will get the Google Style guide uploaded and update this patch with a link.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79715



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


[clang] 5ecb514 - [Driver] Pass -plugin-opt=O2 for -Os -Oz and -plugin-opt=O1 for -Og

2020-05-14 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2020-05-14T10:37:33-07:00
New Revision: 5ecb51414637402b0f89a96924ac7b015d23bcfa

URL: 
https://github.com/llvm/llvm-project/commit/5ecb51414637402b0f89a96924ac7b015d23bcfa
DIFF: 
https://github.com/llvm/llvm-project/commit/5ecb51414637402b0f89a96924ac7b015d23bcfa.diff

LOG: [Driver] Pass -plugin-opt=O2 for -Os -Oz and -plugin-opt=O1 for -Og

Fixes PR42445 (compiler driver options -Os -Oz translate to
-plugin-opt=Os (Oz) which are not recognized by LLVMgold.so or LLD).

The optimization level mapping matches
CompilerInvocation.cpp:getOptimizationLevel() and SpeedLevel of
PassBuilder::OptimizationLevel::O*.

-plugin-opt=O* affects the way we construct regular LTO/ThinLTO pass
manager pipeline.

Reviewed By: pcc

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/test/Driver/lto.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 5219f28565a4..d6451447a924 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -390,13 +390,19 @@ void tools::addLTOOptions(const ToolChain &ToolChain, 
const ArgList &Args,
 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
 
   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
+// The optimization level matches
+// CompilerInvocation.cpp:getOptimizationLevel().
 StringRef OOpt;
 if (A->getOption().matches(options::OPT_O4) ||
 A->getOption().matches(options::OPT_Ofast))
   OOpt = "3";
-else if (A->getOption().matches(options::OPT_O))
+else if (A->getOption().matches(options::OPT_O)) {
   OOpt = A->getValue();
-else if (A->getOption().matches(options::OPT_O0))
+  if (OOpt == "g")
+OOpt = "1";
+  else if (OOpt == "s" || OOpt == "z")
+OOpt = "2";
+} else if (A->getOption().matches(options::OPT_O0))
   OOpt = "0";
 if (!OOpt.empty())
   CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));

diff  --git a/clang/test/Driver/lto.c b/clang/test/Driver/lto.c
index 34e6076dec2e..2308372af9f5 100644
--- a/clang/test/Driver/lto.c
+++ b/clang/test/Driver/lto.c
@@ -48,6 +48,27 @@
 // RUN:   -fuse-ld=gold -flto -fno-lto -### 2>&1 | FileCheck 
--check-prefix=NO-LLVMGOLD %s
 // NO-LLVMGOLD-NOT: "-plugin" "{{.*}}{{[/\\]}}LLVMgold.{{dll|dylib|so}}"
 
+// RUN: %clang -target x86_64-unknown-linux-gnu --sysroot 
%S/Inputs/basic_cross_linux_tree %s \
+// RUN:   -fuse-ld=lld -flto -O -### 2>&1 | FileCheck --check-prefix=O2 %s
+// RUN: %clang -target x86_64-unknown-linux-gnu --sysroot 
%S/Inputs/basic_cross_linux_tree %s \
+// RUN:   -fuse-ld=lld -flto -O1 -### 2>&1 | FileCheck --check-prefix=O1 %s
+// RUN: %clang -target x86_64-unknown-linux-gnu --sysroot 
%S/Inputs/basic_cross_linux_tree %s \
+// RUN:   -fuse-ld=lld -flto -Og -### 2>&1 | FileCheck --check-prefix=O1 %s
+// RUN: %clang -target x86_64-unknown-linux-gnu --sysroot 
%S/Inputs/basic_cross_linux_tree %s \
+// RUN:   -fuse-ld=lld -flto -O2 -### 2>&1 | FileCheck --check-prefix=O2 %s
+// RUN: %clang -target x86_64-unknown-linux-gnu --sysroot 
%S/Inputs/basic_cross_linux_tree %s \
+// RUN:   -fuse-ld=lld -flto -Os -### 2>&1 | FileCheck --check-prefix=O2 %s
+// RUN: %clang -target x86_64-unknown-linux-gnu --sysroot 
%S/Inputs/basic_cross_linux_tree %s \
+// RUN:   -fuse-ld=lld -flto -Oz -### 2>&1 | FileCheck --check-prefix=O2 %s
+// RUN: %clang -target x86_64-unknown-linux-gnu --sysroot 
%S/Inputs/basic_cross_linux_tree %s \
+// RUN:   -fuse-ld=lld -flto -O3 -### 2>&1 | FileCheck --check-prefix=O3 %s
+// RUN: %clang -target x86_64-unknown-linux-gnu --sysroot 
%S/Inputs/basic_cross_linux_tree %s \
+// RUN:   -fuse-ld=lld -flto -Ofast -### 2>&1 | FileCheck --check-prefix=O3 %s
+
+// O1: -plugin-opt=O1
+// O2: -plugin-opt=O2
+// O3: -plugin-opt=O3
+
 // -flto passes along an explicit debugger tuning argument.
 // RUN: %clang -target x86_64-unknown-linux -### %s -flto -glldb 2> %t
 // RUN: FileCheck -check-prefix=CHECK-TUNING-LLDB < %t %s



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


[PATCH] D79950: [clangd] Avoid wasteful data structures in RefSlab::Builder

2020-05-14 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kbobyrev.
Herald added subscribers: cfe-commits, usaxena95, kadircet, arphaman, mgrang, 
jkorous, MaskRay, ilya-biryukov.
Herald added a project: clang.

This is worth another 10% or so on InedxBenchmark.DexBuild.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D79950

Files:
  clang-tools-extra/clangd/index/Ref.cpp
  clang-tools-extra/clangd/index/Ref.h
  clang-tools-extra/clangd/index/SymbolLocation.cpp
  clang-tools-extra/clangd/index/SymbolLocation.h

Index: clang-tools-extra/clangd/index/SymbolLocation.h
===
--- clang-tools-extra/clangd/index/SymbolLocation.h
+++ clang-tools-extra/clangd/index/SymbolLocation.h
@@ -30,22 +30,23 @@
   // Position is encoded into 32 bits to save space.
   // If Line/Column overflow, the value will be their maximum value.
   struct Position {
-Position() : Line(0), Column(0) {}
+Position() : LineColumnPacked(0) {}
 void setLine(uint32_t Line);
-uint32_t line() const { return Line; }
+uint32_t line() const { return LineColumnPacked >> ColumnBits; }
 void setColumn(uint32_t Column);
-uint32_t column() const { return Column; }
+uint32_t column() const { return LineColumnPacked & MaxColumn; }
+uint32_t rep() const { return LineColumnPacked; }
 
 bool hasOverflow() const {
-  return Line >= MaxLine || Column >= MaxColumn;
+  return line() == MaxLine || column() == MaxColumn;
 }
 
-static constexpr uint32_t MaxLine = (1 << 20) - 1;
-static constexpr uint32_t MaxColumn = (1 << 12) - 1;
+static constexpr unsigned ColumnBits = 12;
+static constexpr uint32_t MaxLine = (1 << (32 - ColumnBits)) - 1;
+static constexpr uint32_t MaxColumn = (1 << ColumnBits) - 1;
 
   private:
-uint32_t Line : 20;   // 0-based
-uint32_t Column : 12; // 0-based
+uint32_t LineColumnPacked; // Top 20 bit line, bottom 12 bits column.
   };
 
   /// The symbol range, using half-open range [Start, End).
Index: clang-tools-extra/clangd/index/SymbolLocation.cpp
===
--- clang-tools-extra/clangd/index/SymbolLocation.cpp
+++ clang-tools-extra/clangd/index/SymbolLocation.cpp
@@ -15,18 +15,14 @@
 constexpr uint32_t SymbolLocation::Position::MaxColumn;
 
 void SymbolLocation::Position::setLine(uint32_t L) {
-  if (L > MaxLine) {
-Line = MaxLine;
-return;
-  }
-  Line = L;
+  if (L > MaxLine)
+L = MaxLine;
+  LineColumnPacked = (L << ColumnBits) | column();
 }
 void SymbolLocation::Position::setColumn(uint32_t Col) {
-  if (Col > MaxColumn) {
-Column = MaxColumn;
-return;
-  }
-  Column = Col;
+  if (Col > MaxColumn)
+Col = MaxColumn;
+  LineColumnPacked = (LineColumnPacked & ~MaxColumn) | Col;
 }
 
 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const SymbolLocation &L) {
Index: clang-tools-extra/clangd/index/Ref.h
===
--- clang-tools-extra/clangd/index/Ref.h
+++ clang-tools-extra/clangd/index/Ref.h
@@ -13,6 +13,7 @@
 #include "SymbolLocation.h"
 #include "clang/Index/IndexSymbol.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/Hashing.h"
 #include "llvm/Support/StringSaver.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
@@ -132,9 +133,17 @@
 RefSlab build() &&;
 
   private:
+// A ref we're storing with its symbol to consume with build().
+// All strings are interned, so DenseMapInfo can use pointer comparisons.
+struct Entry {
+  SymbolID Symbol;
+  Ref R;
+};
+friend struct llvm::DenseMapInfo;
+
 llvm::BumpPtrAllocator Arena;
 llvm::UniqueStringSaver UniqueStrings; // Contents on the arena.
-llvm::DenseMap> Refs;
+llvm::DenseSet Entries;
   };
 
 private:
@@ -151,4 +160,29 @@
 } // namespace clangd
 } // namespace clang
 
+namespace llvm {
+template <> struct DenseMapInfo {
+  using Entry = clang::clangd::RefSlab::Builder::Entry;
+  static inline Entry getEmptyKey() {
+static Entry E{clang::clangd::SymbolID(""), {}};
+return E;
+  }
+  static inline Entry getTombstoneKey() {
+static Entry E{clang::clangd::SymbolID("TOMBSTONE"), {}};
+return E;
+  }
+  static unsigned getHashValue(const Entry &Val) {
+return llvm::hash_combine(
+Val.Symbol, reinterpret_cast(Val.R.Location.FileURI),
+Val.R.Location.Start.rep(), Val.R.Location.End.rep());
+  }
+  static bool isEqual(const Entry &LHS, const Entry &RHS) {
+return std::tie(LHS.Symbol, LHS.R.Location.FileURI, LHS.R.Kind) ==
+   std::tie(RHS.Symbol, RHS.R.Location.FileURI, RHS.R.Kind) &&
+   LHS.R.Location.Start == RHS.R.Location.Start &&
+   LHS.R.Location.End == RHS.R.Location.End;
+  }
+};
+}; // namespace llvm
+
 #endif // LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_REF_H
Index: clang-tools-extra/clangd/index/Ref.cpp
=

[PATCH] D76420: Prevent IR-gen from emitting consteval declarations

2020-05-14 Thread Tyker via Phabricator via cfe-commits
Tyker updated this revision to Diff 264023.
Tyker added a comment.

rebased


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76420

Files:
  clang/include/clang/AST/Expr.h
  clang/lib/AST/Expr.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprAgg.cpp
  clang/lib/CodeGen/CGExprComplex.cpp
  clang/lib/CodeGen/CGExprConstant.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/ConstantEmitter.h
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CodeGenCXX/cxx2a-consteval.cpp
  clang/test/SemaCXX/cxx2a-consteval.cpp

Index: clang/test/SemaCXX/cxx2a-consteval.cpp
===
--- clang/test/SemaCXX/cxx2a-consteval.cpp
+++ clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++2a -fsyntax-only -Wno-unused-value %s -verify
+// RUN: %clang_cc1 -std=c++2a -emit-llvm -Wno-unused-value %s -verify > /dev/null
 
 typedef __SIZE_TYPE__ size_t;
 
Index: clang/test/CodeGenCXX/cxx2a-consteval.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/cxx2a-consteval.cpp
@@ -0,0 +1,212 @@
+// NOTE: Assertions have been autogenerated by utils/update_test_checks.py
+// RUN: %clang_cc1 -emit-llvm %s -std=c++2a -o %t.ll
+// RUN: FileCheck -check-prefix=EVAL -input-file=%t.ll %s
+// RUN: FileCheck -check-prefix=EVAL-FN -input-file=%t.ll %s
+// RUN: FileCheck -check-prefix=EVAL-STATIC -input-file=%t.ll %s
+// RUN: %clang_cc1 -emit-llvm %s -Dconsteval="" -std=c++2a -o %t.ll
+// RUNA: FileCheck -check-prefix=EXPR -input-file=%t.ll %s
+
+// there is two version of symbol checks to ensure
+// that the symbol we are looking for are correct
+// EVAL-NOT: @__cxx_global_var_init()
+// EXPR: @__cxx_global_var_init()
+
+// EVAL-NOT: @_Z4ret7v()
+// EXPR: @_Z4ret7v()
+consteval int ret7() {
+  return 7;
+}
+
+int test_ret7() {
+// EVAL-FN-LABEL: @_Z9test_ret7v(
+// EVAL-FN-NEXT:  entry:
+// EVAL-FN-NEXT:[[I:%.*]] = alloca i32, align 4
+// EVAL-FN-NEXT:store i32 7, i32* [[I]], align 4
+// EVAL-FN-NEXT:[[TMP0:%.*]] = load i32, i32* [[I]], align 4
+// EVAL-FN-NEXT:ret i32 [[TMP0]]
+//
+  int i = ret7();
+  return i;
+}
+
+// EVAL-STATIC: @global_i = global i32 7, align 4
+int global_i = ret7();
+
+// EVAL-STATIC: @_ZL7i_const = internal constant i32 5, align 4
+constexpr int i_const = 5;
+
+// EVAL-NOT: @_Z4retIv()
+// EXPR: @_Z4retIv()
+consteval const int& retI() {
+  return i_const;
+}
+
+const int& test_retRefI() {
+// EVAL-FN-LABEL: @_Z12test_retRefIv(
+// EVAL-FN-NEXT:  entry:
+// EVAL-FN-NEXT:ret i32* @_ZL7i_const
+//
+  return retI();
+}
+
+int test_retI() {
+// EVAL-FN-LABEL: @_Z9test_retIv(
+// EVAL-FN-NEXT:  entry:
+// EVAL-FN-NEXT:[[TMP0:%.*]] = load i32, i32* @_ZL7i_const, align 4
+// EVAL-FN-NEXT:ret i32 [[TMP0]]
+//
+  return retI();
+}
+
+// EVAL-NOT: @_Z4retIv()
+// EXPR: @_Z4retIv()
+consteval const int* retIPtr() {
+  return &i_const;
+}
+
+int test_retIPtr() {
+// EVAL-FN-LABEL: @_Z12test_retIPtrv(
+// EVAL-FN-NEXT:  entry:
+// EVAL-FN-NEXT:[[TMP0:%.*]] = load i32, i32* @_ZL7i_const, align 4
+// EVAL-FN-NEXT:ret i32 [[TMP0]]
+//
+  return *retIPtr();
+}
+
+const int* test_retPIPtr() {
+// EVAL-FN-LABEL: @_Z13test_retPIPtrv(
+// EVAL-FN-NEXT:  entry:
+// EVAL-FN-NEXT:ret i32* @_ZL7i_const
+//
+  return retIPtr();
+}
+
+// EVAL-NOT: @_Z4retIv()
+// EXPR: @_Z4retIv()
+consteval const int&& retIRRef() {
+  return static_cast(i_const);
+}
+
+// EVAL-NOT: @_Z4retIv()
+// EXPR: @_Z4retIv()
+const int&& test_retIRRef() {
+  return static_cast(retIRRef());
+}
+
+int test_retIRRefI() {
+// EVAL-FN-LABEL: @_Z14test_retIRRefIv(
+// EVAL-FN-NEXT:  entry:
+// EVAL-FN-NEXT:[[TMP0:%.*]] = load i32, i32* @_ZL7i_const, align 4
+// EVAL-FN-NEXT:ret i32 [[TMP0]]
+//
+  return retIRRef();
+}
+
+struct Agg {
+  int a;
+  long b;
+};
+
+// EVAL-NOT: @_Z6retAggv()
+// EXPR: @_Z6retAggv()
+consteval Agg retAgg() {
+  return {13, 17};
+}
+
+long test_retAgg() {
+// EVAL-FN-LABEL: @_Z11test_retAggv(
+// EVAL-FN-NEXT:  entry:
+// EVAL-FN-NEXT:[[B:%.*]] = alloca i64, align 8
+// EVAL-FN-NEXT:[[REF_TMP:%.*]] = alloca [[STRUCT_AGG:%.*]], align 8
+// EVAL-FN-NEXT:[[TMP0:%.*]] = getelementptr inbounds [[STRUCT_AGG]], %struct.Agg* [[REF_TMP]], i32 0, i32 0
+// EVAL-FN-NEXT:store i32 13, i32* [[TMP0]], align 8
+// EVAL-FN-NEXT:[[TMP1:%.*]] = getelementptr inbounds [[STRUCT_AGG]], %struct.Agg* [[REF_TMP]], i32 0, i32 1
+// EVAL-FN-NEXT:store i64 17, i64* [[TMP1]], align 8
+// EVAL-FN-NEXT:store i64 17, i64* [[B]], align 8
+// EVAL-FN-NEXT:[[TMP2:%.*]] = load i64, i64* [[B]], align 8
+// EVAL-FN-NEXT:ret i64 [[TMP2]]
+//
+  long b = retAgg().b;
+  return b;
+}
+
+// EVAL-STATIC: @A =

[PATCH] D79257: [OPENMP50]Codegen for uses_allocators clause.

2020-05-14 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

LGTM. FWIW, we should directly add new runtime functions we emit into 
OMPKinds.def. That saves us the trouble of searching for the ones we missed 
later.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79257



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


  1   2   >