[PATCH] D111883: [Parse] Improve diagnostic and recoveryy when there is an extra override in the outline method definition.

2021-10-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 380291.
hokein marked 2 inline comments as done.
hokein added a comment.

virt-specifier => specifier


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111883

Files:
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/Parse/ParseDecl.cpp
  clang/test/Parser/cxx-extra-virtual-specifiers.cpp


Index: clang/test/Parser/cxx-extra-virtual-specifiers.cpp
===
--- /dev/null
+++ clang/test/Parser/cxx-extra-virtual-specifiers.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -fdiagnostics-parseable-fixits %s
+
+class A {
+  virtual void foo();
+};
+class B : public A {
+  void foo() override;
+};
+
+void B::foo() override {} // expected-error {{'override' specifier is not 
allowed outside a class definition}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:15-[[@LINE-1]]:24}:""
+
+void f1() override; // expected-error {{'override' specifier is not allowed}}
+
+void f2() override {} // expected-error {{'override' specifier is not allowed}}
+
+void test() {
+  void f() override; // expected-error {{'override' specifier is not allowed}}
+}
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -2021,6 +2021,18 @@
   Actions.CodeCompleteAfterFunctionEquals(D);
   return nullptr;
 }
+// We're at the point where the parsing of function declarator is finished.
+//
+// A common error is that users accidently add a virtual specifier
+// (e.g. override) in an out-line method definition.
+// We attempt to recover by stripping all these specifiers coming after
+// the declarator.
+while (auto Specifier = isCXX11VirtSpecifier()) {
+  Diag(Tok, diag::err_virt_specifier_outside_class)
+  << VirtSpecifiers::getSpecifierName(Specifier)
+  << FixItHint::CreateRemoval(Tok.getLocation());
+  ConsumeToken();
+}
 // Look at the next token to make sure that this isn't a function
 // declaration.  We have to check this because __attribute__ might be the
 // start of a function definition in GCC-extended K&R C.
Index: clang/include/clang/Basic/DiagnosticParseKinds.td
===
--- clang/include/clang/Basic/DiagnosticParseKinds.td
+++ clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -958,6 +958,9 @@
 def err_duplicate_virt_specifier : Error<
   "class member already marked '%0'">;
 
+def err_virt_specifier_outside_class : Error<
+  "'%0' specifier is not allowed outside a class definition">;
+
 def err_expected_parameter_pack : Error<
   "expected the name of a parameter pack">;
 def err_paren_sizeof_parameter_pack : Error<


Index: clang/test/Parser/cxx-extra-virtual-specifiers.cpp
===
--- /dev/null
+++ clang/test/Parser/cxx-extra-virtual-specifiers.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -fdiagnostics-parseable-fixits %s
+
+class A {
+  virtual void foo();
+};
+class B : public A {
+  void foo() override;
+};
+
+void B::foo() override {} // expected-error {{'override' specifier is not allowed outside a class definition}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:15-[[@LINE-1]]:24}:""
+
+void f1() override; // expected-error {{'override' specifier is not allowed}}
+
+void f2() override {} // expected-error {{'override' specifier is not allowed}}
+
+void test() {
+  void f() override; // expected-error {{'override' specifier is not allowed}}
+}
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -2021,6 +2021,18 @@
   Actions.CodeCompleteAfterFunctionEquals(D);
   return nullptr;
 }
+// We're at the point where the parsing of function declarator is finished.
+//
+// A common error is that users accidently add a virtual specifier
+// (e.g. override) in an out-line method definition.
+// We attempt to recover by stripping all these specifiers coming after
+// the declarator.
+while (auto Specifier = isCXX11VirtSpecifier()) {
+  Diag(Tok, diag::err_virt_specifier_outside_class)
+  << VirtSpecifiers::getSpecifierName(Specifier)
+  << FixItHint::CreateRemoval(Tok.getLocation());
+  ConsumeToken();
+}
 // Look at the next token to make sure that this isn't a function
 // declaration.  We have to check this because __attribute__ might be the
 // start of a function definition in GCC-extended K&R C.
Index: clang/include/clang/Basic/DiagnosticParseKinds.td
===
--- clang/include/clang/Basic/Diagn

[PATCH] D111883: [Parse] Improve diagnostic and recoveryy when there is an extra override in the outline method definition.

2021-10-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticParseKinds.td:948
+def err_virt_specifier_outside_class : Error<
+  "'%0' virt-specifier is not allowed outside a class definition">;
+

sammccall wrote:
> sammccall wrote:
> > `virt-specifier` is standardese. I think dropping virt, i.e. `'override' 
> > specifier...` is clear enough.
> Hm, is "outside a class definition" the clearest way to explain the mistake?
> 
> I guess this is handling two classes of problem:
> - repeating `override` on an out-of-line definition (motivating case)
> - placing `override` on a free function
> 
> I'd slightly prefer the motivating case to mention "out-of-line", but that 
> wording doesn't fit the other case. I'm not sure whether it's worth trying to 
> split them 
yeah, the first one is the motivating case, I think it is the most common one, 
but I'm tempted to keep it as-is rather than creating a separate diagnostic 
message for a less-common case.



Comment at: clang/lib/Parse/ParseDecl.cpp:2039
 // start of a function definition in GCC-extended K&R C.
 if (!isDeclarationAfterDeclarator()) {
 

sammccall wrote:
> Do we too have to consider K&R?
> 
> ```
> typedef int override;
> void foo(a) 
> override a; 
> {
> }
> ```
> 
> I guess not because this behavior only fires for c++?
right, the change only affects C++ code -- isCXX11VirtSpecifier returns null 
for non-C++11-or-later code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111883

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


[PATCH] D105169: [Clang/Test]: Rename enable_noundef_analysis to disable-noundef-analysis and turn it off by default

2021-10-18 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D105169#3069220 , @aqjune wrote:

> It seems the original code has a use of an uninitialized variable.
> Line 4420 at seek-preproc.c (function `ff_seek_frame_binary`):
>
>int64_t pos_min=pos_min, pos_max=pos_max, pos, pos_limit; // pos_min and 
> pos_max are self-assigned.
>   ...
>   if (sti->index_entries) {
>  ...
>   }
>   // pos_min and pos_max are used as arguments below
>   pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
>ts_min, ts_max, flags, &ts, avif->read_timestamp);
>
> https://gist.github.com/aqjune/3bd0ea19bbc12b4744843c0c070e994c
>
> If the branch is not taken, `pos_min` and `pos_max` are read while they are 
> still uninitialized.
>
> I guess the variables are self-assigned to avoid warnings?

Yes, I believe so. If the branch is not taken, `pos_min` and `pos_max` are 
undefined when entering `ff_gen_search`. (I would assume that their value isn't 
ever used within `ff_gen_search` in that case.) But regardless of that, in this 
case, the generated code crashes around this line, 
https://gist.github.com/aqjune/3bd0ea19bbc12b4744843c0c070e994c#file-ff_seek_frame_binary-c-L39,
 before entering `ff_gen_search` - and within that branch, those variables are 
properly set before they're used.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105169

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


[clang] 6e63f96 - [Parse] Improve diagnostic and recovery when there is an extra override in the outline method definition.

2021-10-18 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2021-10-18T10:00:21+02:00
New Revision: 6e63f96e11ee9af300b166c994980d3b80cea0c7

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

LOG: [Parse] Improve diagnostic and recovery when there is an extra override in 
the outline method definition.

The clang behavior was poor before this patch:

```
void B::foo() override {}
// Before: clang emited "expcted function body after function
// declarator", and skiped all contents until it hits a ";", the
// following function f() is discarded.

// VS

// Now "override is not allowed" with a remove fixit, and following f()
// is retained.
void f();
```

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

Added: 
clang/test/Parser/cxx-extra-virtual-specifiers.cpp

Modified: 
clang/include/clang/Basic/DiagnosticParseKinds.td
clang/lib/Parse/ParseDecl.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index e82eafba99546..367da91afbae1 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -958,6 +958,9 @@ def err_duplicate_class_virt_specifier : Error<
 def err_duplicate_virt_specifier : Error<
   "class member already marked '%0'">;
 
+def err_virt_specifier_outside_class : Error<
+  "'%0' specifier is not allowed outside a class definition">;
+
 def err_expected_parameter_pack : Error<
   "expected the name of a parameter pack">;
 def err_paren_sizeof_parameter_pack : Error<

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 9f660e466aae0..a0871062395e6 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -2021,6 +2021,18 @@ Parser::DeclGroupPtrTy 
Parser::ParseDeclGroup(ParsingDeclSpec &DS,
   Actions.CodeCompleteAfterFunctionEquals(D);
   return nullptr;
 }
+// We're at the point where the parsing of function declarator is finished.
+//
+// A common error is that users accidently add a virtual specifier
+// (e.g. override) in an out-line method definition.
+// We attempt to recover by stripping all these specifiers coming after
+// the declarator.
+while (auto Specifier = isCXX11VirtSpecifier()) {
+  Diag(Tok, diag::err_virt_specifier_outside_class)
+  << VirtSpecifiers::getSpecifierName(Specifier)
+  << FixItHint::CreateRemoval(Tok.getLocation());
+  ConsumeToken();
+}
 // Look at the next token to make sure that this isn't a function
 // declaration.  We have to check this because __attribute__ might be the
 // start of a function definition in GCC-extended K&R C.

diff  --git a/clang/test/Parser/cxx-extra-virtual-specifiers.cpp 
b/clang/test/Parser/cxx-extra-virtual-specifiers.cpp
new file mode 100644
index 0..f09883424dc8a
--- /dev/null
+++ b/clang/test/Parser/cxx-extra-virtual-specifiers.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -fdiagnostics-parseable-fixits %s
+
+class A {
+  virtual void foo();
+};
+class B : public A {
+  void foo() override;
+};
+
+void B::foo() override {} // expected-error {{'override' specifier is not 
allowed outside a class definition}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:15-[[@LINE-1]]:24}:""
+
+void f1() override; // expected-error {{'override' specifier is not allowed}}
+
+void f2() override {} // expected-error {{'override' specifier is not allowed}}
+
+void test() {
+  void f() override; // expected-error {{'override' specifier is not allowed}}
+}



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


[PATCH] D111883: [Parse] Improve diagnostic and recoveryy when there is an extra override in the outline method definition.

2021-10-18 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6e63f96e11ee: [Parse] Improve diagnostic and recovery when 
there is an extra override in the… (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111883

Files:
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/Parse/ParseDecl.cpp
  clang/test/Parser/cxx-extra-virtual-specifiers.cpp


Index: clang/test/Parser/cxx-extra-virtual-specifiers.cpp
===
--- /dev/null
+++ clang/test/Parser/cxx-extra-virtual-specifiers.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -fdiagnostics-parseable-fixits %s
+
+class A {
+  virtual void foo();
+};
+class B : public A {
+  void foo() override;
+};
+
+void B::foo() override {} // expected-error {{'override' specifier is not 
allowed outside a class definition}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:15-[[@LINE-1]]:24}:""
+
+void f1() override; // expected-error {{'override' specifier is not allowed}}
+
+void f2() override {} // expected-error {{'override' specifier is not allowed}}
+
+void test() {
+  void f() override; // expected-error {{'override' specifier is not allowed}}
+}
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -2021,6 +2021,18 @@
   Actions.CodeCompleteAfterFunctionEquals(D);
   return nullptr;
 }
+// We're at the point where the parsing of function declarator is finished.
+//
+// A common error is that users accidently add a virtual specifier
+// (e.g. override) in an out-line method definition.
+// We attempt to recover by stripping all these specifiers coming after
+// the declarator.
+while (auto Specifier = isCXX11VirtSpecifier()) {
+  Diag(Tok, diag::err_virt_specifier_outside_class)
+  << VirtSpecifiers::getSpecifierName(Specifier)
+  << FixItHint::CreateRemoval(Tok.getLocation());
+  ConsumeToken();
+}
 // Look at the next token to make sure that this isn't a function
 // declaration.  We have to check this because __attribute__ might be the
 // start of a function definition in GCC-extended K&R C.
Index: clang/include/clang/Basic/DiagnosticParseKinds.td
===
--- clang/include/clang/Basic/DiagnosticParseKinds.td
+++ clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -958,6 +958,9 @@
 def err_duplicate_virt_specifier : Error<
   "class member already marked '%0'">;
 
+def err_virt_specifier_outside_class : Error<
+  "'%0' specifier is not allowed outside a class definition">;
+
 def err_expected_parameter_pack : Error<
   "expected the name of a parameter pack">;
 def err_paren_sizeof_parameter_pack : Error<


Index: clang/test/Parser/cxx-extra-virtual-specifiers.cpp
===
--- /dev/null
+++ clang/test/Parser/cxx-extra-virtual-specifiers.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -fdiagnostics-parseable-fixits %s
+
+class A {
+  virtual void foo();
+};
+class B : public A {
+  void foo() override;
+};
+
+void B::foo() override {} // expected-error {{'override' specifier is not allowed outside a class definition}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:15-[[@LINE-1]]:24}:""
+
+void f1() override; // expected-error {{'override' specifier is not allowed}}
+
+void f2() override {} // expected-error {{'override' specifier is not allowed}}
+
+void test() {
+  void f() override; // expected-error {{'override' specifier is not allowed}}
+}
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -2021,6 +2021,18 @@
   Actions.CodeCompleteAfterFunctionEquals(D);
   return nullptr;
 }
+// We're at the point where the parsing of function declarator is finished.
+//
+// A common error is that users accidently add a virtual specifier
+// (e.g. override) in an out-line method definition.
+// We attempt to recover by stripping all these specifiers coming after
+// the declarator.
+while (auto Specifier = isCXX11VirtSpecifier()) {
+  Diag(Tok, diag::err_virt_specifier_outside_class)
+  << VirtSpecifiers::getSpecifierName(Specifier)
+  << FixItHint::CreateRemoval(Tok.getLocation());
+  ConsumeToken();
+}
 // Look at the next token to make sure that this isn't a function
 // declaration.  We have to check this because __attribute__ might be the
 // start of a function definition in GCC-extended K&R C.
Index: clang/include/clang/Basic/D

[PATCH] D105168: [RISCV] Unify the arch string parsing logic to RISCVISAInfo.

2021-10-18 Thread Adrian Kuegel via Phabricator via cfe-commits
akuegel added inline comments.



Comment at: llvm/include/llvm/Support/RISCVISAInfo.h:15
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Support/Error.h"

Would it be possible to avoid the usage of ArgList in a target that belongs to 
Support?
This introduces a dependency cycle, since Option already depends on Support.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105168

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


[PATCH] D111975: [clang-format] [PR52015] clang-format should put __attribute__((foo)) on its own line before @interface / @implementation / @protocol

2021-10-18 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay created this revision.
MyDeveloperDay added reviewers: benhamilton, krasimir, HazardyKnusperkeks, 
curdeius.
MyDeveloperDay added projects: clang, clang-format.
MyDeveloperDay requested review of this revision.

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

A newline should be place between attribute and @ for objectivec

  __attribute__((objc_subclassing_restricted))  
  @interface Foo
  @end

at present it formats as

  __attribute__((objc_subclassing_restricted))   @interface Foo
  @end


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D111975

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTestObjC.cpp


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -1526,6 +1526,18 @@
"  [obj func:arg2];");
 }
 
+TEST_F(FormatTestObjC, Attributes) {
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@interface Foo\n"
+   "@end");
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@protocol Foo\n"
+   "@end");
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@implementation Foo\n"
+   "@end");
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3832,6 +3832,10 @@
   Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
 return true;
 
+  // Ensure wrapping after __attribute__((XX)) and @interface etc.
+  if (Left.is(TT_AttributeParen) && Right.is(TT_ObjCDecl))
+return true;
+
   if (Left.is(TT_LambdaLBrace)) {
 if (IsFunctionArgument(Left) &&
 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline)


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -1526,6 +1526,18 @@
"  [obj func:arg2];");
 }
 
+TEST_F(FormatTestObjC, Attributes) {
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@interface Foo\n"
+   "@end");
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@protocol Foo\n"
+   "@end");
+  verifyFormat("__attribute__((objc_subclassing_restricted))\n"
+   "@implementation Foo\n"
+   "@end");
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3832,6 +3832,10 @@
   Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
 return true;
 
+  // Ensure wrapping after __attribute__((XX)) and @interface etc.
+  if (Left.is(TT_AttributeParen) && Right.is(TT_ObjCDecl))
+return true;
+
   if (Left.is(TT_LambdaLBrace)) {
 if (IsFunctionArgument(Left) &&
 Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105168: [RISCV] Unify the arch string parsing logic to RISCVISAInfo.

2021-10-18 Thread Raphael Isemann via Phabricator via cfe-commits
teemperor added a comment.

This broke the modules build:

  While building module 'LLVM_Utils' imported from 
lvm/lib/Support/TargetParser.cpp:14:
  In file included from :209:
  llvm/include/llvm/Support/RISCVISAInfo.h:15:10: fatal error: could not build 
module 'LLVM_Option'
  #include "llvm/Option/ArgList.h"
   ^~~
  llvm/lib/Support/TargetParser.cpp:14:10: fatal error: could not build module 
'LLVM_Utils'
  #include "llvm/Support/TargetParser.h"
   ^

`Support` headers can't include `Option` headers (as `Option` depends on 
`Support` already, so that would be a cyclic dependency). I believe folks here 
are in the US time zone, so I went ahead and replaced the header include with a 
forward decl to unbreak the bots (see de4d2f80b75e2a1e4b0ac5c25e20f20839633688 
 )

FWIW, I think there is a better place than `Support` for this new class. 
`Support` is a dependency of nearly every single LLVM component, but this class 
seems to be used by a handful of files. Could we maybe move this to some 
other/new part of LLVM (and make the few components that need it depend on 
that)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105168

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


[PATCH] D110357: [Analyzer] Extend ConstraintAssignor to handle remainder op

2021-10-18 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.

I see. Now it looks correct.

Next time we shall have a z3 proof about the theory.
`A => B` <=> `not(A) or B`. which is SAT only if `A and not(B)` UNSAT.

  a = z3.BitVec('a', 32)
  b = z3.BitVec('b', 32)
  zero = z3.BitVecVal(0, 32)
  s = z3.Solver()
  s.add((a % b) != zero)
  s.add(a == zero)
  s.check() # reports UNSAT

Note: it requires the `z3-solver` pip package.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110357

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


[PATCH] D111543: [clang][modules] Delay creating `IdentifierInfo` for names of explicit modules

2021-10-18 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 380304.
jansvoboda11 retitled this revision from "[clang][modules] Stop creating 
`IdentifierInfo` for names of explicit modules" to "[clang][modules] Delay 
creating `IdentifierInfo` for names of explicit modules".
jansvoboda11 edited the summary of this revision.

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

https://reviews.llvm.org/D111543

Files:
  clang/lib/Frontend/CompilerInstance.cpp
  clang/test/Modules/Inputs/module-name-used-by-objc-bridge/Interface.h
  clang/test/Modules/Inputs/module-name-used-by-objc-bridge/InterfaceBridge.h
  clang/test/Modules/Inputs/module-name-used-by-objc-bridge/module.modulemap
  clang/test/Modules/module-name-used-by-objc-bridge.m


Index: clang/test/Modules/module-name-used-by-objc-bridge.m
===
--- /dev/null
+++ clang/test/Modules/module-name-used-by-objc-bridge.m
@@ -0,0 +1,25 @@
+// RUN: rm -rf %t && mkdir %t
+
+// RUN: %clang_cc1 -fmodules -x objective-c -emit-module 
-fmodule-name=InterfaceBridge \
+// RUN:   %S/Inputs/module-name-used-by-objc-bridge/module.modulemap -o 
%t/InterfaceBridge.pcm
+
+// RUN: %clang_cc1 -fmodules -x objective-c -emit-module 
-fmodule-name=Interface \
+// RUN:   %S/Inputs/module-name-used-by-objc-bridge/module.modulemap -o 
%t/Interface.pcm
+
+// Check that the `-fmodule-file==` form succeeds:
+// RUN: %clang_cc1 -fmodules -fsyntax-only %s -I 
%S/Inputs/module-name-used-by-objc-bridge \
+// RUN:   -fmodule-file=InterfaceBridge=%t/InterfaceBridge.pcm 
-fmodule-file=Interface=%t/Interface.pcm \
+// RUN:   
-fmodule-map-file=%S/Inputs/module-name-used-by-objc-bridge/module.modulemap 
-verify
+
+// Check that the `-fmodule-file=` form succeeds:
+// RUN: %clang_cc1 -fmodules -fsyntax-only %s -I 
%S/Inputs/module-name-used-by-objc-bridge \
+// RUN:   -fmodule-file=%t/InterfaceBridge.pcm -fmodule-file=%t/Interface.pcm \
+// RUN:   
-fmodule-map-file=%S/Inputs/module-name-used-by-objc-bridge/module.modulemap 
-verify
+
+#import "InterfaceBridge.h"
+#import "Interface.h"
+
+@interface Interface (User)
+@end
+
+// expected-no-diagnostics
Index: 
clang/test/Modules/Inputs/module-name-used-by-objc-bridge/module.modulemap
===
--- /dev/null
+++ clang/test/Modules/Inputs/module-name-used-by-objc-bridge/module.modulemap
@@ -0,0 +1,7 @@
+module InterfaceBridge {
+  header "InterfaceBridge.h"
+}
+
+module Interface {
+  header "Interface.h"
+}
Index: 
clang/test/Modules/Inputs/module-name-used-by-objc-bridge/InterfaceBridge.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/module-name-used-by-objc-bridge/InterfaceBridge.h
@@ -0,0 +1 @@
+typedef struct __attribute__((objc_bridge(Interface))) Foo *Bar;
Index: clang/test/Modules/Inputs/module-name-used-by-objc-bridge/Interface.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/module-name-used-by-objc-bridge/Interface.h
@@ -0,0 +1,2 @@
+@interface Interface
+@end
Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -565,25 +565,28 @@
 // the files we were handed.
 struct ReadModuleNames : ASTReaderListener {
   Preprocessor &PP;
-  llvm::SmallVector LoadedModules;
+  llvm::SmallVector LoadedModules;
 
   ReadModuleNames(Preprocessor &PP) : PP(PP) {}
 
   void ReadModuleName(StringRef ModuleName) override {
-LoadedModules.push_back(PP.getIdentifierInfo(ModuleName));
+// Keep the module name as a string for now. It's not safe to create a new
+// IdentifierInfo from an ASTReader callback.
+LoadedModules.push_back(ModuleName.str());
   }
 
   void registerAll() {
 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
-for (auto *II : LoadedModules)
-  MM.cacheModuleLoad(*II, MM.findModule(II->getName()));
+for (const std::string &LoadedModule : LoadedModules)
+  MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
+ MM.findModule(LoadedModule));
 LoadedModules.clear();
   }
 
   void markAllUnavailable() {
-for (auto *II : LoadedModules) {
+for (const std::string &LoadedModule : LoadedModules) {
   if (Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule(
-  II->getName())) {
+  LoadedModule)) {
 M->HasIncompatibleModuleFile = true;
 
 // Mark module as available if the only reason it was unavailable


Index: clang/test/Modules/module-name-used-by-objc-bridge.m
===
--- /dev/null
+++ clang/test/Modules/module-name-used-by-objc-bridge.m
@@ -0,0 +1,25 @@
+// RUN: rm -rf %t && mkdir %t
+
+// RUN: %clang_cc1 -fmodules -x objective-c -emit-module -fmodule-name=

[PATCH] D111543: [clang][modules] Delay creating `IdentifierInfo` for names of explicit modules

2021-10-18 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

Thanks for your analysis, Richard. You're right that we're incorrectly marking 
the identifier as up-to-date.

I've rolled back my changes to `ModuleMap` cache and delayed the creation of 
`IdentifierInfo`. I'll commit if CI is happy.


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

https://reviews.llvm.org/D111543

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


[PATCH] D105169: [Clang/Test]: Rename enable_noundef_analysis to disable-noundef-analysis and turn it off by default

2021-10-18 Thread Juneyoung Lee via Phabricator via cfe-commits
aqjune added a comment.

In D105169#3069417 , @mstorsjo wrote:

> Yes, I believe so. If the branch is not taken, `pos_min` and `pos_max` are 
> undefined when entering `ff_gen_search`. (I would assume that their value 
> isn't ever used within `ff_gen_search` in that case.) But regardless of that, 
> in this case, the generated code crashes around this line, 
> https://gist.github.com/aqjune/3bd0ea19bbc12b4744843c0c070e994c#file-ff_seek_frame_binary-c-L39,
>  before entering `ff_gen_search` - and within that branch, those variables 
> are properly set before they're used.

I see, the crash is happening at the line because SimplifyCFG removes the 
`sti->index_entries` null pointer check (which seems valid to me).
If `stl->index_entries` was null, it would lead to uses of uninitialized 
variables as function arguments, which is UB.
SimplifyCFG relies on the information and removes the `stl->index_entries` null 
check.

  int64_t pos_min=pos_min, pos_max=pos_max, pos, pos_limit; // pos_min and 
pos_max are undef
  ...
  if (sti->index_entries) {
 ... (dereference sti->index_entries+index)
 ... (initialize pos_min and pos_max)
  }
  // If sti->index_entries was NULL, UB must happen at the call below because 
undef is passed to ff_gen_search's noundef arg.
  pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
   ts_min, ts_max, flags, &ts, avif->read_timestamp);

SimplifyCFG optimizes this to the code below:

  int64_t pos_min=pos_min, pos_max=pos_max, pos, pos_limit;
  ...
  if (true) { // Changed to true!
 ... (dereference sti->index_entries+index) // This can crash.
 ... (initialize pos_min and pos_max)
  }
  
  pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
   ts_min, ts_max, flags, &ts, avif->read_timestamp);

I think the solution is to initialize `pos_min` and `pos_max` to some value.
If `sti->index_entries` is null, they are never used inside `ff_gen_search` 
anyway, so initializing it into any value (e.g. 0) will work.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105169

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


[PATCH] D110357: [Analyzer] Extend ConstraintAssignor to handle remainder op

2021-10-18 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1618-1627
+const SymbolRef LHS = Sym->getLHS();
+const llvm::APSInt &Zero =
+Builder.getBasicValueFactory().getValue(0, Sym->getType());
+// a % b != 0 implies that a != 0.
+if (!Constraint.containsZero()) {
+  State = RCM.assumeSymNE(State, LHS, Zero, Zero);
+  if (!State)

How about using the family of `ProgramState::isNonNull` or 
`ProgramState::isNull` or `RangeConstraintManager::checkNull` functoins for 
this stuff?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110357

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


[PATCH] D105169: [Clang/Test]: Rename enable_noundef_analysis to disable-noundef-analysis and turn it off by default

2021-10-18 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D105169#3069555 , @aqjune wrote:

> I see, the crash is happening at the line because SimplifyCFG removes the 
> `sti->index_entries` null pointer check (which seems valid to me).
> If `stl->index_entries` was null, it would lead to uses of uninitialized 
> variables as function arguments, which is UB.
> SimplifyCFG relies on the information and removes the `stl->index_entries` 
> null check.

Thanks! That explains it. Although the actual crash is due to yet another 
removed condition:

  int64_t pos_min=pos_min, pos_max=pos_max, pos, pos_limit; // pos_min and 
pos_max are undef
  ...
  if (sti->index_entries) {
 index = av_index_search_timestamp();
 if (index >= 0) {
 ... (dereference sti->index_entries+index)
 ... (initialize pos_min and pos_max)
 }
  }
  // If sti->index_entries was NULL, UB must happen at the call below because 
undef is passed to ff_gen_search's noundef arg.
  pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
   ts_min, ts_max, flags, &ts, avif->read_timestamp);

Both of the nested if conditions are removed:

  int64_t pos_min=pos_min, pos_max=pos_max, pos, pos_limit;
  ...
  if (true) { // Changed to true!
 index = av_index_search_timestamp();
 if (true) { // Also changed to true
 ... (dereference sti->index_entries+index) // This can crash with 
index = -1
 ... (initialize pos_min and pos_max)
 }
  }
  pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
   ts_min, ts_max, flags, &ts, avif->read_timestamp);



> I think the solution is to initialize `pos_min` and `pos_max` to some value.
> If `sti->index_entries` is null, they are never used inside `ff_gen_search` 
> anyway, so initializing it into any value (e.g. 0) will work.

Yes, any value should be fine (and I guess 0 is the easiest to optimize for the 
compiler). Just as background - this is in a codebase that really tries to 
avoid default variable initializations unless they're proven to be necessary. 
But here they clearly are due to the UB rules of the language.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105169

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


[clang] a2d805c - [clang][modules] Delay creating `IdentifierInfo` for names of explicit modules

2021-10-18 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-10-18T11:50:29+02:00
New Revision: a2d805c020a1658b04ed7e606ee67e234a9d5b56

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

LOG: [clang][modules] Delay creating `IdentifierInfo` for names of explicit 
modules

When using explicit Clang modules, some declarations might unexpectedly become 
invisible.

This is caused by the mechanism that loads PCM files passed via 
`-fmodule-file=` and creates an `IdentifierInfo` for the module name. The 
`IdentifierInfo` creation takes place when the `ASTReader` is in a weird state, 
with modules that are loaded but not yet set up properly. This patch delays the 
creation of `IdentifierInfo` until the `ASTReader` is done with reading the PCM.

Note that the `-fmodule-file==` form of the argument doesn't suffer 
from this issue, since it doesn't create `IdentifierInfo` for the module name.

Reviewed By: dexonsmith

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

Added: 
clang/test/Modules/Inputs/module-name-used-by-objc-bridge/Interface.h
clang/test/Modules/Inputs/module-name-used-by-objc-bridge/InterfaceBridge.h
clang/test/Modules/Inputs/module-name-used-by-objc-bridge/module.modulemap
clang/test/Modules/module-name-used-by-objc-bridge.m

Modified: 
clang/lib/Frontend/CompilerInstance.cpp

Removed: 




diff  --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index 20de9174740ac..a9b9e6516d56f 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -565,25 +565,28 @@ namespace {
 // the files we were handed.
 struct ReadModuleNames : ASTReaderListener {
   Preprocessor &PP;
-  llvm::SmallVector LoadedModules;
+  llvm::SmallVector LoadedModules;
 
   ReadModuleNames(Preprocessor &PP) : PP(PP) {}
 
   void ReadModuleName(StringRef ModuleName) override {
-LoadedModules.push_back(PP.getIdentifierInfo(ModuleName));
+// Keep the module name as a string for now. It's not safe to create a new
+// IdentifierInfo from an ASTReader callback.
+LoadedModules.push_back(ModuleName.str());
   }
 
   void registerAll() {
 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
-for (auto *II : LoadedModules)
-  MM.cacheModuleLoad(*II, MM.findModule(II->getName()));
+for (const std::string &LoadedModule : LoadedModules)
+  MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
+ MM.findModule(LoadedModule));
 LoadedModules.clear();
   }
 
   void markAllUnavailable() {
-for (auto *II : LoadedModules) {
+for (const std::string &LoadedModule : LoadedModules) {
   if (Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule(
-  II->getName())) {
+  LoadedModule)) {
 M->HasIncompatibleModuleFile = true;
 
 // Mark module as available if the only reason it was unavailable

diff  --git 
a/clang/test/Modules/Inputs/module-name-used-by-objc-bridge/Interface.h 
b/clang/test/Modules/Inputs/module-name-used-by-objc-bridge/Interface.h
new file mode 100644
index 0..a825c0d25f311
--- /dev/null
+++ b/clang/test/Modules/Inputs/module-name-used-by-objc-bridge/Interface.h
@@ -0,0 +1,2 @@
+@interface Interface
+@end

diff  --git 
a/clang/test/Modules/Inputs/module-name-used-by-objc-bridge/InterfaceBridge.h 
b/clang/test/Modules/Inputs/module-name-used-by-objc-bridge/InterfaceBridge.h
new file mode 100644
index 0..63f6399a806ce
--- /dev/null
+++ 
b/clang/test/Modules/Inputs/module-name-used-by-objc-bridge/InterfaceBridge.h
@@ -0,0 +1 @@
+typedef struct __attribute__((objc_bridge(Interface))) Foo *Bar;

diff  --git 
a/clang/test/Modules/Inputs/module-name-used-by-objc-bridge/module.modulemap 
b/clang/test/Modules/Inputs/module-name-used-by-objc-bridge/module.modulemap
new file mode 100644
index 0..a0bd43ff80a56
--- /dev/null
+++ b/clang/test/Modules/Inputs/module-name-used-by-objc-bridge/module.modulemap
@@ -0,0 +1,7 @@
+module InterfaceBridge {
+  header "InterfaceBridge.h"
+}
+
+module Interface {
+  header "Interface.h"
+}

diff  --git a/clang/test/Modules/module-name-used-by-objc-bridge.m 
b/clang/test/Modules/module-name-used-by-objc-bridge.m
new file mode 100644
index 0..afaa0cb0e4a7d
--- /dev/null
+++ b/clang/test/Modules/module-name-used-by-objc-bridge.m
@@ -0,0 +1,25 @@
+// RUN: rm -rf %t && mkdir %t
+
+// RUN: %clang_cc1 -fmodules -x objective-c -emit-module 
-fmodule-name=InterfaceBridge \
+// RUN:   %S/Inputs/module-name-used-by-objc-bridge/module.modulemap -o 
%t/InterfaceBridge.pcm
+
+// RUN: %clang_cc1 -fmodules -x objective-c -emit-module 
-fmodule-name=Interface \
+// RUN:   %S/Inputs/module-name-used-by-objc-bridge/module.modulemap -o 
%t/Interface.pcm
+
+// 

[PATCH] D110257: [CFE][Codegen] Make sure to maintain the contiguity of all the static allocas

2021-10-18 Thread Mahesha S via Phabricator via cfe-commits
hsmhsm updated this revision to Diff 380320.
hsmhsm added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110257

Files:
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/test/CodeGenCUDA/builtins-amdgcn.cu
  clang/test/CodeGenCXX/amdgcn-automatic-variable.cpp
  clang/test/CodeGenCXX/amdgcn-func-arg.cpp
  clang/test/CodeGenCXX/builtin-amdgcn-atomic-inc-dec.cpp
  clang/test/CodeGenCXX/vla.cpp
  clang/test/CodeGenSYCL/address-space-deduction.cpp
  clang/test/OpenMP/amdgcn_target_init_temp_alloca.cpp

Index: clang/test/OpenMP/amdgcn_target_init_temp_alloca.cpp
===
--- clang/test/OpenMP/amdgcn_target_init_temp_alloca.cpp
+++ clang/test/OpenMP/amdgcn_target_init_temp_alloca.cpp
@@ -12,7 +12,9 @@
   int arr[N];
 
   // CHECK:  [[VAR_ADDR:%.+]] = alloca [100 x i32]*, align 8, addrspace(5)
+  // CHECK-NEXT: [[VAR2_ADDR:%.+]] = alloca i32, align 4, addrspace(5)
   // CHECK-NEXT: [[VAR_ADDR_CAST:%.+]] = addrspacecast [100 x i32]* addrspace(5)* [[VAR_ADDR]] to [100 x i32]**
+  // CHECK-NEXT: [[VAR2_ADDR_CAST:%.+]] = addrspacecast i32 addrspace(5)* [[VAR2_ADDR]] to i32*
   // CHECK:  store [100 x i32]* [[VAR:%.+]], [100 x i32]** [[VAR_ADDR_CAST]], align 8
 
 #pragma omp target
Index: clang/test/CodeGenSYCL/address-space-deduction.cpp
===
--- clang/test/CodeGenSYCL/address-space-deduction.cpp
+++ clang/test/CodeGenSYCL/address-space-deduction.cpp
@@ -1,34 +1,33 @@
 // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
 // RUN: %clang_cc1 -triple spir64 -fsycl-is-device -disable-llvm-passes -emit-llvm %s -o - | FileCheck %s
 
-
 // CHECK-LABEL: @_Z4testv(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[I:%.*]] = alloca i32, align 4
-// CHECK-NEXT:[[I_ASCAST:%.*]] = addrspacecast i32* [[I]] to i32 addrspace(4)*
 // CHECK-NEXT:[[PPTR:%.*]] = alloca i32 addrspace(4)*, align 8
-// CHECK-NEXT:[[PPTR_ASCAST:%.*]] = addrspacecast i32 addrspace(4)** [[PPTR]] to i32 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[IS_I_PTR:%.*]] = alloca i8, align 1
-// CHECK-NEXT:[[IS_I_PTR_ASCAST:%.*]] = addrspacecast i8* [[IS_I_PTR]] to i8 addrspace(4)*
 // CHECK-NEXT:[[VAR23:%.*]] = alloca i32, align 4
-// CHECK-NEXT:[[VAR23_ASCAST:%.*]] = addrspacecast i32* [[VAR23]] to i32 addrspace(4)*
 // CHECK-NEXT:[[CP:%.*]] = alloca i8 addrspace(4)*, align 8
-// CHECK-NEXT:[[CP_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[CP]] to i8 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[ARR:%.*]] = alloca [42 x i32], align 4
-// CHECK-NEXT:[[ARR_ASCAST:%.*]] = addrspacecast [42 x i32]* [[ARR]] to [42 x i32] addrspace(4)*
 // CHECK-NEXT:[[CPP:%.*]] = alloca i8 addrspace(4)*, align 8
-// CHECK-NEXT:[[CPP_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[CPP]] to i8 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[APTR:%.*]] = alloca i32 addrspace(4)*, align 8
-// CHECK-NEXT:[[APTR_ASCAST:%.*]] = addrspacecast i32 addrspace(4)** [[APTR]] to i32 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[STR:%.*]] = alloca i8 addrspace(4)*, align 8
-// CHECK-NEXT:[[STR_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[STR]] to i8 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[PHI_STR:%.*]] = alloca i8 addrspace(4)*, align 8
-// CHECK-NEXT:[[PHI_STR_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[PHI_STR]] to i8 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[SELECT_NULL:%.*]] = alloca i8 addrspace(4)*, align 8
-// CHECK-NEXT:[[SELECT_NULL_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[SELECT_NULL]] to i8 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[SELECT_STR_TRIVIAL1:%.*]] = alloca i8 addrspace(4)*, align 8
-// CHECK-NEXT:[[SELECT_STR_TRIVIAL1_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[SELECT_STR_TRIVIAL1]] to i8 addrspace(4)* addrspace(4)*
 // CHECK-NEXT:[[SELECT_STR_TRIVIAL2:%.*]] = alloca i8 addrspace(4)*, align 8
+// CHECK-NEXT:[[I_ASCAST:%.*]] = addrspacecast i32* [[I]] to i32 addrspace(4)*
+// CHECK-NEXT:[[PPTR_ASCAST:%.*]] = addrspacecast i32 addrspace(4)** [[PPTR]] to i32 addrspace(4)* addrspace(4)*
+// CHECK-NEXT:[[IS_I_PTR_ASCAST:%.*]] = addrspacecast i8* [[IS_I_PTR]] to i8 addrspace(4)*
+// CHECK-NEXT:[[VAR23_ASCAST:%.*]] = addrspacecast i32* [[VAR23]] to i32 addrspace(4)*
+// CHECK-NEXT:[[CP_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[CP]] to i8 addrspace(4)* addrspace(4)*
+// CHECK-NEXT:[[ARR_ASCAST:%.*]] = addrspacecast [42 x i32]* [[ARR]] to [42 x i32] addrspace(4)*
+// CHECK-NEXT:[[CPP_ASCAST:%.*]] = addrspacecast i8 addrspace(4)** [[CPP]] to i8 addrspace(4)* addrspace(4)*
+// CHECK-NEXT:[[APTR_ASCAST:%.*]] = addrspacecast i32 addrspace(4)** [[APTR]] to i32 addrspace(4)* addrspace(4)*
+// CHECK-NEXT:[[STR_ASCAS

[PATCH] D111543: [clang][modules] Delay creating `IdentifierInfo` for names of explicit modules

2021-10-18 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa2d805c020a1: [clang][modules] Delay creating 
`IdentifierInfo` for names of explicit modules (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111543

Files:
  clang/lib/Frontend/CompilerInstance.cpp
  clang/test/Modules/Inputs/module-name-used-by-objc-bridge/Interface.h
  clang/test/Modules/Inputs/module-name-used-by-objc-bridge/InterfaceBridge.h
  clang/test/Modules/Inputs/module-name-used-by-objc-bridge/module.modulemap
  clang/test/Modules/module-name-used-by-objc-bridge.m


Index: clang/test/Modules/module-name-used-by-objc-bridge.m
===
--- /dev/null
+++ clang/test/Modules/module-name-used-by-objc-bridge.m
@@ -0,0 +1,25 @@
+// RUN: rm -rf %t && mkdir %t
+
+// RUN: %clang_cc1 -fmodules -x objective-c -emit-module 
-fmodule-name=InterfaceBridge \
+// RUN:   %S/Inputs/module-name-used-by-objc-bridge/module.modulemap -o 
%t/InterfaceBridge.pcm
+
+// RUN: %clang_cc1 -fmodules -x objective-c -emit-module 
-fmodule-name=Interface \
+// RUN:   %S/Inputs/module-name-used-by-objc-bridge/module.modulemap -o 
%t/Interface.pcm
+
+// Check that the `-fmodule-file==` form succeeds:
+// RUN: %clang_cc1 -fmodules -fsyntax-only %s -I 
%S/Inputs/module-name-used-by-objc-bridge \
+// RUN:   -fmodule-file=InterfaceBridge=%t/InterfaceBridge.pcm 
-fmodule-file=Interface=%t/Interface.pcm \
+// RUN:   
-fmodule-map-file=%S/Inputs/module-name-used-by-objc-bridge/module.modulemap 
-verify
+
+// Check that the `-fmodule-file=` form succeeds:
+// RUN: %clang_cc1 -fmodules -fsyntax-only %s -I 
%S/Inputs/module-name-used-by-objc-bridge \
+// RUN:   -fmodule-file=%t/InterfaceBridge.pcm -fmodule-file=%t/Interface.pcm \
+// RUN:   
-fmodule-map-file=%S/Inputs/module-name-used-by-objc-bridge/module.modulemap 
-verify
+
+#import "InterfaceBridge.h"
+#import "Interface.h"
+
+@interface Interface (User)
+@end
+
+// expected-no-diagnostics
Index: 
clang/test/Modules/Inputs/module-name-used-by-objc-bridge/module.modulemap
===
--- /dev/null
+++ clang/test/Modules/Inputs/module-name-used-by-objc-bridge/module.modulemap
@@ -0,0 +1,7 @@
+module InterfaceBridge {
+  header "InterfaceBridge.h"
+}
+
+module Interface {
+  header "Interface.h"
+}
Index: 
clang/test/Modules/Inputs/module-name-used-by-objc-bridge/InterfaceBridge.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/module-name-used-by-objc-bridge/InterfaceBridge.h
@@ -0,0 +1 @@
+typedef struct __attribute__((objc_bridge(Interface))) Foo *Bar;
Index: clang/test/Modules/Inputs/module-name-used-by-objc-bridge/Interface.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/module-name-used-by-objc-bridge/Interface.h
@@ -0,0 +1,2 @@
+@interface Interface
+@end
Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -565,25 +565,28 @@
 // the files we were handed.
 struct ReadModuleNames : ASTReaderListener {
   Preprocessor &PP;
-  llvm::SmallVector LoadedModules;
+  llvm::SmallVector LoadedModules;
 
   ReadModuleNames(Preprocessor &PP) : PP(PP) {}
 
   void ReadModuleName(StringRef ModuleName) override {
-LoadedModules.push_back(PP.getIdentifierInfo(ModuleName));
+// Keep the module name as a string for now. It's not safe to create a new
+// IdentifierInfo from an ASTReader callback.
+LoadedModules.push_back(ModuleName.str());
   }
 
   void registerAll() {
 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
-for (auto *II : LoadedModules)
-  MM.cacheModuleLoad(*II, MM.findModule(II->getName()));
+for (const std::string &LoadedModule : LoadedModules)
+  MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule),
+ MM.findModule(LoadedModule));
 LoadedModules.clear();
   }
 
   void markAllUnavailable() {
-for (auto *II : LoadedModules) {
+for (const std::string &LoadedModule : LoadedModules) {
   if (Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule(
-  II->getName())) {
+  LoadedModule)) {
 M->HasIncompatibleModuleFile = true;
 
 // Mark module as available if the only reason it was unavailable


Index: clang/test/Modules/module-name-used-by-objc-bridge.m
===
--- /dev/null
+++ clang/test/Modules/module-name-used-by-objc-bridge.m
@@ -0,0 +1,25 @@
+// RUN: rm -rf %t && mkdir %t
+
+// RUN: %clang_cc1 -fmodules -x objective-c -emit-module -fmodule-name=InterfaceBridge \
+// RUN:   %S/Inputs/module-name-used

[PATCH] D111866: [RISCV] Support Zfhmin extension

2021-10-18 Thread Shao-Ce SUN via Phabricator via cfe-commits
achieveartificialintelligence updated this revision to Diff 380323.
achieveartificialintelligence added a comment.
Herald added a subscriber: jdoerfert.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111866

Files:
  clang/test/Driver/riscv-arch.c
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/RISCV.td
  llvm/lib/Target/RISCV/RISCVISelLowering.cpp
  llvm/lib/Target/RISCV/RISCVInstrInfoZfh.td
  llvm/lib/Target/RISCV/RISCVSubtarget.h
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/MC/RISCV/attribute-arch.s
  llvm/test/MC/RISCV/rv32zfhmin-invalid.s
  llvm/test/MC/RISCV/rv32zfhmin-valid.s

Index: llvm/test/MC/RISCV/rv32zfhmin-valid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rv32zfhmin-valid.s
@@ -0,0 +1,62 @@
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zfhmin,+d -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zfhmin,+d -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+experimental-zfhmin,+d < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zfhmin,+d -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+experimental-zfhmin,+d < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zfhmin,+d -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+
+# CHECK-ASM-AND-OBJ: flh ft0, 12(a0)
+# CHECK-ASM: encoding: [0x07,0x10,0xc5,0x00]
+flh f0, 12(a0)
+# CHECK-ASM-AND-OBJ: flh ft1, 4(ra)
+# CHECK-ASM: encoding: [0x87,0x90,0x40,0x00]
+flh f1, +4(ra)
+# CHECK-ASM-AND-OBJ: flh ft2, -2048(a3)
+# CHECK-ASM: encoding: [0x07,0x91,0x06,0x80]
+flh f2, -2048(x13)
+# CHECK-ASM-AND-OBJ: flh ft3, -2048(s1)
+# CHECK-ASM: encoding: [0x87,0x91,0x04,0x80]
+flh f3, %lo(2048)(s1)
+# CHECK-ASM-AND-OBJ: flh ft4, 2047(s2)
+# CHECK-ASM: encoding: [0x07,0x12,0xf9,0x7f]
+flh f4, 2047(s2)
+# CHECK-ASM-AND-OBJ: flh ft5, 0(s3)
+# CHECK-ASM: encoding: [0x87,0x92,0x09,0x00]
+flh f5, 0(s3)
+
+# CHECK-ASM-AND-OBJ: fsh ft6, 2047(s4)
+# CHECK-ASM: encoding: [0xa7,0x1f,0x6a,0x7e]
+fsh f6, 2047(s4)
+# CHECK-ASM-AND-OBJ: fsh ft7, -2048(s5)
+# CHECK-ASM: encoding: [0x27,0x90,0x7a,0x80]
+fsh f7, -2048(s5)
+# CHECK-ASM-AND-OBJ: fsh fs0, -2048(s6)
+# CHECK-ASM: encoding: [0x27,0x10,0x8b,0x80]
+fsh f8, %lo(2048)(s6)
+# CHECK-ASM-AND-OBJ: fsh fs1, 999(s7)
+# CHECK-ASM: encoding: [0xa7,0x93,0x9b,0x3e]
+fsh f9, 999(s7)
+
+# CHECK-ASM-AND-OBJ: fmv.x.h a2, fs7
+# CHECK-ASM: encoding: [0x53,0x86,0x0b,0xe4]
+fmv.x.h a2, fs7
+# CHECK-ASM-AND-OBJ: fmv.h.x ft1, a6
+# CHECK-ASM: encoding: [0xd3,0x00,0x08,0xf4]
+fmv.h.x ft1, a6
+
+# CHECK-ASM-AND-OBJ: fcvt.s.h fa0, ft0
+# CHECK-ASM: encoding: [0x53,0x05,0x20,0x40]
+fcvt.s.h fa0, ft0
+# CHECK-ASM-AND-OBJ: fcvt.h.s ft2, fa2
+# CHECK-ASM: encoding: [0x53,0x71,0x06,0x44]
+fcvt.h.s ft2, fa2
+# CHECK-ASM-AND-OBJ: fcvt.d.h fa0, ft0
+# CHECK-ASM: encoding: [0x53,0x05,0x20,0x42]
+fcvt.d.h fa0, ft0
+# CHECK-ASM-AND-OBJ: fcvt.h.d ft2, fa2
+# CHECK-ASM: encoding: [0x53,0x71,0x16,0x44]
+fcvt.h.d ft2, fa2
Index: llvm/test/MC/RISCV/rv32zfhmin-invalid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rv32zfhmin-invalid.s
@@ -0,0 +1,23 @@
+# RUN: not llvm-mc -triple riscv32 -mattr=+experimental-zfhmin < %s 2>&1 | \
+# RUN:   FileCheck %s
+
+# Out of range immediates
+## simm12
+flh ft1, -2049(a0) # CHECK: :[[@LINE]]:10: error: operand must be a symbol with %lo/%pcrel_lo/%tprel_lo modifier or an integer in the range [-2048, 2047]
+fsh ft2, 2048(a1) # CHECK: :[[@LINE]]:10: error: operand must be a symbol with %lo/%pcrel_lo/%tprel_lo modifier or an integer in the range [-2048, 2047]
+
+# Memory operand not formatted correctly
+flh ft1, a0, -200 # CHECK: :[[@LINE]]:14: error: invalid operand for instruction
+
+# Invalid register names
+flh ft15, 100(a0) # CHECK: :[[@LINE]]:5: error: invalid operand for instruction
+flh ft1, 100(a10) # CHECK: :[[@LINE]]:14: error: expected register
+
+# Integer registers where FP regs are expected
+fmv.x.h fs7, a2 # CHECK: :[[@LINE]]:9: error: invalid operand for instruction
+
+# FP registers where integer regs are expected
+fmv.h.x a8, ft2 # CHECK: :[[@LINE]]:9: error: invalid operand for instruction
+
+# Zfh instructions
+fmadd.h f10, f11, f12, f13, dyn # CHECK: :[[@LINE]]:1: error: instruction requires the following: 'Zfh' (Half-Precision Floating-Point)
Index: llvm/test/MC/RISCV/attribute-arch.s
===
--- llvm/test/MC/RISCV/attribute-arch.s
+++ llvm/test/MC/RISCV/attribute-arch.s
@@ -66,8 +66,11 @@
 .attribute arch, "rv32izbt"
 # CHECK: attribute  5, "rv32i2p0_zbt

[PATCH] D110258: [AArch64] Always add -tune-cpu argument to -cc1 driver

2021-10-18 Thread David Sherwood via Phabricator via cfe-commits
david-arm updated this revision to Diff 380325.
david-arm added a comment.

- Added something to the ReleaseNotes file.


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

https://reviews.llvm.org/D110258

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/aarch64-mtune.c
  llvm/docs/ReleaseNotes.rst
  llvm/lib/Target/AArch64/AArch64Subtarget.cpp
  llvm/lib/Target/AArch64/AArch64Subtarget.h
  llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
  llvm/unittests/Target/AArch64/InstSizes.cpp
  llvm/unittests/Target/AArch64/MatrixRegisterAliasing.cpp

Index: llvm/unittests/Target/AArch64/MatrixRegisterAliasing.cpp
===
--- llvm/unittests/Target/AArch64/MatrixRegisterAliasing.cpp
+++ llvm/unittests/Target/AArch64/MatrixRegisterAliasing.cpp
@@ -26,6 +26,7 @@
 
 std::unique_ptr createInstrInfo(TargetMachine *TM) {
   AArch64Subtarget ST(TM->getTargetTriple(), std::string(TM->getTargetCPU()),
+  std::string(TM->getTargetCPU()),
   std::string(TM->getTargetFeatureString()), *TM,
   /* isLittle */ false);
   return std::make_unique(ST);
Index: llvm/unittests/Target/AArch64/InstSizes.cpp
===
--- llvm/unittests/Target/AArch64/InstSizes.cpp
+++ llvm/unittests/Target/AArch64/InstSizes.cpp
@@ -29,6 +29,7 @@
 
 std::unique_ptr createInstrInfo(TargetMachine *TM) {
   AArch64Subtarget ST(TM->getTargetTriple(), std::string(TM->getTargetCPU()),
+  std::string(TM->getTargetCPU()),
   std::string(TM->getTargetFeatureString()), *TM,
   /* isLittle */ false);
   return std::make_unique(ST);
Index: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
===
--- llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
+++ llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
@@ -355,10 +355,13 @@
 const AArch64Subtarget *
 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
   Attribute CPUAttr = F.getFnAttribute("target-cpu");
+  Attribute TuneAttr = F.getFnAttribute("tune-cpu");
   Attribute FSAttr = F.getFnAttribute("target-features");
 
   std::string CPU =
   CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
+  std::string TuneCPU =
+  TuneAttr.isValid() ? TuneAttr.getValueAsString().str() : CPU;
   std::string FS =
   FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
 
@@ -399,6 +402,7 @@
   Key += "SVEMax";
   Key += std::to_string(MaxSVEVectorSize);
   Key += CPU;
+  Key += TuneCPU;
   Key += FS;
 
   auto &I = SubtargetMap[Key];
@@ -407,8 +411,8 @@
 // creation will depend on the TM and the code generation flags on the
 // function that reside in TargetOptions.
 resetTargetOptions(F);
-I = std::make_unique(TargetTriple, CPU, FS, *this,
-   isLittle, MinSVEVectorSize,
+I = std::make_unique(TargetTriple, CPU, TuneCPU, FS,
+   *this, isLittle, MinSVEVectorSize,
MaxSVEVectorSize);
   }
   return I.get();
Index: llvm/lib/Target/AArch64/AArch64Subtarget.h
===
--- llvm/lib/Target/AArch64/AArch64Subtarget.h
+++ llvm/lib/Target/AArch64/AArch64Subtarget.h
@@ -297,7 +297,8 @@
   /// passed in feature string so that we can use initializer lists for
   /// subtarget initialization.
   AArch64Subtarget &initializeSubtargetDependencies(StringRef FS,
-StringRef CPUString);
+StringRef CPUString,
+StringRef TuneCPUString);
 
   /// Initialize properties based on the selected processor family.
   void initializeProperties();
@@ -306,8 +307,8 @@
   /// This constructor initializes the data members to match that
   /// of the specified triple.
   AArch64Subtarget(const Triple &TT, const std::string &CPU,
-   const std::string &FS, const TargetMachine &TM,
-   bool LittleEndian,
+   const std::string &TuneCPU, const std::string &FS,
+   const TargetMachine &TM, bool LittleEndian,
unsigned MinSVEVectorSizeInBitsOverride = 0,
unsigned MaxSVEVectorSizeInBitsOverride = 0);
 
Index: llvm/lib/Target/AArch64/AArch64Subtarget.cpp
===
--- llvm/lib/Target/AArch64/AArch64Subtarget.cpp
+++ llvm/lib/Target/AArch64/AArch64Subtarget.cpp
@@ -50,15 +50,17 @@
 static cl::opt UseAA("aarch64-use-aa", cl::init(true),
cl::desc("Enable the use of AA during codegen."));
 
-AArch64Subtarget &
-AArch64Subtarget::initializeSubtargetDependencies(StringRe

[PATCH] D111909: [clang-tidy] DefinitionsInHeadersCheck: Added option for checking C Code

2021-10-18 Thread Whisperity via Phabricator via cfe-commits
whisperity added a comment.

It would be interesting to add a test for this. I've recently came across the 
fact that Clang doesn't support //common linkage// definitions, namely that in 
**C** (but not in C++), if you do the following:

  int I;
  void f1(void) {}



  int I;
  void f2(void) {}

and compile these two source files and link them together, the two `I`s will 
refer in the resulting binary to the same symbol. (You must not put an 
initialiser here!) Will `int I;` being in a header, with no initialiser, be 
caught?




Comment at: clang-tools-extra/clang-tidy/misc/DefinitionsInHeadersCheck.h:26
+///   - `CheckCCode`: Adds C99 to the minimum Language Requirements for this
+/// Checker. Disabled by default because this Checker wasn't build for C.
 ///   - `HeaderFileExtensions`: a semicolon-separated list of filename





Comment at: 
clang-tools-extra/docs/clang-tidy/checks/misc-definitions-in-headers.rst:109
+   When `true` C99 is added to the minimum language requirements for this 
+   Cecker. Default is `false` because this Checker was not build for C.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111909

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


[clang] c773f65 - [NFC] Remove Block-ABI-Apple.txt

2021-10-18 Thread Shivam Gupta via cfe-commits

Author: Shivam Gupta
Date: 2021-10-18T15:42:31+05:30
New Revision: c773f6501dba6975660ce16ab73e6d86a10e6b71

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

LOG: [NFC] Remove Block-ABI-Apple.txt

This file was rewritten in rst format in clang/docs/Block-ABI-Apple.rst

Added: 


Modified: 


Removed: 
clang/docs/Block-ABI-Apple.txt



diff  --git a/clang/docs/Block-ABI-Apple.txt b/clang/docs/Block-ABI-Apple.txt
deleted file mode 100644
index 1b04cc9e133c0..0
--- a/clang/docs/Block-ABI-Apple.txt
+++ /dev/null
@@ -1 +0,0 @@
-*NOTE* This document has moved to 
https://clang.llvm.org/docs/Block-ABI-Apple.html.



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


[PATCH] D111790: [AArch64][Driver][SVE] Allow -msve-vector-bits=+ syntax to mean no maximum vscale

2021-10-18 Thread Bradley Smith via Phabricator via cfe-commits
bsmith updated this revision to Diff 380330.
bsmith added a comment.

- Avoid side-effects in assertions


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111790

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/AST/ASTContext.cpp
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGen/aarch64-sve-acle-__ARM_FEATURE_SVE_VECTOR_OPERATORS.c
  clang/test/CodeGen/aarch64-sve-acle-__ARM_FEATURE_SVE_VECTOR_OPERATORS.cpp
  clang/test/CodeGen/aarch64-sve-vector-bits-codegen.c
  clang/test/CodeGen/arm-sve-vector-bits-vscale-range.c
  clang/test/CodeGen/attr-arm-sve-vector-bits-bitcast.c
  clang/test/CodeGen/attr-arm-sve-vector-bits-call.c
  clang/test/CodeGen/attr-arm-sve-vector-bits-cast.c
  clang/test/CodeGen/attr-arm-sve-vector-bits-codegen.c
  clang/test/CodeGen/attr-arm-sve-vector-bits-globals.c
  clang/test/CodeGen/attr-arm-sve-vector-bits-types.c
  clang/test/CodeGenCXX/aarch64-mangle-sve-fixed-vectors.cpp
  clang/test/CodeGenCXX/aarch64-sve-fixedtypeinfo.cpp
  clang/test/Driver/aarch64-sve-vector-bits.c
  clang/test/Sema/aarch64-sve-explicit-casts-fixed-size.c
  clang/test/Sema/aarch64-sve-lax-vector-conversions.c
  clang/test/Sema/attr-arm-sve-vector-bits.c
  clang/test/SemaCXX/aarch64-sve-explicit-casts-fixed-size.cpp
  clang/test/SemaCXX/aarch64-sve-lax-vector-conversions.cpp
  clang/test/SemaCXX/attr-arm-sve-vector-bits.cpp

Index: clang/test/SemaCXX/attr-arm-sve-vector-bits.cpp
===
--- clang/test/SemaCXX/attr-arm-sve-vector-bits.cpp
+++ clang/test/SemaCXX/attr-arm-sve-vector-bits.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -target-feature +bf16 -ffreestanding -fsyntax-only -verify -std=c++11 -msve-vector-bits=512 -fallow-half-arguments-and-returns -Wconversion %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -target-feature +bf16 -ffreestanding -fsyntax-only -verify -std=c++11 -mvscale-min=4 -mvscale-max=4 -fallow-half-arguments-and-returns -Wconversion %s
 // expected-no-diagnostics
 
 #include 
Index: clang/test/SemaCXX/aarch64-sve-lax-vector-conversions.cpp
===
--- clang/test/SemaCXX/aarch64-sve-lax-vector-conversions.cpp
+++ clang/test/SemaCXX/aarch64-sve-lax-vector-conversions.cpp
@@ -1,6 +1,6 @@
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -msve-vector-bits=512 -flax-vector-conversions=none -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify=lax-vector-none %s
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -msve-vector-bits=512 -flax-vector-conversions=integer -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify=lax-vector-integer %s
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -msve-vector-bits=512 -flax-vector-conversions=all -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify=lax-vector-all %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -mvscale-min=4 -mvscale-max=4 -flax-vector-conversions=none -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify=lax-vector-none %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -mvscale-min=4 -mvscale-max=4 -flax-vector-conversions=integer -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify=lax-vector-integer %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -mvscale-min=4 -mvscale-max=4 -flax-vector-conversions=all -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify=lax-vector-all %s
 
 #include 
 
Index: clang/test/SemaCXX/aarch64-sve-explicit-casts-fixed-size.cpp
===
--- clang/test/SemaCXX/aarch64-sve-explicit-casts-fixed-size.cpp
+++ clang/test/SemaCXX/aarch64-sve-explicit-casts-fixed-size.cpp
@@ -1,8 +1,8 @@
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -msve-vector-bits=128 -flax-vector-conversions=none -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify %s
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -msve-vector-bits=256 -flax-vector-conversions=none -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify %s
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -msve-vector-bits=512 -flax-vector-conversions=none -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify %s
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -msve-vector-bits=1024 -flax-vector-conversions=none -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify %s
-// RUN: %clang_cc1 -triple

[PATCH] D107347: [Sema] haveSameParameterTypes - fix repeated isNull() test

2021-10-18 Thread Nathan Sidwell via Phabricator via cfe-commits
urnathan added inline comments.



Comment at: clang/lib/Sema/SemaOverload.cpp:9528
 QualType T2 = NextParam(F2, I2, I == 0);
-if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, 
T2))
+if (!T1.isNull() && !T2.isNull() && !Context.hasSameUnqualifiedType(T1, 
T2))
   return false;

RKSimon wrote:
> @rsmith Can these isNull checks ever fail? Or would we be better off changing 
> them into an assert?
> ```
> QualType T1 = NextParam(F1, I1, I == 0);
> QualType T2 = NextParam(F2, I2, I == 0);
> assert(!T1.isNull() && !T2.isNull() && "Unknown types");
> if (!Context.hasSameUnqualifiedType(T1, T2))
> ```
that it's never ICED without checking T2's nullness suggests to me that they're 
never null.  A null type here would seem to be from bad parsing, in which case 
why are we even checking further?  IMHO assert now, there's plenty of time 
before C14 to revert that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107347

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


[PATCH] D108696: [Coroutines] [Frontend] Lookup in std namespace first

2021-10-18 Thread Adrian Vogelsgesang via Phabricator via cfe-commits
avogelsgesang added a comment.

Hi @ChuanqiXu

sorry for what might be naive questions, but just to make sure I understand the 
context of this patch correctly:

This patch fixes the look up of the `coroutine_traits`, so that clang now 
search both the `std` and the `std::experimental` namespace. As such, it must 
land before D109433  since otherwise the new 
`std::coroutine_traits` wouldn't be found by the compiler, correct?

Also, does this patch enable me to use `clang-cl` to build programs which use 
the coroutine header from Microsoft's STL 
? Or are there 
still other incompatibilities between clang and the Microsoft STL with regards 
to coroutines?


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

https://reviews.llvm.org/D108696

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


[PATCH] D108301: [MSP430][Clang] Update hard-coded MCU data

2021-10-18 Thread Jozef Lawrynowicz via Phabricator via cfe-commits
jozefl added a comment.

Ping.

Thanks,
Jozef


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108301

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


[PATCH] D109174: [MSP430][Clang] Infer CPU type from -mcpu= or -mmcu=

2021-10-18 Thread Jozef Lawrynowicz via Phabricator via cfe-commits
jozefl added a comment.

Ping.

Thanks,
Jozef


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109174

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


[PATCH] D108696: [Coroutines] [Frontend] Lookup in std namespace first

2021-10-18 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

In D108696#3069723 , @avogelsgesang 
wrote:

> Hi @ChuanqiXu
>
> sorry for what might be naive questions, but just to make sure I understand 
> the context of this patch correctly:

Hi, you are welcome : )

> This patch fixes the look up of the `coroutine_traits`, so that clang now 
> search both the `std` and the `std::experimental` namespace. As such, it must 
> land before D109433  since otherwise the 
> new `std::coroutine_traits` wouldn't be found by the compiler, correct?

Yes, correct.

> Also, does this patch enable me to use `clang-cl` to build programs which use 
> the coroutine header from Microsoft's STL 
> ? Or are there 
> still other incompatibilities between clang and the Microsoft STL with 
> regards to coroutines?

After this patch, it should be able to compile  MS STL. Otherwise, 
there must be a bug in either the clang part or in the MS STL part.


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

https://reviews.llvm.org/D108696

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


[PATCH] D111154: [WebAssembly] Implementation of table.get/set for reftypes in LLVM IR

2021-10-18 Thread Paulo Matos via Phabricator via cfe-commits
pmatos updated this revision to Diff 380337.
pmatos added a comment.

Use reference to pointer instead of pointer to pointer as @tlively suggested.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54

Files:
  clang/lib/Basic/Targets/WebAssembly.h
  clang/test/CodeGen/target-data.c
  lld/test/wasm/lto/Inputs/archive.ll
  lld/test/wasm/lto/Inputs/cache.ll
  lld/test/wasm/lto/Inputs/libcall-archive.ll
  lld/test/wasm/lto/Inputs/libcall-truncsfhf2.ll
  lld/test/wasm/lto/Inputs/save-temps.ll
  lld/test/wasm/lto/Inputs/thinlto.ll
  lld/test/wasm/lto/Inputs/used.ll
  lld/test/wasm/lto/archive.ll
  lld/test/wasm/lto/atomics.ll
  lld/test/wasm/lto/cache.ll
  lld/test/wasm/lto/comdat.ll
  lld/test/wasm/lto/diagnostics.ll
  lld/test/wasm/lto/export.ll
  lld/test/wasm/lto/import-attributes.ll
  lld/test/wasm/lto/internalize-basic.ll
  lld/test/wasm/lto/libcall-archive.ll
  lld/test/wasm/lto/libcall-truncsfhf2.ll
  lld/test/wasm/lto/lto-start.ll
  lld/test/wasm/lto/new-pass-manager.ll
  lld/test/wasm/lto/opt-level.ll
  lld/test/wasm/lto/parallel.ll
  lld/test/wasm/lto/relocatable-undefined.ll
  lld/test/wasm/lto/relocatable.ll
  lld/test/wasm/lto/save-temps.ll
  lld/test/wasm/lto/thinlto.ll
  lld/test/wasm/lto/tls.ll
  lld/test/wasm/lto/undef.ll
  lld/test/wasm/lto/used.ll
  lld/test/wasm/lto/verify-invalid.ll
  lld/test/wasm/lto/weak-undefined.ll
  lld/test/wasm/lto/weak.ll
  llvm/lib/Target/WebAssembly/WebAssemblyISD.def
  llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.h
  llvm/lib/Target/WebAssembly/WebAssemblyInstrTable.td
  llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyRegStackify.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
  llvm/test/CodeGen/WebAssembly/externref-tableget.ll
  llvm/test/CodeGen/WebAssembly/externref-tableset.ll
  llvm/test/CodeGen/WebAssembly/funcref-table_call.ll
  llvm/test/CodeGen/WebAssembly/funcref-tableget.ll
  llvm/test/CodeGen/WebAssembly/funcref-tableset.ll

Index: llvm/test/CodeGen/WebAssembly/funcref-tableset.ll
===
--- /dev/null
+++ llvm/test/CodeGen/WebAssembly/funcref-tableset.ll
@@ -0,0 +1,82 @@
+; RUN: llc --mtriple=wasm32-unknown-unknown -asm-verbose=false -mattr=+reference-types < %s | FileCheck %s
+
+%func = type void ()
+%funcref = type %func addrspace(20)* ;; addrspace 20 is nonintegral
+
+@funcref_table = local_unnamed_addr addrspace(1) global [0 x %funcref] undef
+
+define void @set_funcref_table(%funcref %g, i32 %i) {
+; CHECK-LABEL: set_funcref_table:
+; CHECK-NEXT: .functype   set_funcref_table (funcref, i32) -> ()
+; CHECK-NEXT: local.get  1
+; CHECK-NEXT: local.get  0
+; CHECK-NEXT: table.set funcref_table
+; CHECK-NEXT: end_function
+
+;; this generates a table.set of @funcref_table
+  %p = getelementptr [0 x %funcref], [0 x %funcref] addrspace (1)* @funcref_table, i32 0, i32 %i
+  store %funcref %g, %funcref addrspace(1)* %p
+  ret void
+}
+
+define void @set_funcref_table_const(%funcref %g) {
+; CHECK-LABEL: set_funcref_table_const:
+; CHECK-NEXT:  .functype  set_funcref_table_const (funcref) -> ()
+; CHECK-NEXT:  i32.const  0
+; CHECK-NEXT:  local.get  0
+; CHECK-NEXT:  table.set  funcref_table
+; CHECK-NEXT:  end_function
+  %p = getelementptr [0 x %funcref], [0 x %funcref] addrspace (1)* @funcref_table, i32 0, i32 0
+  store %funcref %g, %funcref addrspace(1)* %p
+  ret void
+}
+
+define void @set_funcref_table_with_offset(%funcref %g, i32 %i) {
+; CHECK-LABEL: set_funcref_table_with_offset:
+; CHECK-NEXT:  .functype   set_funcref_table_with_offset (funcref, i32) -> ()
+; CHECK-NEXT:  local.get   1
+; CHECK-NEXT:  i32.const   2
+; CHECK-NEXT:  i32.add
+; CHECK-NEXT:  local.get   0
+; CHECK-NEXT:  table.set   funcref_table
+; CHECK-NEXT:  end_function
+  %off = add nsw i32 %i, 2
+  %p = getelementptr [0 x %funcref], [0 x %funcref] addrspace (1)* @funcref_table, i32 0, i32 %off
+  store %funcref %g, %funcref addrspace(1)* %p
+  ret void
+}
+
+define void @set_funcref_table_with_var_offset(%funcref %g, i32 %i, i32 %j) {
+; CHECK-LABEL: set_funcref_table_with_var_offset:
+; CHECK-NEXT:  .functype   set_funcref_table_with_var_offset (funcref, i32, i32) -> ()
+; CHECK-NEXT:  local.get   1
+; CHECK-NEXT:  local.get   2
+; CHECK-NEXT:  i32.add
+; CHECK-NEXT:  local.get   0
+; CHECK-NEXT:  table.set   funcref_table
+; CHECK-NEXT:  end_function
+  %off = add nsw i32 %i, %j
+  %p = getelementptr [0 x %funcref], [0 x %funcref] addrspace (1)* @funcref_table, i32 0, i32 %off
+  store %funcref %g, %funcref addrspace(1)* %p
+  ret void
+}
+
+declare i32 @set_offset()
+
+define void @set_funcref_table_with_var_offset2(%funcref %g, i32 %i) {
+; CHECK-LABEL: set_funcref_table_with_var_offset2:
+; CHECK-NEXT:  .functype   set_

[PATCH] D107347: [Sema] haveSameParameterTypes - fix repeated isNull() test

2021-10-18 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added inline comments.



Comment at: clang/lib/Sema/SemaOverload.cpp:9528
 QualType T2 = NextParam(F2, I2, I == 0);
-if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, 
T2))
+if (!T1.isNull() && !T2.isNull() && !Context.hasSameUnqualifiedType(T1, 
T2))
   return false;

urnathan wrote:
> RKSimon wrote:
> > @rsmith Can these isNull checks ever fail? Or would we be better off 
> > changing them into an assert?
> > ```
> > QualType T1 = NextParam(F1, I1, I == 0);
> > QualType T2 = NextParam(F2, I2, I == 0);
> > assert(!T1.isNull() && !T2.isNull() && "Unknown types");
> > if (!Context.hasSameUnqualifiedType(T1, T2))
> > ```
> that it's never ICED without checking T2's nullness suggests to me that 
> they're never null.  A null type here would seem to be from bad parsing, in 
> which case why are we even checking further?  IMHO assert now, there's plenty 
> of time before C14 to revert that.
OK - I'll change this to an assertion


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107347

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


[PATCH] D107347: [Sema] haveSameParameterTypes - replace repeated isNull() test with assertions

2021-10-18 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon updated this revision to Diff 380338.
RKSimon retitled this revision from "[Sema] haveSameParameterTypes - fix 
repeated isNull() test" to "[Sema] haveSameParameterTypes - replace repeated 
isNull() test with assertions".
RKSimon edited the summary of this revision.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107347

Files:
  clang/lib/Sema/SemaOverload.cpp


Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -9586,7 +9586,8 @@
   for (unsigned I = 0; I != NumParams; ++I) {
 QualType T1 = NextParam(F1, I1, I == 0);
 QualType T2 = NextParam(F2, I2, I == 0);
-if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, 
T2))
+assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
+if (!Context.hasSameUnqualifiedType(T1, T2))
   return false;
   }
   return true;


Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -9586,7 +9586,8 @@
   for (unsigned I = 0; I != NumParams; ++I) {
 QualType T1 = NextParam(F1, I1, I == 0);
 QualType T2 = NextParam(F2, I2, I == 0);
-if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2))
+assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
+if (!Context.hasSameUnqualifiedType(T1, T2))
   return false;
   }
   return true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 3b3509b - [Sema] haveSameParameterTypes - replace repeated isNull() test with assertions

2021-10-18 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2021-10-18T12:36:44+01:00
New Revision: 3b3509b3cba272c98d2235a8664ae9625ac729f8

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

LOG: [Sema] haveSameParameterTypes - replace repeated isNull() test with 
assertions

As reported on https://pvs-studio.com/en/blog/posts/cpp/0771/ (Snippet 2) - 
(and mentioned on rGdc4259d5a38409) we are repeating the T1.isNull() check 
instead of checking T2.isNull() as well, and at this point neither should be 
null - so we're better off with an assertion.

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

Added: 


Modified: 
clang/lib/Sema/SemaOverload.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index d93fd9df0093e..a2af2ac6f7ee8 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -9586,7 +9586,8 @@ static bool haveSameParameterTypes(ASTContext &Context, 
const FunctionDecl *F1,
   for (unsigned I = 0; I != NumParams; ++I) {
 QualType T1 = NextParam(F1, I1, I == 0);
 QualType T2 = NextParam(F2, I2, I == 0);
-if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, 
T2))
+assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
+if (!Context.hasSameUnqualifiedType(T1, T2))
   return false;
   }
   return true;



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


[PATCH] D107347: [Sema] haveSameParameterTypes - replace repeated isNull() test with assertions

2021-10-18 Thread Simon Pilgrim via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3b3509b3cba2: [Sema] haveSameParameterTypes - replace 
repeated isNull() test with assertions (authored by RKSimon).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107347

Files:
  clang/lib/Sema/SemaOverload.cpp


Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -9586,7 +9586,8 @@
   for (unsigned I = 0; I != NumParams; ++I) {
 QualType T1 = NextParam(F1, I1, I == 0);
 QualType T2 = NextParam(F2, I2, I == 0);
-if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, 
T2))
+assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
+if (!Context.hasSameUnqualifiedType(T1, T2))
   return false;
   }
   return true;


Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -9586,7 +9586,8 @@
   for (unsigned I = 0; I != NumParams; ++I) {
 QualType T1 = NextParam(F1, I1, I == 0);
 QualType T2 = NextParam(F2, I2, I == 0);
-if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2))
+assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
+if (!Context.hasSameUnqualifiedType(T1, T2))
   return false;
   }
   return true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D111971: [clang] Allocate 2 bits to store the constexpr specifier kind when serializing

2021-10-18 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz accepted this revision.
adamcz added a comment.
This revision is now accepted and ready to land.

Fix LGTM

As for the test, I suggest putting it in clang/test/AST/, maybe in 
ast-dump-constant-expr? You can write a CHECK-NEXT: thingy to verify that 
consteval is preserved. The test already runs both with and without AST 
reader/writer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111971

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


[PATCH] D111985: [Clang] Add elementwise min/max builtins.

2021-10-18 Thread Florian Hahn via Phabricator via cfe-commits
fhahn created this revision.
fhahn added reviewers: aaron.ballman, scanon, craig.topper, rjmccall, 
erichkeane.
fhahn requested review of this revision.
Herald added a project: clang.

This patch implements __builtin_elementwise_max and
__builtin_elementwise_min, as specified in D111529 
.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D111985

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-elementwise-math.c
  clang/test/Sema/builtins-elementwise-math.c

Index: clang/test/Sema/builtins-elementwise-math.c
===
--- /dev/null
+++ clang/test/Sema/builtins-elementwise-math.c
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 %s -pedantic -verify -triple=x86_64-apple-darwin9
+
+typedef float float4 __attribute__((ext_vector_type(4)));
+typedef int int3 __attribute__((ext_vector_type(3)));
+
+struct Foo {
+  char *p;
+};
+
+void builtin_elementwise_max(int i, double d, float4 v, int3 iv) {
+  i = __builtin_elementwise_max(i, d);
+  // expected-error@-1 {{argument types do not match, 'int' != 'double'}}
+
+  struct Foo s = __builtin_elementwise_max(i, i);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_elementwise_max(i);
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 1}}
+
+  i = __builtin_elementwise_max();
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 0}}
+
+  i = __builtin_elementwise_max(v, iv);
+  // expected-error@-1 {{argument types do not match, 'float4' (vector of 4 'float' values) != 'int3' (vector of 3 'int' values)}}
+}
+
+void builtin_elementwise_min(int i, double d, float4 v, int3 iv) {
+  i = __builtin_elementwise_min(i, d);
+  // expected-error@-1 {{argument types do not match, 'int' != 'double'}}
+
+  struct Foo s = __builtin_elementwise_min(i, i);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_elementwise_min(i);
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 1}}
+
+  i = __builtin_elementwise_min();
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 0}}
+
+  i = __builtin_elementwise_min(v, iv);
+  // expected-error@-1 {{argument types do not match, 'float4' (vector of 4 'float' values) != 'int3' (vector of 3 'int' values)}}
+}
Index: clang/test/CodeGen/builtins-elementwise-math.c
===
--- /dev/null
+++ clang/test/CodeGen/builtins-elementwise-math.c
@@ -0,0 +1,85 @@
+// RUN: %clang_cc1 -disable-noundef-analysis -triple x86_64-apple-darwin %s -emit-llvm -disable-llvm-passes -o - | FileCheck %s
+
+typedef float float4 __attribute__((ext_vector_type(4)));
+typedef short int si8 __attribute__((ext_vector_type(8)));
+typedef unsigned int u4 __attribute__((ext_vector_type(4)));
+
+void builtin_max(float f1, float f2, double d1, double d2, float4 vf1,
+ float4 vf2, long long int i1, long long int i2, si8 vi1,
+ si8 vi2, unsigned u1, unsigned u2, u4 vu1, u4 vu2) {
+  // CHECK-LABEL: define void @builtin_max(
+  // CHECK:  [[F1:%.+]] = load float, float* %f1.addr, align 4
+  // CHECK-NEXT: [[F2:%.+]] = load float, float* %f2.addr, align 4
+  // CHECK-NEXT:  call float @llvm.maxnum.f32(float %0, float %1)
+  f1 = __builtin_elementwise_max(f1, f2);
+
+  // CHECK:  [[D1:%.+]] = load double, double* %d1.addr, align 8
+  // CHECK-NEXT: [[D2:%.+]] = load double, double* %d2.addr, align 8
+  // CHECK-NEXT: call double @llvm.maxnum.f64(double [[D1]], double [[D2]])
+  d1 = __builtin_elementwise_max(d1, d2);
+
+  // CHECK:  [[VF1:%.+]] = load <4 x float>, <4 x float>* %vf1.addr, align 16
+  // CHECK-NEXT: [[VF2:%.+]] = load <4 x float>, <4 x float>* %vf2.addr, align 16
+  // CHECK-NEXT: call <4 x float> @llvm.maxnum.v4f32(<4 x float> [[VF1]], <4 x float> [[VF2]])
+  vf1 = __builtin_elementwise_max(vf1, vf2);
+
+  // CHECK:  [[I1:%.+]] = load i64, i64* %i1.addr, align 8
+  // CHECK-NEXT: [[I2:%.+]] = load i64, i64* %i2.addr, align 8
+  // CHECK-NEXT: call i64 @llvm.smax.i64(i64 [[I1]], i64 [[I2]])
+  i1 = __builtin_elementwise_max(i1, i2);
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: [[VI2:%.+]] = load <8 x i16>, <8 x i16>* %vi2.addr, align 16
+  // CHECK-NEXT: call <8 x i16> @llvm.smax.v8i16(<8 x i16> [[VI1]], <8 x i16> [[VI2]])
+  vi1 = __builtin_elementwise_max(vi1, vi2);
+
+  // CHECK:  [[U1:%.+]] = load i32, i32* %u1.addr, align 4
+  // CHECK-NEXT: [[U2:%.+]] = load i32, i32* %u2.addr, align 4
+  // CHECK-NEXT: call i32 @llvm.umax.i32(i32 [[U1]], i32 [[U2]])
+  u1 = __builtin_elementwise_max(u1, u2

[PATCH] D111986: [Clang] Add elementwise abs builtin.

2021-10-18 Thread Florian Hahn via Phabricator via cfe-commits
fhahn created this revision.
fhahn added reviewers: aaron.ballman, scanon, craig.topper, rjmccall, 
erichkeane.
Herald added a subscriber: mstorsjo.
fhahn requested review of this revision.
Herald added a project: clang.

This patch implements __builtin_elementwise_abs as specified in
D111529 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D111986

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-elementwise-math.c
  clang/test/Sema/builtins-elementwise-math.c

Index: clang/test/Sema/builtins-elementwise-math.c
===
--- clang/test/Sema/builtins-elementwise-math.c
+++ clang/test/Sema/builtins-elementwise-math.c
@@ -2,11 +2,32 @@
 
 typedef float float4 __attribute__((ext_vector_type(4)));
 typedef int int3 __attribute__((ext_vector_type(3)));
+typedef unsigned unsigned4 __attribute__((ext_vector_type(4)));
 
 struct Foo {
   char *p;
 };
 
+void builtin_elementwise_abs(int i, double d, float4 v, int3 iv, unsigned u, unsigned4 uv) {
+  struct Foo s = __builtin_elementwise_abs(i);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_elementwise_abs();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_elementwise_abs(i, i);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_elementwise_abs(v);
+  // expected-error@-1 {{assigning to 'int' from incompatible type 'float4' (vector of 4 'float' values)}}
+
+  u = __builtin_elementwise_abs(u);
+  // expected-error@-1 {{argument must have a signed integer or floating point type, but had a unsigned integer type}}
+
+  uv = __builtin_elementwise_abs(uv);
+  // expected-error@-1 {{argument must have a signed integer or floating point type, but had a unsigned integer type}}
+}
+
 void builtin_elementwise_max(int i, double d, float4 v, int3 iv) {
   i = __builtin_elementwise_max(i, d);
   // expected-error@-1 {{argument types do not match, 'int' != 'double'}}
Index: clang/test/CodeGen/builtins-elementwise-math.c
===
--- clang/test/CodeGen/builtins-elementwise-math.c
+++ clang/test/CodeGen/builtins-elementwise-math.c
@@ -4,10 +4,34 @@
 typedef short int si8 __attribute__((ext_vector_type(8)));
 typedef unsigned int u4 __attribute__((ext_vector_type(4)));
 
+void builtin_abs(float f1, float f2, double d1, double d2, float4 vf1, float4 vf2, si8 vi1, si8 vi2, long long int i1, long long int i2) {
+  // CHECK-LABEL: builtin_abs(
+  // CHECK:  [[F1:%.+]] = load float, float* %f1.addr, align 4
+  // CHECK-NEXT:  call float @llvm.fabs.f32(float [[F1]])
+  f2 = __builtin_elementwise_abs(f1);
+
+  // CHECK:  [[D1:%.+]] = load double, double* %d1.addr, align 8
+  // CHECK-NEXT: call double @llvm.fabs.f64(double [[D1]])
+  d2 = __builtin_elementwise_abs(d1);
+
+  // CHECK:  [[VF1:%.+]] = load <4 x float>, <4 x float>* %vf1.addr, align 16
+  // CHECK-NEXT: call <4 x float> @llvm.fabs.v4f32(<4 x float> [[VF1]])
+  vf2 = __builtin_elementwise_abs(vf1);
+
+  // CHECK:  [[I1:%.+]] = load i64, i64* %i1.addr, align 8
+  // CHECK-NEXT: call i64 @llvm.abs.i64(i64 [[I1]], i1 false)
+  i2 = __builtin_elementwise_abs(i1);
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call <8 x i16> @llvm.abs.v8i16(<8 x i16> [[VI1]], i1 false)
+  vi2 = __builtin_elementwise_abs(vi1);
+}
+
 void builtin_max(float f1, float f2, double d1, double d2, float4 vf1,
  float4 vf2, long long int i1, long long int i2, si8 vi1,
  si8 vi2, unsigned u1, unsigned u2, u4 vu1, u4 vu2) {
   // CHECK-LABEL: define void @builtin_max(
+
   // CHECK:  [[F1:%.+]] = load float, float* %f1.addr, align 4
   // CHECK-NEXT: [[F2:%.+]] = load float, float* %f2.addr, align 4
   // CHECK-NEXT:  call float @llvm.maxnum.f32(float %0, float %1)
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -1976,9 +1976,12 @@
 break;
   }
 
+  case Builtin::BI__builtin_elementwise_abs:
+return SemaBuiltinElementwiseMathOneArg(TheCall, TheCallResult);
+
   case Builtin::BI__builtin_elementwise_min:
   case Builtin::BI__builtin_elementwise_max:
-return SemaBuiltinElementwiseMath(TheCall, TheCallResult);
+return SemaBuiltinElementwiseMathTwoArgs(TheCall, TheCallResult);
 
   case Builtin::BI__builtin_matrix_transpose:
 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
@@ -16653,8 +16656,32 @@
  _2, _3, _4));
 }
 
-ExprResult Sema::SemaBuiltinElementwiseMath(

[PATCH] D99797: [analyzer] Implemented RangeSet::Factory::unite function to handle intersections and adjacency

2021-10-18 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

In D99797#3059203 , @steakhal wrote:

> PS: the test coverage is outstanding!

Thank you for this analysis.




Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:149
+
+RangeSet RangeSet::Factory::unite(RangeSet Original, llvm::APSInt Point) {
+  return unite(Original, Range(ValueFactory.getValue(Point)));

steakhal wrote:
> Why do you take `APSInt`s by value? Generally, we take them by reference.
I want to send a message to the caller that he can pass an arbitrary **APSInt** 
without warrying about making it permanent (aka stored by the Factory). But we 
can revise this contract and carry this responsibility to a caller.



Comment at: clang/unittests/StaticAnalyzer/RangeSetTest.cpp:81
   const llvm::APSInt &from(BaseType X) {
-llvm::APSInt Dummy = Base;
-Dummy = X;
-return BVF.getValue(Dummy);
+static llvm::APSInt Base{sizeof(BaseType) * 8,
+ std::is_unsigned::value};

steakhal wrote:
> Shouldn't you use `sizeof(BaseType) * CHAR_BIT` instead?
Agree. It's better to avoid magic numbers. I'll fix.


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

https://reviews.llvm.org/D99797

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


[PATCH] D109372: [RISCV][RFC] Add Clang support for RISC-V overlay system

2021-10-18 Thread Edward Jones via Phabricator via cfe-commits
edward-jones updated this revision to Diff 380347.

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

https://reviews.llvm.org/D109372

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Driver/ToolChains/Arch/RISCV.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/riscv-overlay.c
  clang/test/Driver/riscv-overlay.c
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/Sema/riscv-overlay-attr.c
  clang/test/Sema/riscv-overlay-namespace.cpp

Index: clang/test/Sema/riscv-overlay-namespace.cpp
===
--- /dev/null
+++ clang/test/Sema/riscv-overlay-namespace.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 %s -triple riscv32-unknown-elf -verify -fsyntax-only -moverlay
+// RUN: %clang_cc1 %s -triple riscv64-unknown-elf -verify -fsyntax-only -moverlay
+
+namespace {
+class foo {
+public:
+  static int X() __attribute__((overlaycall)) { return 0; } // expected-error {{functions marked with 'overlaycall' attribute must have external linkage}}
+};
+} // end of anonymous namespace
+
+namespace X {
+class bar {
+public:
+  static int X() __attribute__((overlaycall)) { return 1; }
+};
+} // end of namespace X
+
+extern "C" {
+int main(void) { return foo::X() + X::bar::X(); }
+}
Index: clang/test/Sema/riscv-overlay-attr.c
===
--- /dev/null
+++ clang/test/Sema/riscv-overlay-attr.c
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple riscv32 -moverlay -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple riscv64 -moverlay -fsyntax-only -verify %s
+
+int notAFunction __attribute__((overlaycall));
+// expected-warning@-1 {{'overlaycall' attribute only applies to functions}}
+
+void incompatForwardDecl(int x);
+void __attribute__((overlaycall)) incompatForwardDecl(int x) {}
+// expected-error@-1 {{redeclaration of 'incompatForwardDecl' must not have the 'overlaycall' attribute}}
+// expected-note@-3 {{previous definition is here}}
+
+static void staticcall() __attribute__((overlaycall)) {}
+// expected-error@-1 {{functions marked with 'overlaycall' attribute must have external linkage}}
+
+static void __attribute__((overlaycall)) staticcall2() {}
+// expected-error@-1 {{functions marked with 'overlaycall' attribute must have external linkage}}
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -147,6 +147,7 @@
 // CHECK-NEXT: PassObjectSize (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: PatchableFunctionEntry (SubjectMatchRule_function, SubjectMatchRule_objc_method)
 // CHECK-NEXT: Pointer (SubjectMatchRule_record_not_is_union)
+// CHECK-NEXT: RISCVOverlayCall (SubjectMatchRule_function)
 // CHECK-NEXT: ReleaseHandle (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: RenderScriptKernel (SubjectMatchRule_function)
 // CHECK-NEXT: ReqdWorkGroupSize (SubjectMatchRule_function)
Index: clang/test/Driver/riscv-overlay.c
===
--- /dev/null
+++ clang/test/Driver/riscv-overlay.c
@@ -0,0 +1,5 @@
+// Check that ComRV Driver Arguments
+
+// RUN: not %clang -target riscv32 -moverlay %s -o %t.o -mabi=ilp32f 2>&1 \
+// RUN:   | FileCheck -check-prefix=INVALID-ABI %s
+// INVALID-ABI: invalid ABI 'ilp32f' when using '-moverlay'
Index: clang/test/CodeGen/riscv-overlay.c
===
--- /dev/null
+++ clang/test/CodeGen/riscv-overlay.c
@@ -0,0 +1,11 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --check-attributes
+// RUN: %clang_cc1 -triple riscv32 -moverlay -emit-llvm %s -o - \
+// RUN:| FileCheck %s
+
+// CHECK-LABEL: @test_overlay_func(
+// CHECK-SAME: #0
+// CHECK: attributes #0 = {
+// CHECK-SAME: "overlay"
+int __attribute__((overlaycall)) test_overlay_func(void) {
+  return 5;
+}
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -2039,6 +2039,33 @@
   D->addAttr(::new (S.Context) CmseNSEntryAttr(S.Context, AL));
 }
 
+static void handleRISCVOverlayAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
+  if (!S.getLangOpts().Overlay) {
+S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored_overlay)
+<< AL;
+return;
+  }
+
+  if (isFunctionOrMethod(D)) {
+const aut

[PATCH] D111529: Specify Clang vector builtins.

2021-10-18 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 380351.
fhahn marked an inline comment as done.
fhahn added a comment.

Thanks for the latest set of comments!

I tried to incorporate the suggestions about improving the reduction wording. I 
also added an example.

I also put up 2 patches to start with the implementation of min/max and the abs 
builtins in D111985  and D111986 
. I adjusted the supported types for 
`__builtin_elementwise_abs` to *signed* integer and floating point types.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111529

Files:
  clang/docs/LanguageExtensions.rst


Index: clang/docs/LanguageExtensions.rst
===
--- clang/docs/LanguageExtensions.rst
+++ clang/docs/LanguageExtensions.rst
@@ -506,6 +506,82 @@
   If it's an extension (OpenCL) vector, it's only available in C and OpenCL C.
   And it selects base on signedness of the condition operands (OpenCL v1.1 
s6.3.9).
 
+Vector Builtins
+---
+
+**Note: The implementation of vector builtins is work-in-progress and 
incomplete.**
+
+In addition to the operators mentioned above, Clang provides a set of builtins
+to perform additional operations on certain scalar and vector types.
+
+Let ``T`` be one of the following types:
+
+* an integer type (as in C2x 6.2.5p19), but excluding enumerated types and 
_Bool
+* the standard floating types float or double
+* a half-precision floating point type, if one is supported on the target
+* a vector type.
+
+For scalar types, consider the operation applied to a vector with a single 
element.
+
+*Elementwise Builtins*
+
+Each builtin returns a vector equivalent to applying the specified operation
+elementwise to the input.
+
+Unless specified otherwise operation(±0) = ±0 and operation(±infinity) = 
±infinity
+
+= 
 
=
+ Name  Operation   
 Supported element types
+= 
 
=
+ T __builtin_elementwise_abs(T x)  return the absolute value of a 
number x   signed integer and floating point types
+ T __builtin_elementwise_ceil(T x) return the smallest integral value 
greater than or equal to x floating point types
+ T __builtin_elementwise_floor(T x)return the largest integral value 
less than or equal to x floating point types
+ T __builtin_elementwise_roundeven(T x)round x to the nearest integer 
value in floating point format,floating point types
+   rounding halfway cases to even 
(that is, to the nearest value
+   that is an even integer), 
regardless of the current rounding
+   direction.
+ T__builtin_elementwise_trunc(T x) return the integral value nearest 
to but no larger in floating point types
+   magnitude than x
+ T __builtin_elementwise_max(T x, T y) return x or y, whichever is larger  
  integer and floating point types
+ T __builtin_elementwise_min(T x, T y) return x or y, whichever is smaller 
  integer and floating point types
+= 
 
=
+
+
+*Reduction Builtins*
+
+Each builtin returns a scalar equivalent to applying the specified
+operation(x, y) as recursive even-odd pairwise reduction to all vector
+elements. ``operation(x, y)`` is repeatedly applied to each non-overlapping
+even-odd element pair with indices ``i * 2`` and ``i * 2 + 1`` with
+``i in [0, Number of elements / 2)``. If the numbers of elements is not a
+multiple of 2, the vector is padded with a neutral element for the reduction
+operation at the end.
+
+Example:
+
+.. code-block:: c++
+
+__builtin_reduce_fadd([e3, e2, e1, e0]) = __builtin_reduced_fadd([e3 + e2, 
e1 + e0])
+= (e3 + e2) + (e1 + e0)
+
+
+Let ``VT`` be a vector type and ``ET`` the element type of ``VT``.
+
+=== 
 
==
+ NameOperation 
   Supported element types
+=== 
 
===

[PATCH] D110258: [AArch64] Always add -tune-cpu argument to -cc1 driver

2021-10-18 Thread Dave Green via Phabricator via cfe-commits
dmgreen added a comment.

There are clang release notes that could also do with a line or two, after all 
the -mtune flag being a clang flag. The X86 notes for reference were added in 
https://releases.llvm.org/12.0.0/docs/ReleaseNotes.html and 
https://releases.llvm.org/12.0.0/tools/clang/docs/ReleaseNotes.html, from the 
look of it. I like "no longer ignored", but don't really have a strong opinion 
on the exact wording.


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

https://reviews.llvm.org/D110258

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


[PATCH] D111529: Specify Clang vector builtins.

2021-10-18 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 380352.
fhahn marked an inline comment as done.
fhahn added a comment.

adjust padding wording.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111529

Files:
  clang/docs/LanguageExtensions.rst


Index: clang/docs/LanguageExtensions.rst
===
--- clang/docs/LanguageExtensions.rst
+++ clang/docs/LanguageExtensions.rst
@@ -506,6 +506,82 @@
   If it's an extension (OpenCL) vector, it's only available in C and OpenCL C.
   And it selects base on signedness of the condition operands (OpenCL v1.1 
s6.3.9).
 
+Vector Builtins
+---
+
+**Note: The implementation of vector builtins is work-in-progress and 
incomplete.**
+
+In addition to the operators mentioned above, Clang provides a set of builtins
+to perform additional operations on certain scalar and vector types.
+
+Let ``T`` be one of the following types:
+
+* an integer type (as in C2x 6.2.5p19), but excluding enumerated types and 
_Bool
+* the standard floating types float or double
+* a half-precision floating point type, if one is supported on the target
+* a vector type.
+
+For scalar types, consider the operation applied to a vector with a single 
element.
+
+*Elementwise Builtins*
+
+Each builtin returns a vector equivalent to applying the specified operation
+elementwise to the input.
+
+Unless specified otherwise operation(±0) = ±0 and operation(±infinity) = 
±infinity
+
+= 
 
=
+ Name  Operation   
 Supported element types
+= 
 
=
+ T __builtin_elementwise_abs(T x)  return the absolute value of a 
number x   signed integer and floating point types
+ T __builtin_elementwise_ceil(T x) return the smallest integral value 
greater than or equal to x floating point types
+ T __builtin_elementwise_floor(T x)return the largest integral value 
less than or equal to x floating point types
+ T __builtin_elementwise_roundeven(T x)round x to the nearest integer 
value in floating point format,floating point types
+   rounding halfway cases to even 
(that is, to the nearest value
+   that is an even integer), 
regardless of the current rounding
+   direction.
+ T__builtin_elementwise_trunc(T x) return the integral value nearest 
to but no larger in floating point types
+   magnitude than x
+ T __builtin_elementwise_max(T x, T y) return x or y, whichever is larger  
  integer and floating point types
+ T __builtin_elementwise_min(T x, T y) return x or y, whichever is smaller 
  integer and floating point types
+= 
 
=
+
+
+*Reduction Builtins*
+
+Each builtin returns a scalar equivalent to applying the specified
+operation(x, y) as recursive even-odd pairwise reduction to all vector
+elements. ``operation(x, y)`` is repeatedly applied to each non-overlapping
+even-odd element pair with indices ``i * 2`` and ``i * 2 + 1`` with
+``i in [0, Number of elements / 2)``. If the numbers of elements is not a
+power of 2, the vector is widening with neutral elements for the reduction
+at the end to the next power of 2.
+
+Example:
+
+.. code-block:: c++
+
+__builtin_reduce_fadd([e3, e2, e1, e0]) = __builtin_reduced_fadd([e3 + e2, 
e1 + e0])
+= (e3 + e2) + (e1 + e0)
+
+
+Let ``VT`` be a vector type and ``ET`` the element type of ``VT``.
+
+=== 
 
==
+ NameOperation 
   Supported element types
+=== 
 
==
+ ET __builtin_reduce_max(VT a)   return x or y, whichever is larger; 
If exactly one argument is   integer and floating point types
+ a NaN, return the other argument. If 
both arguments are NaNs,
+ fmax() return a NaN.
+ ET __builtin_reduce_min(VT a)   return x or y, whichever i

[PATCH] D111529: Specify Clang vector builtins.

2021-10-18 Thread Florian Hahn via Phabricator via cfe-commits
fhahn marked 2 inline comments as done.
fhahn added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:553
+Each builtin returns a scalar equivalent to applying the specified
+operation(x, y) as horizontal recursive pairwise reduction to all vector
+elements. In each reduction step, ``operation(x, y)`` is applied to adjacent

kparzysz wrote:
> It's really not clear what "horizontal recursive pairwise" means unless one 
> has read the mailing list discussions.  Maybe you could spell it out, e.g. 
> "recursive even-odd pairwise reduction" or something like that.
Thanks, I used that wording!



Comment at: clang/docs/LanguageExtensions.rst:552
+operation(x, y) as pairwise tree reduction to the input. The pairs are formed
+by concatenating both inputs and pairing adjacent elements.
+

craig.topper wrote:
> fhahn wrote:
> > craig.topper wrote:
> > > scanon wrote:
> > > > fhahn wrote:
> > > > > craig.topper wrote:
> > > > > > I'm not sure I understand what is being concatenated here.
> > > > > I tried to spell it out more clearly. I'm still not sure if that 
> > > > > spells it out as clearly as possibly and I'd appreciate any 
> > > > > suggestions on how to improve the wording.
> > > > It's unclear because there's no apparent "first" or "second" vector; 
> > > > there's just a single argument, and the result isn't a vector, it's a 
> > > > scalar. I think you want to say something like: "the operation is 
> > > > repeatedly applied to adjacent pairs of elements until the result is a 
> > > > scalar" and then provide a worked example.
> > > The input is a single vector. I'm not understanding where we get a second 
> > > vector to concatenate.
> > Oh yes, now I see where the confusion was coming from. I was thinking about 
> > the reduction tree and how the input is broken up. Sorry for the confusing 
> > wording. I gave it another try, should be much simpler again now.
> Should it somehow mention the pair is the even element `i` and the odd 
> element `i+1`. There are n-1 adjacent pairs in an n element vector, but we 
> want non-overlapping pairs.
> 
> Should probably spell out the non-power2 behavior. Presumably we pad identity 
> elements after the last element to widen the vector out to a power 2 and then 
> proceed normally?
> Should it somehow mention the pair is the even element i and the odd element 
> i+1. There are n-1 adjacent pairs in an n element vector, but we want 
> non-overlapping pairs.

Thanks, I tried to update the wording to make it clear that it operates on 
even-odd non-overlapping pairs.


> Should probably spell out the non-power2 behavior. Presumably we pad identity 
> elements after the last element to widen the vector out to a power 2 and then 
> proceed normally?

Good point, done!

>  I think you want to say something like: "the operation is repeatedly applied 
> to adjacent pairs of elements until the result is a scalar" and then provide 
> a worked example.

Used and added an example.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111529

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


[PATCH] D107450: [clang-tidy] Fix wrong FixIt in performance-move-const-arg

2021-10-18 Thread gehry via Phabricator via cfe-commits
Sockke added a comment.

Hi, Could anyone please review this diff? @whisperity, @aaron.ballman


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

https://reviews.llvm.org/D107450

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


[clang] cbf778a - Remove also Block-ABI-Apple.txt from the Makefile

2021-10-18 Thread Sylvestre Ledru via cfe-commits

Author: Sylvestre Ledru
Date: 2021-10-18T14:56:23+02:00
New Revision: cbf778a592fa5ee7c2bdd3d3ee7b468da2a7c9e6

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

LOG: Remove also Block-ABI-Apple.txt from the Makefile

Added: 


Modified: 
clang/docs/Makefile.sphinx

Removed: 




diff  --git a/clang/docs/Makefile.sphinx b/clang/docs/Makefile.sphinx
index 7949e39c3687..06c3b86819d0 100644
--- a/clang/docs/Makefile.sphinx
+++ b/clang/docs/Makefile.sphinx
@@ -50,10 +50,6 @@ html:
@# Kind of a hack, but HTML-formatted docs are on the way out anyway.
@echo "Copying legacy HTML-formatted docs into $(BUILDDIR)/html"
@cp -a *.html $(BUILDDIR)/html
-   @# FIXME: What we really need is a way to specify redirects, so that
-   @# we can just redirect to a reST'ified version of this document.
-   @# PR14714 is tracking the issue of redirects.
-   @cp -a Block-ABI-Apple.txt $(BUILDDIR)/html
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
 
 dirhtml:



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


[clang] 5644d15 - [analyzer][NFC] Add unittests for CallDescription and split the old ones

2021-10-18 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-10-18T14:57:24+02:00
New Revision: 5644d152578f4604f7dc8c908a0a3f91a726ad80

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

LOG: [analyzer][NFC] Add unittests for CallDescription and split the old ones

This NFC change accomplishes three things:
1) Splits up the single unittest into reasonable segments.
2) Extends the test infra using a template to select the AST-node
   from which it is supposed to construct a `CallEvent`.
3) Adds a *lot* of different tests, documenting the current
   capabilities of the `CallDescription`. The corresponding tests are
   marked with `FIXME`s, where the current behavior should be different.

Both `CXXMemberCallExpr` and `CXXOperatorCallExpr` are derived from
`CallExpr`, so they are matched by using the default template parameter.
On the other hand, `CXXConstructExpr` is not derived from `CallExpr`.
In case we want to match for them, we need to pass the type explicitly
to the `CallDescriptionAction`.

About destructors:
They have no AST-node, but they are generated in the CFG machinery in
the analyzer. Thus, to be able to match against them, we would need to
construct a CFG and walk on that instead of simply walking the AST.

I'm also relaxing the `EXPECT`ation in the
`CallDescriptionConsumer::performTest()`, to check the `LookupResult`
only if we matched for the `CallDescription`.
This is necessary to allow tests in which we expect *no* matches at all.

Reviewed By: martong

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

Added: 


Modified: 
clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp

Removed: 




diff  --git a/clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp 
b/clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
index 2ebaa46b0f715..e232d0ff065bb 100644
--- a/clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
+++ b/clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
@@ -8,9 +8,11 @@
 
 #include "Reusables.h"
 
+#include "clang/AST/ExprCXX.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/Tooling/Tooling.h"
 #include "gtest/gtest.h"
+#include 
 
 namespace clang {
 namespace ento {
@@ -48,25 +50,48 @@ class ResultMap {
 // we were supposed to find ("true" in the provided ResultMap) and that we
 // don't find the ones that we weren't supposed to find
 // ("false" in the ResultMap).
+template 
 class CallDescriptionConsumer : public ExprEngineConsumer {
   ResultMap &RM;
   void performTest(const Decl *D) {
 using namespace ast_matchers;
+using T = MatchedExprT;
 
 if (!D->hasBody())
   return;
 
-const CallExpr *CE = findNode(D, callExpr());
 const StackFrameContext *SFC =
 Eng.getAnalysisDeclContextManager().getStackFrame(D);
-ProgramStateRef State = Eng.getInitialState(SFC);
-CallEventRef<> Call =
-Eng.getStateManager().getCallEventManager().getCall(CE, State, SFC);
+const ProgramStateRef State = Eng.getInitialState(SFC);
 
+// FIXME: Maybe use std::variant and std::visit for these.
+const auto MatcherCreator = []() {
+  if (std::is_same::value)
+return callExpr();
+  if (std::is_same::value)
+return cxxConstructExpr();
+  if (std::is_same::value)
+return cxxMemberCallExpr();
+  if (std::is_same::value)
+return cxxOperatorCallExpr();
+  llvm_unreachable("Only these expressions are supported for now.");
+};
+
+const Expr *E = findNode(D, MatcherCreator());
+
+CallEventManager &CEMgr = Eng.getStateManager().getCallEventManager();
+CallEventRef<> Call = [=, &CEMgr]() -> CallEventRef {
+  if (std::is_base_of::value)
+return CEMgr.getCall(E, State, SFC);
+  if (std::is_same::value)
+return CEMgr.getCXXConstructorCall(cast(E),
+   /*Target=*/nullptr, State, SFC);
+  llvm_unreachable("Only these expressions are supported for now.");
+}();
+
+// If the call actually matched, check if we really expected it to match.
 const bool *LookupResult = RM.lookup(*Call);
-// Check that we've found the function in the map
-// with the correct description.
-EXPECT_TRUE(LookupResult && *LookupResult);
+EXPECT_TRUE(!LookupResult || *LookupResult);
 
 // ResultMap is responsible for making sure that we've found *all* calls.
   }
@@ -83,6 +108,7 @@ class CallDescriptionConsumer : public ExprEngineConsumer {
   }
 };
 
+template 
 class CallDescriptionAction : public ASTFrontendAction {
   ResultMap RM;
 
@@ -93,63 +119,370 @@ class CallDescriptionAction : public ASTFrontendAction {
 
   std::unique_ptr CreateASTConsumer(CompilerInstance &Compiler,
  StringRef File) override {
-return std:

[clang] 3ec7b91 - [analyzer][NFC] Refactor CallEvent::isCalled()

2021-10-18 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-10-18T14:57:24+02:00
New Revision: 3ec7b91141da4b3f4dce4964ca3ea7c3549584d2

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

LOG: [analyzer][NFC] Refactor CallEvent::isCalled()

Refactor the code to make it more readable.

It will set up further changes, and improvements to this code in
subsequent patches.
This is a non-functional change.

Reviewed By: martong

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
clang/lib/StaticAnalyzer/Core/CallEvent.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
index 060fff1a74071..e10e3509fe3d7 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -1237,9 +1237,7 @@ enum CallDescriptionFlags : int {
 /// arguments and the name of the function.
 class CallDescription {
   friend CallEvent;
-
-  mutable IdentifierInfo *II = nullptr;
-  mutable bool IsLookupDone = false;
+  mutable Optional II;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
   std::vector QualifiedName;
@@ -1273,7 +1271,9 @@ class CallDescription {
   Optional RequiredParams = None)
   : QualifiedName(QualifiedName), RequiredArgs(RequiredArgs),
 RequiredParams(readRequiredParams(RequiredArgs, RequiredParams)),
-Flags(Flags) {}
+Flags(Flags) {
+assert(!QualifiedName.empty());
+  }
 
   /// Construct a CallDescription with default flags.
   CallDescription(ArrayRef QualifiedName,
@@ -1283,6 +1283,17 @@ class CallDescription {
 
   /// Get the name of the function that this object matches.
   StringRef getFunctionName() const { return QualifiedName.back(); }
+
+  /// Get the qualified name parts in reversed order.
+  /// E.g. { "std", "vector", "data" } -> "vector", "std"
+  auto begin_qualified_name_parts() const {
+return std::next(QualifiedName.rbegin());
+  }
+  auto end_qualified_name_parts() const { return QualifiedName.rend(); }
+
+  /// It's false, if and only if we expect a single identifier, such as
+  /// `getenv`. It's true for `std::swap`, or `my::detail::container::data`.
+  bool hasQualifiedNameParts() const { return QualifiedName.size() > 1; }
 };
 
 /// An immutable map from CallDescriptions to arbitrary data. Provides a 
unified

diff  --git a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp 
b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
index 9a95921b64c3b..ec44bcf5b27ca 100644
--- a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -307,10 +307,7 @@ bool CallEvent::isCalled(const CallDescription &CD) const {
   if (getKind() == CE_ObjCMessage)
 return false;
 
-  const IdentifierInfo *II = getCalleeIdentifier();
-  if (!II)
-return false;
-  const FunctionDecl *FD = dyn_cast_or_null(getDecl());
+  const auto *FD = dyn_cast_or_null(getDecl());
   if (!FD)
 return false;
 
@@ -320,44 +317,69 @@ bool CallEvent::isCalled(const CallDescription &CD) const 
{
(!CD.RequiredParams || CD.RequiredParams <= parameters().size());
   }
 
-  if (!CD.IsLookupDone) {
-CD.IsLookupDone = true;
+  if (!CD.II.hasValue()) {
 CD.II = &getState()->getStateManager().getContext().Idents.get(
 CD.getFunctionName());
   }
 
-  if (II != CD.II)
-return false;
+  const auto MatchNameOnly = [](const CallDescription &CD,
+const NamedDecl *ND) -> bool {
+DeclarationName Name = ND->getDeclName();
+if (const auto *II = Name.getAsIdentifierInfo())
+  return II == CD.II.getValue(); // Fast case.
 
-  // If CallDescription provides prefix names, use them to improve matching
-  // accuracy.
-  if (CD.QualifiedName.size() > 1 && FD) {
-const DeclContext *Ctx = FD->getDeclContext();
-// See if we'll be able to match them all.
-size_t NumUnmatched = CD.QualifiedName.size() - 1;
-for (; Ctx && isa(Ctx); Ctx = Ctx->getParent()) {
-  if (NumUnmatched == 0)
-break;
+// Simply report mismatch for:
+// C++ overloaded operators, constructors, destructors, etc.
+return false;
+  };
 
-  if (const auto *ND = dyn_cast(Ctx)) {
-if (ND->getName() == CD.QualifiedName[NumUnmatched - 1])
-  --NumUnmatched;
-continue;
-  }
+  const auto ExactMatchArgAndParamCounts =
+  [](const CallEvent &Call, const CallDescription &CD) -> bool {
+const bool ArgsMatch =
+!CD.RequiredArgs || CD.RequiredArgs == Call.getNumArgs();

[clang] 72d04d7 - [analyzer] Allow matching non-CallExprs using CallDescriptions

2021-10-18 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2021-10-18T14:57:24+02:00
New Revision: 72d04d7b2b53eea977e160551077cf1a3f51ba9a

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

LOG: [analyzer] Allow matching non-CallExprs using CallDescriptions

Fallback to stringification and string comparison if we cannot compare
the `IdentifierInfo`s, which is the case for C++ overloaded operators,
constructors, destructors, etc.

Examples:
  { "std", "basic_string", "basic_string", 2} // match the 2 param std::string 
constructor
  { "std", "basic_string", "~basic_string" }  // match the std::string 
destructor
  { "aaa", "bbb", "operator int" } // matches the struct bbb conversion 
operator to int

Reviewed By: martong

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/CallEvent.cpp
clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp 
b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
index ec44bcf5b27ca..5e504ad30b101 100644
--- a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -328,9 +328,11 @@ bool CallEvent::isCalled(const CallDescription &CD) const {
 if (const auto *II = Name.getAsIdentifierInfo())
   return II == CD.II.getValue(); // Fast case.
 
-// Simply report mismatch for:
+// Fallback to the slow stringification and comparison for:
 // C++ overloaded operators, constructors, destructors, etc.
-return false;
+// FIXME This comparison is way SLOWER than comparing pointers.
+// At some point in the future, we should compare FunctionDecl pointers.
+return Name.getAsString() == CD.getFunctionName();
   };
 
   const auto ExactMatchArgAndParamCounts =

diff  --git a/clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp 
b/clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
index e232d0ff065bb..d719240236558 100644
--- a/clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
+++ b/clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
@@ -187,12 +187,11 @@ TEST(CallDescription, MatchConstructor) {
   using namespace std;
   basic_string s("hello");
 })code";
-  // FIXME: We should match.
   const std::string Code = (Twine{MockStdStringHeader} + AdditionalCode).str();
   EXPECT_TRUE(tooling::runToolOnCode(
   std::unique_ptr(
   new CallDescriptionAction({
-  {{{"std", "basic_string", "basic_string"}, 2, 2}, false},
+  {{{"std", "basic_string", "basic_string"}, 2, 2}, true},
   })),
   Code));
 }
@@ -216,10 +215,9 @@ TEST(CallDescription, MatchConversionOperator) {
   aaa::bbb::Bar x;
   int tmp = x;
 })code";
-  // FIXME: We should match.
   EXPECT_TRUE(tooling::runToolOnCode(
   std::unique_ptr(new CallDescriptionAction<>({
-  {{{"aaa", "bbb", "Bar", "operator int"}}, false},
+  {{{"aaa", "bbb", "Bar", "operator int"}}, true},
   })),
   Code));
 }



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


[PATCH] D111794: [analyzer][NFC] Add unittests for CallDescription and split the old ones

2021-10-18 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5644d152578f: [analyzer][NFC] Add unittests for 
CallDescription and split the old ones (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111794

Files:
  clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp

Index: clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
===
--- clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
+++ clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
@@ -8,9 +8,11 @@
 
 #include "Reusables.h"
 
+#include "clang/AST/ExprCXX.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/Tooling/Tooling.h"
 #include "gtest/gtest.h"
+#include 
 
 namespace clang {
 namespace ento {
@@ -48,25 +50,48 @@
 // we were supposed to find ("true" in the provided ResultMap) and that we
 // don't find the ones that we weren't supposed to find
 // ("false" in the ResultMap).
+template 
 class CallDescriptionConsumer : public ExprEngineConsumer {
   ResultMap &RM;
   void performTest(const Decl *D) {
 using namespace ast_matchers;
+using T = MatchedExprT;
 
 if (!D->hasBody())
   return;
 
-const CallExpr *CE = findNode(D, callExpr());
 const StackFrameContext *SFC =
 Eng.getAnalysisDeclContextManager().getStackFrame(D);
-ProgramStateRef State = Eng.getInitialState(SFC);
-CallEventRef<> Call =
-Eng.getStateManager().getCallEventManager().getCall(CE, State, SFC);
+const ProgramStateRef State = Eng.getInitialState(SFC);
 
+// FIXME: Maybe use std::variant and std::visit for these.
+const auto MatcherCreator = []() {
+  if (std::is_same::value)
+return callExpr();
+  if (std::is_same::value)
+return cxxConstructExpr();
+  if (std::is_same::value)
+return cxxMemberCallExpr();
+  if (std::is_same::value)
+return cxxOperatorCallExpr();
+  llvm_unreachable("Only these expressions are supported for now.");
+};
+
+const Expr *E = findNode(D, MatcherCreator());
+
+CallEventManager &CEMgr = Eng.getStateManager().getCallEventManager();
+CallEventRef<> Call = [=, &CEMgr]() -> CallEventRef {
+  if (std::is_base_of::value)
+return CEMgr.getCall(E, State, SFC);
+  if (std::is_same::value)
+return CEMgr.getCXXConstructorCall(cast(E),
+   /*Target=*/nullptr, State, SFC);
+  llvm_unreachable("Only these expressions are supported for now.");
+}();
+
+// If the call actually matched, check if we really expected it to match.
 const bool *LookupResult = RM.lookup(*Call);
-// Check that we've found the function in the map
-// with the correct description.
-EXPECT_TRUE(LookupResult && *LookupResult);
+EXPECT_TRUE(!LookupResult || *LookupResult);
 
 // ResultMap is responsible for making sure that we've found *all* calls.
   }
@@ -83,6 +108,7 @@
   }
 };
 
+template 
 class CallDescriptionAction : public ASTFrontendAction {
   ResultMap RM;
 
@@ -93,63 +119,370 @@
 
   std::unique_ptr CreateASTConsumer(CompilerInstance &Compiler,
  StringRef File) override {
-return std::make_unique(Compiler, RM);
+return std::make_unique>(Compiler,
+   RM);
   }
 };
 
-TEST(CallEvent, CallDescription) {
-  // Test simple name matching.
+TEST(CallDescription, SimpleNameMatching) {
   EXPECT_TRUE(tooling::runToolOnCode(
-  std::unique_ptr(new CallDescriptionAction({
+  std::unique_ptr(new CallDescriptionAction<>({
   {{"bar"}, false}, // false: there's no call to 'bar' in this code.
   {{"foo"}, true},  // true: there's a call to 'foo' in this code.
-  })), "void foo(); void bar() { foo(); }"));
+  })),
+  "void foo(); void bar() { foo(); }"));
+}
 
-  // Test arguments check.
+TEST(CallDescription, RequiredArguments) {
   EXPECT_TRUE(tooling::runToolOnCode(
-  std::unique_ptr(new CallDescriptionAction({
+  std::unique_ptr(new CallDescriptionAction<>({
   {{"foo", 1}, true},
   {{"foo", 2}, false},
-  })), "void foo(int); void foo(int, int); void bar() { foo(1); }"));
+  })),
+  "void foo(int); void foo(int, int); void bar() { foo(1); }"));
+}
 
-  // Test lack of arguments check.
+TEST(CallDescription, LackOfRequiredArguments) {
   EXPECT_TRUE(tooling::runToolOnCode(
-  std::unique_ptr(new CallDescriptionAction({
+  std::unique_ptr(new CallDescriptionAction<>({
   {{"foo", None}, true},
   {{"foo", 2}, false},
-  })), "void foo(int); void foo(int, int); void bar() { foo(1); }"));
+  })),
+  "void foo(int); void foo(int, int); v

[PATCH] D111534: [analyzer][NFC] Refactor CallEvent::isCalled()

2021-10-18 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3ec7b91141da: [analyzer][NFC] Refactor CallEvent::isCalled() 
(authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D111534?vs=379778&id=380362#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111534

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp

Index: clang/lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -307,10 +307,7 @@
   if (getKind() == CE_ObjCMessage)
 return false;
 
-  const IdentifierInfo *II = getCalleeIdentifier();
-  if (!II)
-return false;
-  const FunctionDecl *FD = dyn_cast_or_null(getDecl());
+  const auto *FD = dyn_cast_or_null(getDecl());
   if (!FD)
 return false;
 
@@ -320,44 +317,69 @@
(!CD.RequiredParams || CD.RequiredParams <= parameters().size());
   }
 
-  if (!CD.IsLookupDone) {
-CD.IsLookupDone = true;
+  if (!CD.II.hasValue()) {
 CD.II = &getState()->getStateManager().getContext().Idents.get(
 CD.getFunctionName());
   }
 
-  if (II != CD.II)
-return false;
+  const auto MatchNameOnly = [](const CallDescription &CD,
+const NamedDecl *ND) -> bool {
+DeclarationName Name = ND->getDeclName();
+if (const auto *II = Name.getAsIdentifierInfo())
+  return II == CD.II.getValue(); // Fast case.
 
-  // If CallDescription provides prefix names, use them to improve matching
-  // accuracy.
-  if (CD.QualifiedName.size() > 1 && FD) {
-const DeclContext *Ctx = FD->getDeclContext();
-// See if we'll be able to match them all.
-size_t NumUnmatched = CD.QualifiedName.size() - 1;
-for (; Ctx && isa(Ctx); Ctx = Ctx->getParent()) {
-  if (NumUnmatched == 0)
-break;
+// Simply report mismatch for:
+// C++ overloaded operators, constructors, destructors, etc.
+return false;
+  };
 
-  if (const auto *ND = dyn_cast(Ctx)) {
-if (ND->getName() == CD.QualifiedName[NumUnmatched - 1])
-  --NumUnmatched;
-continue;
-  }
+  const auto ExactMatchArgAndParamCounts =
+  [](const CallEvent &Call, const CallDescription &CD) -> bool {
+const bool ArgsMatch =
+!CD.RequiredArgs || CD.RequiredArgs == Call.getNumArgs();
+const bool ParamsMatch =
+!CD.RequiredParams || CD.RequiredParams == Call.parameters().size();
+return ArgsMatch && ParamsMatch;
+  };
 
-  if (const auto *RD = dyn_cast(Ctx)) {
-if (RD->getName() == CD.QualifiedName[NumUnmatched - 1])
-  --NumUnmatched;
+  const auto MatchQualifiedNameParts = [](const CallDescription &CD,
+  const Decl *D) -> bool {
+const auto FindNextNamespaceOrRecord =
+[](const DeclContext *Ctx) -> const DeclContext * {
+  while (Ctx && !isa(Ctx))
+Ctx = Ctx->getParent();
+  return Ctx;
+};
+
+auto QualifierPartsIt = CD.begin_qualified_name_parts();
+const auto QualifierPartsEndIt = CD.end_qualified_name_parts();
+
+// Match namespace and record names. Skip unrelated names if they don't
+// match.
+const DeclContext *Ctx = FindNextNamespaceOrRecord(D->getDeclContext());
+for (; Ctx && QualifierPartsIt != QualifierPartsEndIt;
+ Ctx = FindNextNamespaceOrRecord(Ctx->getParent())) {
+  // If not matched just continue and try matching for the next one.
+  if (cast(Ctx)->getName() != *QualifierPartsIt)
 continue;
-  }
+  ++QualifierPartsIt;
 }
 
-if (NumUnmatched > 0)
-  return false;
-  }
+// We matched if we consumed all expected qualifier segments.
+return QualifierPartsIt == QualifierPartsEndIt;
+  };
+
+  // Let's start matching...
+  if (!ExactMatchArgAndParamCounts(*this, CD))
+return false;
+
+  if (!MatchNameOnly(CD, FD))
+return false;
+
+  if (!CD.hasQualifiedNameParts())
+return true;
 
-  return (!CD.RequiredArgs || CD.RequiredArgs == getNumArgs()) &&
- (!CD.RequiredParams || CD.RequiredParams == parameters().size());
+  return MatchQualifiedNameParts(CD, FD);
 }
 
 SVal CallEvent::getArgSVal(unsigned Index) const {
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -1237,9 +1237,7 @@
 /// arguments and the name of the function.
 class CallDescription {
   friend CallEvent;
-
-  mutable IdentifierInfo *II = nullptr;
-  mutable bool IsLookupDone = false;
+  mutable Option

[PATCH] D111535: [analyzer] Allow matching non-CallExprs using CallDescriptions

2021-10-18 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG72d04d7b2b53: [analyzer] Allow matching non-CallExprs using 
CallDescriptions (authored by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111535

Files:
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp
  clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp


Index: clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
===
--- clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
+++ clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
@@ -187,12 +187,11 @@
   using namespace std;
   basic_string s("hello");
 })code";
-  // FIXME: We should match.
   const std::string Code = (Twine{MockStdStringHeader} + AdditionalCode).str();
   EXPECT_TRUE(tooling::runToolOnCode(
   std::unique_ptr(
   new CallDescriptionAction({
-  {{{"std", "basic_string", "basic_string"}, 2, 2}, false},
+  {{{"std", "basic_string", "basic_string"}, 2, 2}, true},
   })),
   Code));
 }
@@ -216,10 +215,9 @@
   aaa::bbb::Bar x;
   int tmp = x;
 })code";
-  // FIXME: We should match.
   EXPECT_TRUE(tooling::runToolOnCode(
   std::unique_ptr(new CallDescriptionAction<>({
-  {{{"aaa", "bbb", "Bar", "operator int"}}, false},
+  {{{"aaa", "bbb", "Bar", "operator int"}}, true},
   })),
   Code));
 }
Index: clang/lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -328,9 +328,11 @@
 if (const auto *II = Name.getAsIdentifierInfo())
   return II == CD.II.getValue(); // Fast case.
 
-// Simply report mismatch for:
+// Fallback to the slow stringification and comparison for:
 // C++ overloaded operators, constructors, destructors, etc.
-return false;
+// FIXME This comparison is way SLOWER than comparing pointers.
+// At some point in the future, we should compare FunctionDecl pointers.
+return Name.getAsString() == CD.getFunctionName();
   };
 
   const auto ExactMatchArgAndParamCounts =


Index: clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
===
--- clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
+++ clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
@@ -187,12 +187,11 @@
   using namespace std;
   basic_string s("hello");
 })code";
-  // FIXME: We should match.
   const std::string Code = (Twine{MockStdStringHeader} + AdditionalCode).str();
   EXPECT_TRUE(tooling::runToolOnCode(
   std::unique_ptr(
   new CallDescriptionAction({
-  {{{"std", "basic_string", "basic_string"}, 2, 2}, false},
+  {{{"std", "basic_string", "basic_string"}, 2, 2}, true},
   })),
   Code));
 }
@@ -216,10 +215,9 @@
   aaa::bbb::Bar x;
   int tmp = x;
 })code";
-  // FIXME: We should match.
   EXPECT_TRUE(tooling::runToolOnCode(
   std::unique_ptr(new CallDescriptionAction<>({
-  {{{"aaa", "bbb", "Bar", "operator int"}}, false},
+  {{{"aaa", "bbb", "Bar", "operator int"}}, true},
   })),
   Code));
 }
Index: clang/lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -328,9 +328,11 @@
 if (const auto *II = Name.getAsIdentifierInfo())
   return II == CD.II.getValue(); // Fast case.
 
-// Simply report mismatch for:
+// Fallback to the slow stringification and comparison for:
 // C++ overloaded operators, constructors, destructors, etc.
-return false;
+// FIXME This comparison is way SLOWER than comparing pointers.
+// At some point in the future, we should compare FunctionDecl pointers.
+return Name.getAsString() == CD.getFunctionName();
   };
 
   const auto ExactMatchArgAndParamCounts =
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105169: [Clang/Test]: Rename enable_noundef_analysis to disable-noundef-analysis and turn it off by default

2021-10-18 Thread Oliver Stannard (Linaro) via Phabricator via cfe-commits
ostannard added a comment.

This change is causing a lot of failures in the address sanitiser tests on the 
2-stage AArch64 buildbots. For example: 
https://lab.llvm.org/buildbot/#/builders/179/builds/1326

I can reproduce the failures on another AArch64 machine, they only happen with 
a 2-stage build, the first stage tests pass fine. I've verified that reverting 
this (and the related test patches) does make the failures go away.

Is there enough detail in the buildbot logs for you to investigate this, or is 
there any extra stuff (logs, intermediate files) I can send you to help? Would 
it be OK to revert this change until these failures are fixed?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105169

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


[PATCH] D105169: [Clang/Test]: Rename enable_noundef_analysis to disable-noundef-analysis and turn it off by default

2021-10-18 Thread Sylvestre Ledru via Phabricator via cfe-commits
sylvestre.ledru added a comment.

This change caused libclc to fail to build on old ubuntu (using llvm-spir  
10.0.0-1)
See:
https://bugs.llvm.org/show_bug.cgi?id=52200


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105169

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


[PATCH] D105169: [Clang/Test]: Rename enable_noundef_analysis to disable-noundef-analysis and turn it off by default

2021-10-18 Thread Juneyoung Lee via Phabricator via cfe-commits
aqjune added a comment.

I will revert this patch, since its fix needs some time for me to investigate.
I have access to an AArch server, so I can give it a try by myself.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105169

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


[PATCH] D111993: [libomptarget][WIP] Patch amdgpu DeviceRTL until it compiles

2021-10-18 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield created this revision.
JonChesterfield added a reviewer: jdoerfert.
Herald added subscribers: kerbowa, t-tye, tpr, dstuttard, yaxunl, nhaehnle, 
jvesely, kzhuravl.
JonChesterfield requested review of this revision.
Herald added subscribers: openmp-commits, cfe-commits, sstefan1, wdng.
Herald added projects: clang, OpenMP.

Requires cmake changes in D111983 , D111987 


Mixture of typo fixes, stub implementations and a workaround for
runtime values for memory ordering


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D111993

Files:
  clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
  openmp/libomptarget/DeviceRTL/include/Synchronization.h
  openmp/libomptarget/DeviceRTL/src/Configuration.cpp
  openmp/libomptarget/DeviceRTL/src/Mapping.cpp
  openmp/libomptarget/DeviceRTL/src/Synchronization.cpp
  openmp/libomptarget/DeviceRTL/src/Utils.cpp

Index: openmp/libomptarget/DeviceRTL/src/Utils.cpp
===
--- openmp/libomptarget/DeviceRTL/src/Utils.cpp
+++ openmp/libomptarget/DeviceRTL/src/Utils.cpp
@@ -35,8 +35,9 @@
 #pragma omp begin declare variant match(device = {arch(amdgcn)})
 
 void Unpack(uint64_t Val, uint32_t *LowBits, uint32_t *HighBits) {
-  *LowBits = (uint32_t)(Val & UINT64_C(0x));
-  *HighBits = (uint32_t)((Val & UINT64_C(0x)) >> 32);
+  static_assert(sizeof(unsigned long) == 8, "");
+  *LowBits = (uint32_t)(Val & 0xUL);
+  *HighBits = (uint32_t)((Val & 0xUL) >> 32);
 }
 
 uint64_t Pack(uint32_t LowBits, uint32_t HighBits) {
@@ -75,7 +76,7 @@
 
 int32_t shuffle(uint64_t Mask, int32_t Var, int32_t SrcLane) {
   int Width = mapping::getWarpSize();
-  int Self = mapping::getgetThreadIdInWarp();
+  int Self = mapping::getThreadIdInWarp();
   int Index = SrcLane + (Self & ~(Width - 1));
   return __builtin_amdgcn_ds_bpermute(Index << 2, Var);
 }
Index: openmp/libomptarget/DeviceRTL/src/Synchronization.cpp
===
--- openmp/libomptarget/DeviceRTL/src/Synchronization.cpp
+++ openmp/libomptarget/DeviceRTL/src/Synchronization.cpp
@@ -32,9 +32,18 @@
 uint32_t atomicInc(uint32_t *Address, uint32_t Val, int Ordering);
 
 uint32_t atomicRead(uint32_t *Address, int Ordering) {
+  // TODO: amdgpu can load from memory. nvptx probably can too
   return __atomic_fetch_add(Address, 0U, __ATOMIC_SEQ_CST);
 }
 
+void atomicStore(uint32_t *Address, uint32_t Val, int Ordering) {
+  __atomic_store_n(Address, Val, Ordering);
+}
+
+void atomicStore(uint64_t *Address, uint64_t Val, int Ordering) {
+  __atomic_store_n(Address, Val, Ordering);
+}
+
 uint32_t atomicAdd(uint32_t *Address, uint32_t Val, int Ordering) {
   return __atomic_fetch_add(Address, Val, Ordering);
 }
@@ -64,11 +73,54 @@
 ///{
 #pragma omp begin declare variant match(device = {arch(amdgcn)})
 
+#define FENCE_ATOMIC_CASES()   \
+  CASE(__ATOMIC_ACQUIRE);  \
+  CASE(__ATOMIC_RELEASE);  \
+  CASE(__ATOMIC_ACQ_REL);  \
+  CASE(__ATOMIC_SEQ_CST)
+#define ALL_ATOMIC_CASES() \
+  FENCE_ATOMIC_CASES();\
+  CASE(__ATOMIC_RELAXED);  \
+  CASE(__ATOMIC_CONSUME)
+
+#if 0
+// Can't spell the dispatch from runtime ordering like:
+template 
+static uint32_t atomicInc(uint32_t *Address, uint32_t Val) {
+  return __builtin_amdgcn_atomic_inc32(Address, Val, Ordering , "");
+}
+// clang/lib/AST/ExprConstant.cpp:14739: bool clang::Expr::EvaluateAsInt(clang::Expr::EvalResult&, const clang::ASTContext&, clang::Expr::SideEffectsKind, bool) const: Assertion `!isValueDependent() && "Expression evaluator can't be called on a dependent expression."' failed.
+
+// Can spell it with raw macros or struct dispatch, or raise ordering to a
+// template parameter on the Synchonization API. Choosing struct dispatch.
+#endif
+
+
+namespace {
+template  struct atomicOpTy;
+#define CASE(X)\
+  template <> struct atomicOpTy {   \
+static uint32_t atomicInc(uint32_t *Address, uint32_t Val) {   \
+  return __builtin_amdgcn_atomic_inc32(Address, Val, X, "");   \
+}  \
+  };
+ALL_ATOMIC_CASES();
+#undef CASE
+}
+
 uint32_t atomicInc(uint32_t *Address, uint32_t Val, int Ordering) {
-  return __builtin_amdgcn_atomic_inc32(Address, Val, Ordering, "");
+  switch (Ordering) {
+  default:
+__builtin_unreachable();
+#define CASE(X)   

[PATCH] D111993: [libomptarget][WIP] Patch amdgpu DeviceRTL until it compiles

2021-10-18 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp:255
  options::OPT_fno_openmp_target_new_runtime, false))
-BitcodeSuffix = "new-amdgcn-" + GPUArch;
+BitcodeSuffix = "new-amdgpu-" + GPUArch;
   else

Naming is somewhat inconsistent. I think 'amdgcn' refers to 'graphics core 
next', but the gfx10 cards are branded 'radeon dna'. Changing to a new library 
seems a relatively good point to rename it.



Comment at: openmp/libomptarget/DeviceRTL/include/Synchronization.h:48
 /// Atomically read \p Addr with \p Ordering semantics.
 uint32_t read(uint32_t *Addr, int Ordering);
 

^ would like to call this 'load'



Comment at: openmp/libomptarget/DeviceRTL/src/Configuration.cpp:23
 
-extern uint32_t __omp_rtl_debug_kind;
+// extern uint32_t __omp_rtl_debug_kind;
 

What is this? Symbol is undefined on nvptx as far as I can tell. Amdgpu fails 
to link without a definition.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111993

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


[PATCH] D111993: [libomptarget][WIP] Patch amdgpu DeviceRTL until it compiles

2021-10-18 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: openmp/libomptarget/DeviceRTL/src/Synchronization.cpp:87
+#if 0
+// Can't spell the dispatch from runtime ordering like:
+template 

Suggestion offline is that delaying the check in clang for these builtins until 
template instantiation would make them usable from a function template, 
worthwhile usability improvement


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111993

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


[PATCH] D109652: [PowerPC] Restrict various P10 options to P10 only.

2021-10-18 Thread Lei Huang via Phabricator via cfe-commits
lei accepted this revision.
lei added a comment.

LGTM
I think you went a bit overkill with the tests for this patch 🙂.  Please cut 
down the number of run lines before committing.




Comment at: clang/test/Driver/ppc-p10-features-support-check.c:4
+// RUN:   --check-prefix=HASPAIRED
+// RUN: %clang -target powerpc64le-unknown-linux-gnu -S -emit-llvm  \
+// RUN:   -mcpu=power10 -mpaired-vector-memops %s -o - | FileCheck %s \

I think you can just use `pwr10` and `power10` in diff run lines if you need, 
but no need to test for both in this case.



Comment at: clang/test/Driver/ppc-p10-features-support-check.c:11
+// RUN: not %clang -target powerpc64le-unknown-linux-gnu -fsyntax-only \
+// RUN:   -mcpu=pwr8 -mpaired-vector-memops %s 2>&1 | FileCheck %s \
+// RUN:   --check-prefix=NOPAIRED

might be an overkill to also test for pwr7/8.  I think pwr9/10 test is enough.



Comment at: clang/test/Driver/ppc-p10-features-support-check.c:19
+// RUN:   --check-prefix=NOPAIRED
+
+// RUN: %clang -target powerpc64le-unknown-linux-gnu -S -emit-llvm  \

same comment for the set of runlines below.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109652

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


[PATCH] D111985: [Clang] Add elementwise min/max builtins.

2021-10-18 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 380409.
fhahn added a comment.

polish tests a bit


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111985

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-elementwise-math.c
  clang/test/Sema/builtins-elementwise-math.c

Index: clang/test/Sema/builtins-elementwise-math.c
===
--- /dev/null
+++ clang/test/Sema/builtins-elementwise-math.c
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 %s -pedantic -verify -triple=x86_64-apple-darwin9
+
+typedef float float4 __attribute__((ext_vector_type(4)));
+typedef int int3 __attribute__((ext_vector_type(3)));
+
+struct Foo {
+  char *p;
+};
+
+void test_builtin_elementwise_max(int i, double d, float4 v, int3 iv) {
+  i = __builtin_elementwise_max(i, d);
+  // expected-error@-1 {{argument types do not match, 'int' != 'double'}}
+
+  struct Foo s = __builtin_elementwise_max(i, i);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_elementwise_max(i);
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 1}}
+
+  i = __builtin_elementwise_max();
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 0}}
+
+  i = __builtin_elementwise_max(v, iv);
+  // expected-error@-1 {{argument types do not match, 'float4' (vector of 4 'float' values) != 'int3' (vector of 3 'int' values)}}
+}
+
+void test_builtin_elementwise_min(int i, double d, float4 v, int3 iv) {
+  i = __builtin_elementwise_min(i, d);
+  // expected-error@-1 {{argument types do not match, 'int' != 'double'}}
+
+  struct Foo s = __builtin_elementwise_min(i, i);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_elementwise_min(i);
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 1}}
+
+  i = __builtin_elementwise_min();
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 0}}
+
+  i = __builtin_elementwise_min(v, iv);
+  // expected-error@-1 {{argument types do not match, 'float4' (vector of 4 'float' values) != 'int3' (vector of 3 'int' values)}}
+}
Index: clang/test/CodeGen/builtins-elementwise-math.c
===
--- /dev/null
+++ clang/test/CodeGen/builtins-elementwise-math.c
@@ -0,0 +1,88 @@
+// RUN: %clang_cc1 -disable-noundef-analysis -triple x86_64-apple-darwin %s -emit-llvm -disable-llvm-passes -o - | FileCheck %s
+
+typedef float float4 __attribute__((ext_vector_type(4)));
+typedef short int si8 __attribute__((ext_vector_type(8)));
+typedef unsigned int u4 __attribute__((ext_vector_type(4)));
+
+void test_builtin_elementwise_max(float f1, float f2, double d1, double d2,
+  float4 vf1, float4 vf2, long long int i1,
+  long long int i2, si8 vi1,si8 vi2,
+  unsigned u1, unsigned u2, u4 vu1, u4 vu2) {
+  // CHECK-LABEL: define void @test_builtin_elementwise_max(
+
+  // CHECK:  [[F1:%.+]] = load float, float* %f1.addr, align 4
+  // CHECK-NEXT: [[F2:%.+]] = load float, float* %f2.addr, align 4
+  // CHECK-NEXT:  call float @llvm.maxnum.f32(float %0, float %1)
+  f1 = __builtin_elementwise_max(f1, f2);
+
+  // CHECK:  [[D1:%.+]] = load double, double* %d1.addr, align 8
+  // CHECK-NEXT: [[D2:%.+]] = load double, double* %d2.addr, align 8
+  // CHECK-NEXT: call double @llvm.maxnum.f64(double [[D1]], double [[D2]])
+  d1 = __builtin_elementwise_max(d1, d2);
+
+  // CHECK:  [[VF1:%.+]] = load <4 x float>, <4 x float>* %vf1.addr, align 16
+  // CHECK-NEXT: [[VF2:%.+]] = load <4 x float>, <4 x float>* %vf2.addr, align 16
+  // CHECK-NEXT: call <4 x float> @llvm.maxnum.v4f32(<4 x float> [[VF1]], <4 x float> [[VF2]])
+  vf1 = __builtin_elementwise_max(vf1, vf2);
+
+  // CHECK:  [[I1:%.+]] = load i64, i64* %i1.addr, align 8
+  // CHECK-NEXT: [[I2:%.+]] = load i64, i64* %i2.addr, align 8
+  // CHECK-NEXT: call i64 @llvm.smax.i64(i64 [[I1]], i64 [[I2]])
+  i1 = __builtin_elementwise_max(i1, i2);
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: [[VI2:%.+]] = load <8 x i16>, <8 x i16>* %vi2.addr, align 16
+  // CHECK-NEXT: call <8 x i16> @llvm.smax.v8i16(<8 x i16> [[VI1]], <8 x i16> [[VI2]])
+  vi1 = __builtin_elementwise_max(vi1, vi2);
+
+  // CHECK:  [[U1:%.+]] = load i32, i32* %u1.addr, align 4
+  // CHECK-NEXT: [[U2:%.+]] = load i32, i32* %u2.addr, align 4
+  // CHECK-NEXT: call i32 @llvm.umax.i32(i32 [[U1]], i32 [[U2]])
+  u1 = __builtin_elementwise_max(u1, u2);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x

[PATCH] D111986: [Clang] Add elementwise abs builtin.

2021-10-18 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 380411.
fhahn added a comment.

polish tests a bit


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111986

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-elementwise-math.c
  clang/test/Sema/builtins-elementwise-math.c

Index: clang/test/Sema/builtins-elementwise-math.c
===
--- clang/test/Sema/builtins-elementwise-math.c
+++ clang/test/Sema/builtins-elementwise-math.c
@@ -2,11 +2,32 @@
 
 typedef float float4 __attribute__((ext_vector_type(4)));
 typedef int int3 __attribute__((ext_vector_type(3)));
+typedef unsigned unsigned4 __attribute__((ext_vector_type(4)));
 
 struct Foo {
   char *p;
 };
 
+void test_builtin_elementwise_abs(int i, double d, float4 v, int3 iv, unsigned u, unsigned4 uv) {
+  struct Foo s = __builtin_elementwise_abs(i);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_elementwise_abs();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_elementwise_abs(i, i);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_elementwise_abs(v);
+  // expected-error@-1 {{assigning to 'int' from incompatible type 'float4' (vector of 4 'float' values)}}
+
+  u = __builtin_elementwise_abs(u);
+  // expected-error@-1 {{argument must have a signed integer or floating point type, but was an unsigned integer type}}
+
+  uv = __builtin_elementwise_abs(uv);
+  // expected-error@-1 {{argument must have a signed integer or floating point type, but was an unsigned integer type}}
+}
+
 void test_builtin_elementwise_max(int i, double d, float4 v, int3 iv) {
   i = __builtin_elementwise_max(i, d);
   // expected-error@-1 {{argument types do not match, 'int' != 'double'}}
Index: clang/test/CodeGen/builtins-elementwise-math.c
===
--- clang/test/CodeGen/builtins-elementwise-math.c
+++ clang/test/CodeGen/builtins-elementwise-math.c
@@ -4,12 +4,36 @@
 typedef short int si8 __attribute__((ext_vector_type(8)));
 typedef unsigned int u4 __attribute__((ext_vector_type(4)));
 
+void test_builtin_elementwise_abs(float f1, float f2, double d1, double d2,
+  float4 vf1, float4 vf2, si8 vi1, si8 vi2,
+  long long int i1, long long int i2) {
+  // CHECK-LABEL: define void @test_builtin_elementwise_abs(
+  // CHECK:  [[F1:%.+]] = load float, float* %f1.addr, align 4
+  // CHECK-NEXT:  call float @llvm.fabs.f32(float [[F1]])
+  f2 = __builtin_elementwise_abs(f1);
+
+  // CHECK:  [[D1:%.+]] = load double, double* %d1.addr, align 8
+  // CHECK-NEXT: call double @llvm.fabs.f64(double [[D1]])
+  d2 = __builtin_elementwise_abs(d1);
+
+  // CHECK:  [[VF1:%.+]] = load <4 x float>, <4 x float>* %vf1.addr, align 16
+  // CHECK-NEXT: call <4 x float> @llvm.fabs.v4f32(<4 x float> [[VF1]])
+  vf2 = __builtin_elementwise_abs(vf1);
+
+  // CHECK:  [[I1:%.+]] = load i64, i64* %i1.addr, align 8
+  // CHECK-NEXT: call i64 @llvm.abs.i64(i64 [[I1]], i1 false)
+  i2 = __builtin_elementwise_abs(i1);
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call <8 x i16> @llvm.abs.v8i16(<8 x i16> [[VI1]], i1 false)
+  vi2 = __builtin_elementwise_abs(vi1);
+}
+
 void test_builtin_elementwise_max(float f1, float f2, double d1, double d2,
   float4 vf1, float4 vf2, long long int i1,
   long long int i2, si8 vi1,si8 vi2,
   unsigned u1, unsigned u2, u4 vu1, u4 vu2) {
   // CHECK-LABEL: define void @test_builtin_elementwise_max(
-
   // CHECK:  [[F1:%.+]] = load float, float* %f1.addr, align 4
   // CHECK-NEXT: [[F2:%.+]] = load float, float* %f2.addr, align 4
   // CHECK-NEXT:  call float @llvm.maxnum.f32(float %0, float %1)
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -1976,9 +1976,12 @@
 break;
   }
 
+  case Builtin::BI__builtin_elementwise_abs:
+return SemaBuiltinElementwiseMathOneArg(TheCall, TheCallResult);
+
   case Builtin::BI__builtin_elementwise_min:
   case Builtin::BI__builtin_elementwise_max:
-return SemaBuiltinElementwiseMath(TheCall, TheCallResult);
+return SemaBuiltinElementwiseMathTwoArgs(TheCall, TheCallResult);
 
   case Builtin::BI__builtin_matrix_transpose:
 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
@@ -16653,8 +16656,32 @@
  _2, _3, _

[PATCH] D112001: [Clang] Add min/max reduction builtins.

2021-10-18 Thread Florian Hahn via Phabricator via cfe-commits
fhahn created this revision.
fhahn added reviewers: aaron.ballman, scanon, craig.topper, rjmccall, 
erichkeane.
fhahn requested review of this revision.
Herald added a project: clang.

This patch implements __builtin_reduce_max and __builtin_reduce_min as
specified in D111529 .

The order of operations does not matter for min or max reductions and
they can be directly lowered to the corresponding
llvm.vector.reduce.{fmin,fmax,umin,umax,smin,smax} intrinsic calls.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112001

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-elementwise-math.c
  clang/test/Sema/builtins-elementwise-math.c

Index: clang/test/Sema/builtins-elementwise-math.c
===
--- clang/test/Sema/builtins-elementwise-math.c
+++ clang/test/Sema/builtins-elementwise-math.c
@@ -61,3 +61,31 @@
   i = __builtin_elementwise_min(v, iv);
   // expected-error@-1 {{argument types do not match, 'float4' (vector of 4 'float' values) != 'int3' (vector of 3 'int' values)}}
 }
+
+void test_builtin_reduce_max(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_max(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_reduce_max(v, v);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_reduce_max();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_reduce_max(i);
+  // expected-error@-1 {{argument must have a vector type, but was 'int'}}
+}
+
+void test_builtin_reduce_min(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_min(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_reduce_min(v, v);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_reduce_min();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_reduce_min(i);
+  // expected-error@-1 {{argument must have a vector type, but was 'int'}}
+}
Index: clang/test/CodeGen/builtins-elementwise-math.c
===
--- clang/test/CodeGen/builtins-elementwise-math.c
+++ clang/test/CodeGen/builtins-elementwise-math.c
@@ -110,3 +110,33 @@
   // CHECK-NEXT: call <4 x i32> @llvm.umin.v4i32(<4 x i32> [[VU1]], <4 x i32> [[VU2]])
   vu1 = __builtin_elementwise_min(vu1, vu2);
 }
+
+void test_builtin_reduce_max(float4 vf1, si8 vi1, u4 vu1) {
+  // CHECK-LABEL: define void @test_builtin_reduce_max(
+  // CHECK:  [[VF1:%.+]] = load <4 x float>, <4 x float>* %vf1.addr, align 16
+  // CHECK-NEXT: call float @llvm.vector.reduce.fmax.v4f32(<4 x float> [[VF1]])
+  float r1 = __builtin_reduce_max(vf1);
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.smax.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_max(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.umax.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_max(vu1);
+}
+
+void test_builtin_reduce_min(float4 vf1, si8 vi1, u4 vu1) {
+  // CHECK-LABEL: define void @test_builtin_reduce_min(
+  // CHECK:  [[VF1:%.+]] = load <4 x float>, <4 x float>* %vf1.addr, align 16
+  // CHECK-NEXT: call float @llvm.vector.reduce.fmin.v4f32(<4 x float> [[VF1]])
+  float r1 = __builtin_reduce_min(vf1);
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.smin.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_min(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.umin.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_min(vu1);
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -1978,11 +1978,15 @@
 
   case Builtin::BI__builtin_elementwise_abs:
 return SemaBuiltinElementwiseMathOneArg(TheCall, TheCallResult);
-
   case Builtin::BI__builtin_elementwise_min:
   case Builtin::BI__builtin_elementwise_max:
 return SemaBuiltinElementwiseMathTwoArgs(TheCall, TheCallResult);
 
+  case Builtin::BI__builtin_reduce_max:
+  case Builtin::BI__builtin_reduce_min:
+return SemaBuiltinReduceMath(TheCall, TheCallResult);
+
+
   case Builtin::BI__builtin_matrix_transpose:
 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
   case Builtin::BI__builtin_matrix_column_major_load:
@@ -16656,6 +16660,

[clang] ab41a1c - [clang] Disable -clear-ast-before-backend with -print-stats

2021-10-18 Thread Arthur Eubanks via cfe-commits

Author: Arthur Eubanks
Date: 2021-10-18T08:43:32-07:00
New Revision: ab41a1c50558f23e5b6aa7a3b68825f9b4a71fe7

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

LOG: [clang] Disable -clear-ast-before-backend with -print-stats

We still need access to various things in the ASTContext when printing stats.

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

Added: 


Modified: 
clang/lib/Frontend/CompilerInvocation.cpp
clang/test/Misc/clear-ast-before-backend.c

Removed: 




diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 7360e6b40d69a..410702d51ed2a 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -454,6 +454,8 @@ static bool FixupInvocation(CompilerInvocation &Invocation,
   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
+  if (FrontendOpts.ShowStats)
+CodeGenOpts.ClearASTBeforeBackend = false;
   LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;

diff  --git a/clang/test/Misc/clear-ast-before-backend.c 
b/clang/test/Misc/clear-ast-before-backend.c
index 8e46d3bcb0682..88809b86f866e 100644
--- a/clang/test/Misc/clear-ast-before-backend.c
+++ b/clang/test/Misc/clear-ast-before-backend.c
@@ -1,3 +1,9 @@
 // RUN: %clang_cc1 -clear-ast-before-backend %s -emit-obj -o /dev/null -O1
+// RUN: %clang_cc1 -clear-ast-before-backend %s -emit-obj -o /dev/null 
-print-stats 2>&1 | FileCheck %s
+
+// CHECK: *** Decl Stats:
+// CHECK: {{.*}} decls total
+// CHECK: 1 Function decls
+// CHECK: Total bytes =
 
 void f() {}



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


[PATCH] D111973: [clang] Disable -clear-ast-before-backend with -print-stats

2021-10-18 Thread Arthur Eubanks via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGab41a1c50558: [clang] Disable -clear-ast-before-backend with 
-print-stats (authored by aeubanks).

Changed prior to commit:
  https://reviews.llvm.org/D111973?vs=380281&id=380421#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111973

Files:
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Misc/clear-ast-before-backend.c


Index: clang/test/Misc/clear-ast-before-backend.c
===
--- clang/test/Misc/clear-ast-before-backend.c
+++ clang/test/Misc/clear-ast-before-backend.c
@@ -1,3 +1,9 @@
 // RUN: %clang_cc1 -clear-ast-before-backend %s -emit-obj -o /dev/null -O1
+// RUN: %clang_cc1 -clear-ast-before-backend %s -emit-obj -o /dev/null 
-print-stats 2>&1 | FileCheck %s
+
+// CHECK: *** Decl Stats:
+// CHECK: {{.*}} decls total
+// CHECK: 1 Function decls
+// CHECK: Total bytes =
 
 void f() {}
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -454,6 +454,8 @@
   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
+  if (FrontendOpts.ShowStats)
+CodeGenOpts.ClearASTBeforeBackend = false;
   LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;


Index: clang/test/Misc/clear-ast-before-backend.c
===
--- clang/test/Misc/clear-ast-before-backend.c
+++ clang/test/Misc/clear-ast-before-backend.c
@@ -1,3 +1,9 @@
 // RUN: %clang_cc1 -clear-ast-before-backend %s -emit-obj -o /dev/null -O1
+// RUN: %clang_cc1 -clear-ast-before-backend %s -emit-obj -o /dev/null -print-stats 2>&1 | FileCheck %s
+
+// CHECK: *** Decl Stats:
+// CHECK: {{.*}} decls total
+// CHECK: 1 Function decls
+// CHECK: Total bytes =
 
 void f() {}
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -454,6 +454,8 @@
   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
+  if (FrontendOpts.ShowStats)
+CodeGenOpts.ClearASTBeforeBackend = false;
   LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D111973: [clang] Disable -clear-ast-before-backend with -print-stats

2021-10-18 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added a comment.

In D111973#3069304 , @dblaikie wrote:

> Could you check some of the stats output is valid/expected, not just 
> corrupt/garbage? "just doesn't crash" isn't a great criteria for a test.

forgot to upload the diff, but I did so in the committed change


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111973

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


[PATCH] D111973: [clang] Disable -clear-ast-before-backend with -print-stats

2021-10-18 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added a comment.

In D111973#3070519 , @aeubanks wrote:

> In D111973#3069304 , @dblaikie 
> wrote:
>
>> Could you check some of the stats output is valid/expected, not just 
>> corrupt/garbage? "just doesn't crash" isn't a great criteria for a test.
>
> forgot to upload the diff, but I did so in the committed change

oh wait phab updated with the committed change, I didn't know that happened


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111973

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


[PATCH] D112008: Add -extra-arg-clang-tidy to {clang-tidy-diff,run-clang-tidy}.py

2021-10-18 Thread Xavier Roche via Phabricator via cfe-commits
Xavier created this revision.
Xavier added a reviewer: alexfh.
Xavier added a project: clang-tools-extra.
Xavier requested review of this revision.
Herald added a subscriber: cfe-commits.

This small patch adds a new `-extra-arg-clang-tidy` option to clang-tidy-diff 
and run-clang-tidy scripts. This is especially handy in addition to the 
`-checks` option, to tune the executed checks.

//Example//:

  clang-tidy-diff.py -checks='-*,clang-analyzer-*' 
-extra-arg-clang-tidy='-warnings-as-errors=-*,clang-analyzer-*'


https://reviews.llvm.org/D112008

Files:
  clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
  clang-tools-extra/clang-tidy/tool/run-clang-tidy.py


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -104,6 +104,7 @@
   start.append('-extra-arg=%s' % arg)
   for arg in extra_arg_before:
   start.append('-extra-arg-before=%s' % arg)
+  common_clang_tidy_args += args.extra_arg_clang_tidy
   start.append('-p=' + build_path)
   if quiet:
   start.append('-quiet')
@@ -241,6 +242,9 @@
   action='append', default=[],
   help='Additional argument to prepend to the compiler '
   'command line.')
+  parser.add_argument('-extra-arg-clang-tidy', dest='extra_arg_clang_tidy',
+  action='append', default=[],
+  help='Additional argument to use with clang-tidy.')
   parser.add_argument('-quiet', action='store_true',
   help='Run clang-tidy in quiet mode')
   args = parser.parse_args()
Index: clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
===
--- clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
+++ clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
@@ -158,6 +158,9 @@
   action='append', default=[],
   help='Additional argument to prepend to the compiler '
   'command line.')
+  parser.add_argument('-extra-arg-clang-tidy', dest='extra_arg_clang_tidy',
+  action='append', default=[],
+  help='Additional argument to use with clang-tidy.')
   parser.add_argument('-quiet', action='store_true', default=False,
   help='Run clang-tidy in quiet mode')
   clang_tidy_args = []
@@ -233,6 +236,7 @@
 common_clang_tidy_args.append('-extra-arg=%s' % arg)
   for arg in args.extra_arg_before:
 common_clang_tidy_args.append('-extra-arg-before=%s' % arg)
+  common_clang_tidy_args += args.extra_arg_clang_tidy
 
   for name in lines_by_file:
 line_filter_json = json.dumps(


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -104,6 +104,7 @@
   start.append('-extra-arg=%s' % arg)
   for arg in extra_arg_before:
   start.append('-extra-arg-before=%s' % arg)
+  common_clang_tidy_args += args.extra_arg_clang_tidy
   start.append('-p=' + build_path)
   if quiet:
   start.append('-quiet')
@@ -241,6 +242,9 @@
   action='append', default=[],
   help='Additional argument to prepend to the compiler '
   'command line.')
+  parser.add_argument('-extra-arg-clang-tidy', dest='extra_arg_clang_tidy',
+  action='append', default=[],
+  help='Additional argument to use with clang-tidy.')
   parser.add_argument('-quiet', action='store_true',
   help='Run clang-tidy in quiet mode')
   args = parser.parse_args()
Index: clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
===
--- clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
+++ clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
@@ -158,6 +158,9 @@
   action='append', default=[],
   help='Additional argument to prepend to the compiler '
   'command line.')
+  parser.add_argument('-extra-arg-clang-tidy', dest='extra_arg_clang_tidy',
+  action='append', default=[],
+  help='Additional argument to use with clang-tidy.')
   parser.add_argument('-quiet', action='store_true', default=False,
   help='Run clang-tidy in quiet mode')
   clang_tidy_args = []
@@ -233,6 +236,7 @@
 common_clang_tidy_args.append('-extra-arg=%s' % arg)
   for arg in args.extra_arg_before:
 common_clang_tidy_args.append('-extra-arg-before=%s' % arg)
+  common_clang_tidy_args += args.extra_arg_clang_tidy
 
   for name in lines_by_file:
 line_filter_json = json.dumps(

[PATCH] D111870: [clangd] Add a way to enable IncludeCleaner through config

2021-10-18 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 380426.
kbobyrev added a comment.

Fix the warning range.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111870

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp

Index: clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
@@ -67,6 +67,7 @@
 CheckOptions:
   IgnoreMacros: true
   example-check.ExampleOption: 0
+  IncludeCleaner: UnusedHeaders
   )yaml";
   auto Results = Fragment::parseYAML(YAML, "config.yaml", Diags.callback());
   EXPECT_THAT(Diags.Diagnostics, IsEmpty());
@@ -83,6 +84,8 @@
   EXPECT_THAT(Results[3].Diagnostics.ClangTidy.CheckOptions,
   ElementsAre(PairVal("IgnoreMacros", "true"),
   PairVal("example-check.ExampleOption", "0")));
+  EXPECT_TRUE(Results[3].Diagnostics.IncludeCleaner);
+  EXPECT_EQ("UnusedHeaders", *Results[3].Diagnostics.IncludeCleaner.getValue());
 }
 
 TEST(ParseYAML, Locations) {
Index: clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
@@ -244,6 +244,25 @@
   }
 }
 
+TEST_F(ConfigCompileTests, DiagnosticsIncludeCleaner) {
+  // Defaults to None.
+  EXPECT_TRUE(compileAndApply());
+  EXPECT_EQ(Conf.Diagnostics.IncludeCleaner,
+Config::IncludeCleanerPolicy::None);
+
+  Frag = {};
+  Frag.Diagnostics.IncludeCleaner.emplace("None");
+  EXPECT_TRUE(compileAndApply());
+  EXPECT_EQ(Conf.Diagnostics.IncludeCleaner,
+Config::IncludeCleanerPolicy::None);
+
+  Frag = {};
+  Frag.Diagnostics.IncludeCleaner.emplace("UnusedHeaders");
+  EXPECT_TRUE(compileAndApply());
+  EXPECT_EQ(Conf.Diagnostics.IncludeCleaner,
+Config::IncludeCleanerPolicy::UnusedHeaders);
+}
+
 TEST_F(ConfigCompileTests, DiagnosticSuppression) {
   Frag.Diagnostics.Suppress.emplace_back("bugprone-use-after-move");
   Frag.Diagnostics.Suppress.emplace_back("unreachable-code");
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -18,6 +18,7 @@
 #include "FeatureModule.h"
 #include "Headers.h"
 #include "HeuristicResolver.h"
+#include "IncludeCleaner.h"
 #include "IncludeFixer.h"
 #include "Preamble.h"
 #include "SourceCode.h"
@@ -342,6 +343,7 @@
   llvm::Optional FixIncludes;
   // No need to run clang-tidy or IncludeFixerif we are not going to surface
   // diagnostics.
+  const Config &Cfg = Config::current();
   if (PreserveDiags) {
 trace::Span Tracer("ClangTidyInit");
 tidy::ClangTidyOptions ClangTidyOpts =
@@ -366,7 +368,6 @@
   Check->registerMatchers(&CTFinder);
 }
 
-const Config &Cfg = Config::current();
 ASTDiags.setLevelAdjuster([&](DiagnosticsEngine::Level DiagLevel,
   const clang::Diagnostic &Info) {
   if (Cfg.Diagnostics.SuppressAll ||
@@ -515,10 +516,16 @@
   Diags->insert(Diags->end(), D.begin(), D.end());
 }
   }
-  return ParsedAST(Inputs.Version, std::move(Preamble), std::move(Clang),
+  ParsedAST Result(Inputs.Version, std::move(Preamble), std::move(Clang),
std::move(Action), std::move(Tokens), std::move(Macros),
std::move(Marks), std::move(ParsedDecls), std::move(Diags),
std::move(Includes), std::move(CanonIncludes));
+  if (Result.Diags && Cfg.Diagnostics.IncludeCleaner ==
+  Config::IncludeCleanerPolicy::UnusedHeaders)
+for (const auto &D :
+ issueUnusedIncludesDiagnostics(Result, Inputs.Contents))
+  Result.Diags->push_back(D);
+  return Result;
 }
 
 ParsedAST::ParsedAST(ParsedAST &&Other) = default;
Index: clang-tools-extra/clangd/IncludeCleaner.h
===
--- clang-tools-extra/clangd/IncludeCleaner.h
+++ clang-tools-extra/clangd/IncludeCleaner.h
@@ -63,6 +63,9 @@
 
 std::vector computeUnusedIncludes(ParsedAST &AST);
 
+std::vector issueUnusedIncludesDiagnostics(ParsedAST &AST,
+ StringRef Code);
+
 } // namespace clangd
 } // namespace clang
 
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===

[PATCH] D111534: [analyzer][NFC] Refactor CallEvent::isCalled()

2021-10-18 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

Thank you for adding me. I'll make a deeper review later.




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h:1289
+  /// E.g. { "std", "vector", "data" } -> "vector", "std"
+  auto begin_qualified_name_parts() const {
+return std::next(QualifiedName.rbegin());

What rules did you use to name this functions? It seems that it goes against [[ 
https://llvm.org/docs/CodingStandards.html#name-types-functions-variables-and-enumerators-properly
 | LLVM naming rules]].



Comment at: clang/lib/StaticAnalyzer/Core/CallEvent.cpp:336-352
+  const auto ExactMatchArgAndParamCounts =
+  [](const CallEvent &Call, const CallDescription &CD) -> bool {
+const bool ArgsMatch =
+!CD.RequiredArgs || CD.RequiredArgs == Call.getNumArgs();
+const bool ParamsMatch =
+!CD.RequiredParams || CD.RequiredParams == Call.parameters().size();
+return ArgsMatch && ParamsMatch;

Can we move these lambdas in separate functions? IMO it could make the code 
even more readable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111534

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


[PATCH] D111909: [clang-tidy] DefinitionsInHeadersCheck: Added option for checking C Code

2021-10-18 Thread Max Schroetter via Phabricator via cfe-commits
schrc3b6 added a comment.

In D111909#3069668 , @whisperity 
wrote:

> Will `int I;` being in a header, with no initialiser, be caught?

Currently it will be caught.

  1 warning generated.
  ./foo.h:1:5: warning: variable 'i' defined in a header file; variable 
definitions in header files can lead to ODR violations 
[misc-definitions-in-headers]
  int i;

I guess you don't want that to be cought if it is actually a tentative 
definition. If I remember correctly for clang and gcc -fno-common is the 
default.
I think we could do one of two things here either create no warning if there is 
a VarDelc without initialization or we could try to detect common linkage.
I will have a look if I can detect a change from inside the checker if the 
linkage of the variable changes via the fcommon compiler flag.

> It would be interesting to add a test for this.

I will do so.

Thanks for the feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111909

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


[PATCH] D112008: Add -extra-arg-clang-tidy to {clang-tidy-diff,run-clang-tidy}.py

2021-10-18 Thread Xavier Roche via Phabricator via cfe-commits
Xavier updated this revision to Diff 380429.

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

https://reviews.llvm.org/D112008

Files:
  clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
  clang-tools-extra/clang-tidy/tool/run-clang-tidy.py


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -104,6 +104,7 @@
   start.append('-extra-arg=%s' % arg)
   for arg in extra_arg_before:
   start.append('-extra-arg-before=%s' % arg)
+  start += args.extra_arg_clang_tidy
   start.append('-p=' + build_path)
   if quiet:
   start.append('-quiet')
@@ -241,6 +242,9 @@
   action='append', default=[],
   help='Additional argument to prepend to the compiler '
   'command line.')
+  parser.add_argument('-extra-arg-clang-tidy', dest='extra_arg_clang_tidy',
+  action='append', default=[],
+  help='Additional argument to use with clang-tidy.')
   parser.add_argument('-quiet', action='store_true',
   help='Run clang-tidy in quiet mode')
   args = parser.parse_args()
Index: clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
===
--- clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
+++ clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
@@ -158,6 +158,9 @@
   action='append', default=[],
   help='Additional argument to prepend to the compiler '
   'command line.')
+  parser.add_argument('-extra-arg-clang-tidy', dest='extra_arg_clang_tidy',
+  action='append', default=[],
+  help='Additional argument to use with clang-tidy.')
   parser.add_argument('-quiet', action='store_true', default=False,
   help='Run clang-tidy in quiet mode')
   clang_tidy_args = []
@@ -233,6 +236,7 @@
 common_clang_tidy_args.append('-extra-arg=%s' % arg)
   for arg in args.extra_arg_before:
 common_clang_tidy_args.append('-extra-arg-before=%s' % arg)
+  common_clang_tidy_args += args.extra_arg_clang_tidy
 
   for name in lines_by_file:
 line_filter_json = json.dumps(


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -104,6 +104,7 @@
   start.append('-extra-arg=%s' % arg)
   for arg in extra_arg_before:
   start.append('-extra-arg-before=%s' % arg)
+  start += args.extra_arg_clang_tidy
   start.append('-p=' + build_path)
   if quiet:
   start.append('-quiet')
@@ -241,6 +242,9 @@
   action='append', default=[],
   help='Additional argument to prepend to the compiler '
   'command line.')
+  parser.add_argument('-extra-arg-clang-tidy', dest='extra_arg_clang_tidy',
+  action='append', default=[],
+  help='Additional argument to use with clang-tidy.')
   parser.add_argument('-quiet', action='store_true',
   help='Run clang-tidy in quiet mode')
   args = parser.parse_args()
Index: clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
===
--- clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
+++ clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
@@ -158,6 +158,9 @@
   action='append', default=[],
   help='Additional argument to prepend to the compiler '
   'command line.')
+  parser.add_argument('-extra-arg-clang-tidy', dest='extra_arg_clang_tidy',
+  action='append', default=[],
+  help='Additional argument to use with clang-tidy.')
   parser.add_argument('-quiet', action='store_true', default=False,
   help='Run clang-tidy in quiet mode')
   clang_tidy_args = []
@@ -233,6 +236,7 @@
 common_clang_tidy_args.append('-extra-arg=%s' % arg)
   for arg in args.extra_arg_before:
 common_clang_tidy_args.append('-extra-arg-before=%s' % arg)
+  common_clang_tidy_args += args.extra_arg_clang_tidy
 
   for name in lines_by_file:
 line_filter_json = json.dumps(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D112008: Add -extra-arg-clang-tidy to {clang-tidy-diff,run-clang-tidy}.py

2021-10-18 Thread Xavier Roche via Phabricator via cfe-commits
Xavier updated this revision to Diff 380431.

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

https://reviews.llvm.org/D112008

Files:
  clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
  clang-tools-extra/clang-tidy/tool/run-clang-tidy.py


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -81,8 +81,8 @@
 
 def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
 header_filter, allow_enabling_alpha_checkers,
-extra_arg, extra_arg_before, quiet, config,
-line_filter):
+extra_arg, extra_arg_before, extra_arg_clang_tidy,
+quiet, config, line_filter):
   """Gets a command line for clang-tidy."""
   start = [clang_tidy_binary, '--use-color']
   if allow_enabling_alpha_checkers:
@@ -104,6 +104,7 @@
   start.append('-extra-arg=%s' % arg)
   for arg in extra_arg_before:
   start.append('-extra-arg-before=%s' % arg)
+  start += extra_arg_clang_tidy
   start.append('-p=' + build_path)
   if quiet:
   start.append('-quiet')
@@ -168,7 +169,8 @@
  tmpdir, build_path, args.header_filter,
  args.allow_enabling_alpha_checkers,
  args.extra_arg, args.extra_arg_before,
- args.quiet, args.config, args.line_filter)
+ args.extra_arg_clang_tidy, args.quiet,
+ args.config, args.line_filter)
 
 proc = subprocess.Popen(invocation, stdout=subprocess.PIPE, 
stderr=subprocess.PIPE)
 output, err = proc.communicate()
@@ -241,6 +243,9 @@
   action='append', default=[],
   help='Additional argument to prepend to the compiler '
   'command line.')
+  parser.add_argument('-extra-arg-clang-tidy', dest='extra_arg_clang_tidy',
+  action='append', default=[],
+  help='Additional argument to use with clang-tidy.')
   parser.add_argument('-quiet', action='store_true',
   help='Run clang-tidy in quiet mode')
   args = parser.parse_args()
Index: clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
===
--- clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
+++ clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
@@ -158,6 +158,9 @@
   action='append', default=[],
   help='Additional argument to prepend to the compiler '
   'command line.')
+  parser.add_argument('-extra-arg-clang-tidy', dest='extra_arg_clang_tidy',
+  action='append', default=[],
+  help='Additional argument to use with clang-tidy.')
   parser.add_argument('-quiet', action='store_true', default=False,
   help='Run clang-tidy in quiet mode')
   clang_tidy_args = []
@@ -233,6 +236,7 @@
 common_clang_tidy_args.append('-extra-arg=%s' % arg)
   for arg in args.extra_arg_before:
 common_clang_tidy_args.append('-extra-arg-before=%s' % arg)
+  common_clang_tidy_args += args.extra_arg_clang_tidy
 
   for name in lines_by_file:
 line_filter_json = json.dumps(


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -81,8 +81,8 @@
 
 def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
 header_filter, allow_enabling_alpha_checkers,
-extra_arg, extra_arg_before, quiet, config,
-line_filter):
+extra_arg, extra_arg_before, extra_arg_clang_tidy,
+quiet, config, line_filter):
   """Gets a command line for clang-tidy."""
   start = [clang_tidy_binary, '--use-color']
   if allow_enabling_alpha_checkers:
@@ -104,6 +104,7 @@
   start.append('-extra-arg=%s' % arg)
   for arg in extra_arg_before:
   start.append('-extra-arg-before=%s' % arg)
+  start += extra_arg_clang_tidy
   start.append('-p=' + build_path)
   if quiet:
   start.append('-quiet')
@@ -168,7 +169,8 @@
  tmpdir, build_path, args.header_filter,
  args.allow_enabling_alpha_checkers,
  args.extra_arg, args.extra_arg_before,
- args.quiet, args.config, args.line_filter)
+ args.extra_arg_clang_tidy, args.quiet,
+

[PATCH] D111909: [clang-tidy] DefinitionsInHeadersCheck: Added option for checking C Code

2021-10-18 Thread Whisperity via Phabricator via cfe-commits
whisperity added a comment.

In D111909#3070593 , @schrc3b6 wrote:

> I guess you don't want that to be cought if it is actually a tentative 
> definition. If I remember correctly for clang and gcc -fno-common is the 
> default.
> I think we could do one of two things here either create no warning if there 
> is a VarDelc without initialization or we could try to detect common linkage.
> I will have a look if I can detect a change from inside the checker if the 
> linkage of the variable changes via the fcommon compiler flag.

My personal belief after having encountered common linkage is that it is 
disgusting and it's good that Clang doesn't support them (by default).

But I do not have any stake or practical experience with working long term on 
//C// programs to have a well-educated opinion on this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111909

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


[PATCH] D112008: Add -extra-arg-clang-tidy to {clang-tidy-diff,run-clang-tidy}.py

2021-10-18 Thread Xavier Roche via Phabricator via cfe-commits
Xavier added a comment.

**Note**: manually tested the two scripts;

- For `clang-tidy-diff.py`

  git diff -U0 --no-prefix --no-color $(git merge-base origin/master 
HEAD)..HEAD \
  | ~/git/llvm-project/clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py 
-quiet -clang-tidy-binary clang-tidy-12 -path=build -j8 \
  -checks='-*,clang-analyzer-*' 
-extra-arg-clang-tidy='-warnings-as-errors=-*,clang-analyzer-*'



- For `run-clang-tidy.py`

  ~/git/llvm-project/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py \
  -checks='-*,clang-analyzer-*' -clang-tidy-binary clang-tidy-12 -p build 
-extra-arg-clang-tidy='-warnings-as-errors=-*,clang-analyzer-*' 


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

https://reviews.llvm.org/D112008

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


[PATCH] D112008: Add -extra-arg-clang-tidy to {clang-tidy-diff,run-clang-tidy}.py

2021-10-18 Thread Xavier Roche via Phabricator via cfe-commits
Xavier updated this revision to Diff 380436.

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

https://reviews.llvm.org/D112008

Files:
  clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
  clang-tools-extra/clang-tidy/tool/run-clang-tidy.py


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -81,8 +81,8 @@
 
 def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
 header_filter, allow_enabling_alpha_checkers,
-extra_arg, extra_arg_before, quiet, config,
-line_filter):
+extra_arg, extra_arg_before, extra_arg_clang_tidy,
+quiet, config, line_filter):
   """Gets a command line for clang-tidy."""
   start = [clang_tidy_binary, '--use-color']
   if allow_enabling_alpha_checkers:
@@ -109,6 +109,7 @@
   start.append('-quiet')
   if config:
   start.append('-config=' + config)
+  start += extra_arg_clang_tidy
   start.append(f)
   return start
 
@@ -168,7 +169,8 @@
  tmpdir, build_path, args.header_filter,
  args.allow_enabling_alpha_checkers,
  args.extra_arg, args.extra_arg_before,
- args.quiet, args.config, args.line_filter)
+ args.extra_arg_clang_tidy, args.quiet,
+ args.config, args.line_filter)
 
 proc = subprocess.Popen(invocation, stdout=subprocess.PIPE, 
stderr=subprocess.PIPE)
 output, err = proc.communicate()
@@ -241,6 +243,9 @@
   action='append', default=[],
   help='Additional argument to prepend to the compiler '
   'command line.')
+  parser.add_argument('-extra-arg-clang-tidy', dest='extra_arg_clang_tidy',
+  action='append', default=[],
+  help='Additional argument to use with clang-tidy.')
   parser.add_argument('-quiet', action='store_true',
   help='Run clang-tidy in quiet mode')
   args = parser.parse_args()
Index: clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
===
--- clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
+++ clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
@@ -158,6 +158,9 @@
   action='append', default=[],
   help='Additional argument to prepend to the compiler '
   'command line.')
+  parser.add_argument('-extra-arg-clang-tidy', dest='extra_arg_clang_tidy',
+  action='append', default=[],
+  help='Additional argument to use with clang-tidy.')
   parser.add_argument('-quiet', action='store_true', default=False,
   help='Run clang-tidy in quiet mode')
   clang_tidy_args = []
@@ -233,6 +236,7 @@
 common_clang_tidy_args.append('-extra-arg=%s' % arg)
   for arg in args.extra_arg_before:
 common_clang_tidy_args.append('-extra-arg-before=%s' % arg)
+  common_clang_tidy_args += args.extra_arg_clang_tidy
 
   for name in lines_by_file:
 line_filter_json = json.dumps(


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -81,8 +81,8 @@
 
 def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
 header_filter, allow_enabling_alpha_checkers,
-extra_arg, extra_arg_before, quiet, config,
-line_filter):
+extra_arg, extra_arg_before, extra_arg_clang_tidy,
+quiet, config, line_filter):
   """Gets a command line for clang-tidy."""
   start = [clang_tidy_binary, '--use-color']
   if allow_enabling_alpha_checkers:
@@ -109,6 +109,7 @@
   start.append('-quiet')
   if config:
   start.append('-config=' + config)
+  start += extra_arg_clang_tidy
   start.append(f)
   return start
 
@@ -168,7 +169,8 @@
  tmpdir, build_path, args.header_filter,
  args.allow_enabling_alpha_checkers,
  args.extra_arg, args.extra_arg_before,
- args.quiet, args.config, args.line_filter)
+ args.extra_arg_clang_tidy, args.quiet,
+ args.config, args.line_filter)
 
 proc = subprocess.Popen(invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 output, err = proc.communicate()

[clang] 1fb24fe - Reland [clang] Pass -clear-ast-before-backend in Clang::ConstructJob()

2021-10-18 Thread Arthur Eubanks via cfe-commits

Author: Arthur Eubanks
Date: 2021-10-18T09:08:16-07:00
New Revision: 1fb24fe85a19ae71b00875ff6c96ef1831dcf7e3

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

LOG: Reland [clang] Pass -clear-ast-before-backend in Clang::ConstructJob()

This clears the memory used for the Clang AST before we run LLVM passes.

https://llvm-compile-time-tracker.com/compare.php?from=d0a5f61c4f6fccec87fd5207e3fcd9502dd59854&to=b7437fee79e04464dd968e1a29185495f3590481&stat=max-rss
shows significant memory savings with no slowdown (in fact -O0 slightly speeds 
up).

For more background, see
https://lists.llvm.org/pipermail/cfe-dev/2021-September/068930.html.

Turn this off for the interpreter since it does codegen multiple times.

Relanding with fix for -print-stats: D111973

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Interpreter/Interpreter.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index d2c08412d5932..83afbc3952d84 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4660,6 +4660,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   // cleanup.
   if (!C.isForDiagnostics())
 CmdArgs.push_back("-disable-free");
+  CmdArgs.push_back("-clear-ast-before-backend");
 
 #ifdef NDEBUG
   const bool IsAssertBuild = false;

diff  --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 02b3025297b67..d14940d2e1321 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -113,6 +113,10 @@ CreateCI(const llvm::opt::ArgStringList &Argv) {
 
   Clang->getTarget().adjust(Clang->getDiagnostics(), Clang->getLangOpts());
 
+  // Don't clear the AST before backend codegen since we do codegen multiple
+  // times, reusing the same AST.
+  Clang->getCodeGenOpts().ClearASTBeforeBackend = false;
+
   return std::move(Clang);
 }
 



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


[PATCH] D112013: [clang][ASTImporter] Fix for importing functions with EST_Unevaluated prototype.

2021-10-18 Thread Balázs Kéri via Phabricator via cfe-commits
balazske created this revision.
Herald added subscribers: steakhal, whisperity, martong, teemperor, gamesh411, 
Szelethus, dkrupp.
Herald added a reviewer: a.sidorin.
Herald added a reviewer: shafik.
balazske requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Fix for importing functions where the TypeSourceInfo is set and the
exception specification information contains reference to the function
declaration itself.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112013

Files:
  clang/lib/AST/ASTImporter.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -6145,6 +6145,57 @@
 2u);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportTypeSourceInfoWithExceptionSpecUnevaluated) {
+  // This code results in a lambda with implicit constructor.
+  // The constructor should have a "unevaluated" exception specification in its
+  // prototype information.
+  // In some cases the constructor has a TypeSourceInfo that contains the
+  // function's prototype, but often the TypeSourceInfo is not set
+  // (like in the code used here).
+  // The test sets the TypeSourceInfo artifically to simulate a case when it is
+  // set. The test verifies that AST import of such AST does not crash.
+  // (Here the function's TypeSourceInfo references the function itself in the
+  // exception information of the prototype.)
+  // A lambda and implicit constructor of it is used because the problem was
+  // encountered in a similar real code.
+  Decl *FromTU =
+  getTuDecl("void f() { auto X = [](){}; }", Lang_CXX11, "input0.cc");
+
+  CXXRecordDecl *FromL = FirstDeclMatcher()
+ .match(FromTU, lambdaExpr())
+ ->getLambdaClass();
+
+  CXXConstructorDecl *FromCtor = *FromL->ctor_begin();
+  QualType FromTy = FromCtor->getType();
+  const auto *FromFPT = FromTy->getAs();
+  ASSERT_TRUE(FromFPT);
+  FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
+  // If type is EST_Unevaluated, SourceDecl should be set to the parent decl.
+  EXPECT_EQ(FromEPI.ExceptionSpec.Type, EST_Unevaluated);
+  EXPECT_EQ(FromEPI.ExceptionSpec.SourceDecl, FromCtor);
+
+  // No TypeSourceInfo for the constructor.
+  ASSERT_FALSE(FromCtor->getTypeSourceInfo());
+  // Set a TypeSourceInfo for the function, this state may occur in reality.
+  TypeSourceInfo *FromTSI = FromTU->getASTContext().getTrivialTypeSourceInfo(
+  FromTy, FromCtor->getBeginLoc());
+  FromCtor->setTypeSourceInfo(FromTSI);
+
+  // Import it.
+  auto ToL = Import(FromL, Lang_CXX11);
+
+  // Check if the import was correct.
+  CXXConstructorDecl *ToCtor = *ToL->ctor_begin();
+  const auto *ToFPT = ToCtor->getType()->getAs();
+  ASSERT_TRUE(FromFPT);
+  FunctionProtoType::ExtProtoInfo ToEPI = ToFPT->getExtProtoInfo();
+  EXPECT_EQ(ToEPI.ExceptionSpec.Type, EST_Unevaluated);
+  EXPECT_EQ(ToEPI.ExceptionSpec.SourceDecl, ToCtor);
+  EXPECT_TRUE(ToCtor->getTypeSourceInfo());
+  EXPECT_EQ(ToCtor->getTypeSourceInfo()->getType().getTypePtr(), ToFPT);
+}
+
 struct ImportAutoFunctions : ASTImporterOptionSpecificTestBase {};
 
 TEST_P(ImportAutoFunctions, ReturnWithTypedefDeclaredInside) {
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -3422,11 +3422,14 @@
 return std::move(Err);
 
   QualType FromTy = D->getType();
+  TypeSourceInfo *FromTSI = D->getTypeSourceInfo();
   // Set to true if we do not import the type of the function as is. There are
   // cases when the original type would result in an infinite recursion during
   // the import. To avoid an infinite recursion when importing, we create the
   // FunctionDecl with a simplified function type and update it only after the
   // relevant AST nodes are already imported.
+  // The type is related to TypeSourceInfo (it references the type), so we must
+  // do the same with TypeSourceInfo.
   bool UsedDifferentProtoType = false;
   if (const auto *FromFPT = FromTy->getAs()) {
 QualType FromReturnTy = FromFPT->getReturnType();
@@ -3453,11 +3456,13 @@
 }
 FromTy = Importer.getFromContext().getFunctionType(
 FromReturnTy, FromFPT->getParamTypes(), FromEPI);
+FromTSI = Importer.getFromContext().getTrivialTypeSourceInfo(
+FromTy, D->getBeginLoc());
   }
 
   Error Err = Error::success();
   auto T = importChecked(Err, FromTy);
-  auto TInfo = importChecked(Err, D->getTypeSourceInfo());
+  auto TInfo = importChecked(Err, FromTSI);
   auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
   auto ToEndLoc = importChecked(Err, D->getEndLoc());
   auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
@@ -3

[PATCH] D74531: [WebAssembly] Emit clangast in custom section aligned by 4 bytes

2021-10-18 Thread Sam Clegg via Phabricator via cfe-commits
sbc100 added inline comments.



Comment at: llvm/lib/MC/WasmObjectWriter.cpp:374
+  // Custom sections in wasm also have a string identifier with extra paddings
+  // for alignment for special sections.
+  // TODO: support section alignment at asm and llvm level?

I would leave the first sentence alone which that applies to all custom 
sections.The second part of this sentence (the new part) is maybe not 
needed since you have a comment already on line 378.

Also, how about keeping the simpler form in the default case, and putting this 
new code in a new method. e.g.:

```
if (Name != "__clangast") {
  writeString(Name);
} else {
  writeStringWithAlignment(Name, 4);
}
```

Then the entire new method can be marked with the TODO to remove it if/when we 
change the section mapping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D74531

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


[PATCH] D106681: [analyzer][NFC] Move a block from `getBindingForElement` to separate functions

2021-10-18 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 380441.
ASDenysPetrov retitled this revision from "[analyzer] Retrieve a value from 
list initialization of constant multi-dimensional array." to "[analyzer][NFC] 
Move a block from `getBindingForElement` to separate functions".
ASDenysPetrov edited the summary of this revision.
ASDenysPetrov added reviewers: martong, steakhal.
ASDenysPetrov set the repository for this revision to rG LLVM Github Monorepo.
ASDenysPetrov added a comment.

@martong
Please, look. As you suggested in D111542#inline-1064497 
 I made an intermediate patch 
making next patches easer for review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106681

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp

Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -437,6 +437,10 @@
 
   RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B,
 const SubRegion *R);
+  Optional getConstantValFromConstArrayInitializer(
+  RegionBindingsConstRef B, const VarRegion *VR, const ElementRegion *R);
+  Optional getSValFromInitListExpr(const InitListExpr *ILE,
+ uint64_t Offset, QualType ElemT);
 
 public: // Part of public interface to class.
 
@@ -1625,6 +1629,93 @@
   return Result;
 }
 
+Optional RegionStoreManager::getConstantValFromConstArrayInitializer(
+RegionBindingsConstRef B, const VarRegion *VR, const ElementRegion *R) {
+  assert(R && VR && "Regions should not be null");
+
+  // Array should be immutable.
+  const VarDecl *VD = VR->getDecl();
+  if (!VD->getType().isConstQualified() &&
+  !R->getElementType().isConstQualified() &&
+  (!B.isMainAnalysis() || !VD->hasGlobalStorage()))
+return None;
+
+  // Array's declaration should have ConstantArrayType type.
+  const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(VD->getType());
+  if (!CAT)
+return None;
+
+  // Array should be one-dimensional.
+  // TODO: Support multidimensional array.
+  if (isa(CAT->getElementType())) // is multidimensional
+return None;
+
+  // Array's offset should be a concrete value.
+  // Return Unknown value if symbolic index presented.
+  // FIXME: We also need to take ElementRegions with symbolic
+  // indexes into account.
+  const auto OffsetVal = R->getIndex().getAs();
+  if (!OffsetVal.hasValue())
+return UnknownVal();
+
+  // Check offset for being out of bounds.
+  // C++20 [expr.add] 7.6.6.4 (excerpt):
+  //   If P points to an array element i of an array object x with n
+  //   elements, where i < 0 or i > n, the behavior is undefined.
+  //   Dereferencing is not allowed on the "one past the last
+  //   element", when i == n.
+  // Example:
+  //   const int arr[4] = {1, 2};
+  //   const int *ptr = arr;
+  //   int x0 = ptr[0];  // 1
+  //   int x1 = ptr[1];  // 2
+  //   int x2 = ptr[2];  // 0
+  //   int x3 = ptr[3];  // 0
+  //   int x4 = ptr[4];  // UB
+  //   int x5 = ptr[-1]; // UB
+  const llvm::APSInt &OffsetInt = OffsetVal->getValue();
+  const auto Offset = static_cast(OffsetInt.getExtValue());
+  // Use `getZExtValue` because array extent can not be negative.
+  const uint64_t Extent = CAT->getSize().getZExtValue();
+  // Check for `OffsetInt < 0` but NOT for `Offset < 0`, because `OffsetInt`
+  // CAN be negative, but `Offset` can NOT, because `Offset` is an uint64_t.
+  if (OffsetInt < 0 || Offset >= Extent)
+return UndefinedVal();
+  // From here `Offset` is in the bounds.
+
+  // Array's declaration should have an initializer.
+  const Expr *Init = VD->getAnyInitializer();
+  if (!Init)
+return None;
+
+  // Handle InitListExpr.
+  if (const auto *ILE = dyn_cast(Init))
+return getSValFromInitListExpr(ILE, Offset, R->getElementType());
+
+  // FIXME: Handle StringLiteral.
+
+  // FIXME: Handle CompoundLiteralExpr.
+
+  return None;
+}
+
+Optional
+RegionStoreManager::getSValFromInitListExpr(const InitListExpr *ILE,
+uint64_t Offset, QualType ElemT) {
+  assert(ILE && "InitListExpr should not be null");
+
+  // C++20 [expr.add] 9.4.17.5 (excerpt):
+  //   i-th array element is value-initialized for each k < i ≤ n,
+  //   where k is an expression-list size and n is an array extent.
+  if (Offset >= ILE->getNumInits())
+return svalBuilder.makeZeroVal(ElemT);
+
+  // Return a constant value, if it is presented.
+  // FIXME: Support other SVals.
+  const Expr *E = ILE->getInit(Offset);
+  return svalBuilder.getConstantVal(E);
+}
+
 SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B,
   const ElementRegion* R) {
   // Check if the region ha

[PATCH] D111534: [analyzer][NFC] Refactor CallEvent::isCalled()

2021-10-18 Thread Balázs Benics via Phabricator via cfe-commits
steakhal marked 3 inline comments as done.
steakhal added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h:1289
+  /// E.g. { "std", "vector", "data" } -> "vector", "std"
+  auto begin_qualified_name_parts() const {
+return std::next(QualifiedName.rbegin());

ASDenysPetrov wrote:
> What rules did you use to name this functions? It seems that it goes against 
> [[ 
> https://llvm.org/docs/CodingStandards.html#name-types-functions-variables-and-enumerators-properly
>  | LLVM naming rules]].
Not exactly. There is an exception for `begin()` and `end()`.
That being said, `begin` should have been a suffix instead of being a prefix.
But I still like this more :D



Comment at: clang/lib/StaticAnalyzer/Core/CallEvent.cpp:336-352
+  const auto ExactMatchArgAndParamCounts =
+  [](const CallEvent &Call, const CallDescription &CD) -> bool {
+const bool ArgsMatch =
+!CD.RequiredArgs || CD.RequiredArgs == Call.getNumArgs();
+const bool ParamsMatch =
+!CD.RequiredParams || CD.RequiredParams == Call.parameters().size();
+return ArgsMatch && ParamsMatch;

ASDenysPetrov wrote:
> Can we move these lambdas in separate functions? IMO it could make the code 
> even more readable.
We could, but I'm not planning to move them.
That would be more appropriate to move all `CallDescription` implementation to 
its own translation unit.



Comment at: clang/lib/StaticAnalyzer/Core/CallEvent.cpp:349
+[](const DeclContext *Ctx) -> const DeclContext * {
+  while (Ctx && !isa(Ctx) && !isa(Ctx))
+Ctx = Ctx->getParent();

martong wrote:
> steakhal wrote:
> > TBH I don't understand why doesn't `isa()` work. 
> > I could have used this variadic form so many times.
> > WDYT, should I propose turning `isa` and `isa_and_nonnull`˙into variadic 
> > functions?
> > TBH I don't understand why doesn't `isa()` work. 
> > I could have used this variadic form so many times.
> > WDYT, should I propose turning `isa` and `isa_and_nonnull`˙into variadic 
> > functions?
> 
> Yes, that's a good idea!
Actually, it's already variadic :D
I created a follow-up patch for addressing similar issues in D111982.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111534

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


[PATCH] D111975: [clang-format] [PR52015] clang-format should put __attribute__((foo)) on its own line before @interface / @implementation / @protocol

2021-10-18 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton accepted this revision.
benhamilton added a comment.

Thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111975

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


[PATCH] D111870: [clangd] Add a way to enable IncludeCleaner through config

2021-10-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/Config.h:89
 
   /// Controls warnings and errors when parsing code.
+  enum IncludeCleanerPolicy { UnusedHeaders, None };

you've accidentally split this comment from its decl



Comment at: clang-tools-extra/clangd/Config.h:90
   /// Controls warnings and errors when parsing code.
+  enum IncludeCleanerPolicy { UnusedHeaders, None };
   struct {

structure, as discussed offline...

"include cleaner" refers to a set of features to do with header hygiene, 
related but I think we still want to configure them individually.

"Unused headers" is the feature we're trying to configure, so I think it's a 
key rather than a value. Its value could be a boolean, (and configure other 
aspects separately), or we could make it an enum so we can choose a policy at 
the same time.
My suspicion is that the major knob here is strictness: do we warn when a 
header doesn't *directly* provide any used symbols, or also indirectly?

So I'd probably call this `UnusedInclude: Strict` 



Comment at: clang-tools-extra/clangd/Config.h:94
 llvm::StringSet<> Suppress;
+IncludeCleanerPolicy IncludeCleaner = None;
 

don't group with the generic suppression bits



Comment at: clang-tools-extra/clangd/ConfigFragment.h:213
 
+/// Valid values are:
+/// - UnusedHeaders

This is where the documentation for the feature goes :-)



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:215
+D.Message = "Included header is unused";
+D.Name = "clangd-include-cleaner";
+// FIXME: This range should be the whole line with target #include.

Source should be `Clangd` I think (our first?).

Name should be something like "unused-include": this doesn't need to echo the 
tool name.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:216
+D.Name = "clangd-include-cleaner";
+// FIXME: This range should be the whole line with target #include.
+D.Range.start.line = Inc->HashLine;

remove FIXEDME



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:221
+D.Range.end.character =
+Code.drop_front(Inc->HashOffset).find_first_of("\n\1A");
+D.Fixes.emplace_back();

This doesn't handle hitting EOF correctly, and also gets encodings wrong 
(should be UTF-16 code units, unless we're in another mode).

I think you want:
```
D.range.end.character = 
lspLength(Code.drop_front(Inc->HashOffset).take_until([](char C) { return c == 
'\n' || c == '\r'; }));
```

You could make this a function in SourceCode.h if you like.
(I'm fairly sure we're not clean when it comes to using `\r` being a line 
separator in the rest of the code BTW)



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:226
+D.Fixes.back().Edits.back().range.start.line = Inc->HashLine;
+// LSP uses [start; end) ranges: this will span the deletion range to EOL.
+D.Fixes.back().Edits.back().range.end.line = Inc->HashLine + 1;

No need to explain the ranges thing, this is ubiquitous and documented on the 
structs.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:229
+D.InsideMainFile = true;
+AST.getSourceManager();
+D.File = AST.getSourceManager()

no-op



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:230
+AST.getSourceManager();
+D.File = AST.getSourceManager()
+ .getFileEntryForID(AST.getSourceManager().getMainFileID())

don't do this in the loop



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:235
+D.Severity = DiagnosticsEngine::Warning;
+Result.push_back(std::move(D));
+  }

D.Tags.push_back(Unneccesary)

This produces nice rendering in vscode



Comment at: clang-tools-extra/clangd/IncludeCleaner.h:67
+std::vector issueUnusedIncludesDiagnostics(ParsedAST &AST,
+ StringRef Code);
+

nit: llvm::StringRef



Comment at: clang-tools-extra/clangd/ParsedAST.cpp:380
 if (IsClangTidyDiag) {
   if (Cfg.Diagnostics.Suppress.contains(CheckName))
 return DiagnosticsEngine::Ignored;

You're bypassing this logic, which is OK, but you'll need to duplicate it 
somewhere. (Probably wherever is looking at cfg anyway)



Comment at: clang-tools-extra/clangd/ParsedAST.cpp:519
   }
-  return ParsedAST(Inputs.Version, std::move(Preamble), std::move(Clang),
+  ParsedAST Result(Inputs.Version, std::move(Preamble), std::move(Clang),
std::move(Action), std::move(Tokens), std::move(Macros),

You're missing tests for this functionality



Comment at: 

[PATCH] D111863: [libunwind] Add an interface for dynamic .eh_frame registration

2021-10-18 Thread Steven Wu via Phabricator via cfe-commits
steven_wu added a comment.

I don't know enough about Dwarf unwinding but the implementation looks 
generally good. Can you please add a testcase indicating how ORCJIT is planning 
to use it?




Comment at: libunwind/src/DwarfParser.hpp:158
+   FDE_Info *fdeInfo, CIE_Info *cieInfo,
+   bool useCIEInfo = false);
   static bool parseFDEInstructions(A &addressSpace, const FDE_Info &fdeInfo,

Can you document how and when this parameter should be used?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111863

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


[PATCH] D112001: [Clang] Add min/max reduction builtins.

2021-10-18 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:16673
+  if (!VecTy)
+  if (!TyA->getAs())
+  return Diag(A->getBeginLoc(), 
diag::err_elementwise_math_invalid_arg_type_2)

Is this indented incorrectly? There appear to be 2 ifs at the same level


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112001

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


[clang] 2e4e200 - Fix a comment in SemaSYCL to make sure I can commit

2021-10-18 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2021-10-18T10:12:28-07:00
New Revision: 2e4e2004afc51303bbb8836e886363f2056d73eb

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

LOG: Fix a comment in SemaSYCL to make sure I can commit

Added: 


Modified: 
clang/lib/Sema/SemaSYCL.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaSYCL.cpp b/clang/lib/Sema/SemaSYCL.cpp
index 481725eb0924..815463307ecc 100644
--- a/clang/lib/Sema/SemaSYCL.cpp
+++ b/clang/lib/Sema/SemaSYCL.cpp
@@ -38,7 +38,7 @@ bool Sema::checkSYCLDeviceFunction(SourceLocation Loc, 
FunctionDecl *Callee) {
  "Should only be called during SYCL compilation");
   assert(Callee && "Callee may not be null.");
 
-  // Errors in unevaluated context don't need to be generated,
+  // Errors in an unevaluated context don't need to be generated,
   // so we can safely skip them.
   if (isUnevaluatedContext() || isConstantEvaluated())
 return true;



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


[PATCH] D111986: [Clang] Add elementwise abs builtin.

2021-10-18 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:3109
+  Result = Builder.CreateBinaryIntrinsic(
+  llvm::Intrinsic::abs, Op0, Builder.getFalse(), nullptr, "elt.abs");
+else

Did we discuss that this is different than __builtin_abs which is undefined for 
INT_MIN?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111986

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


[PATCH] D112019: [clang-format] [PR51412] AlignConsecutiveMacros fights with Visual Studio and resource.h

2021-10-18 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay created this revision.
MyDeveloperDay added reviewers: curdeius, HazardyKnusperkeks, krasimir.
MyDeveloperDay added projects: clang, clang-format.
MyDeveloperDay requested review of this revision.

clang-format `AlignConsecutiveMacros` feature causes real problems when using 
Win32 resource.h files via the resource editor in Visual Studio when editing RC 
files.

VS produces the following for the resource.h files

  ...
  // Microsoft Visual C++ generated include file.
  // Used by MyTest.rc
  //
  #define IDP_OLE_INIT_FAILED 100
  #define IDP_FAILED_TO_CREATE102
  #define ID_STATUSBAR_SHOW   108
  #define ID_STATUSBAR_TEXT   109

Visual Studio generates a resource.h with Alignment macros which start at 40 
characters, but `AlignConsecutiveMacros`  will determine the starting point but 
assume a minimum of 0 meaning a clang-format will result in:

  #define IDP_OLE_INIT_FAILED  100
  #define IDP_FAILED_TO_CREATE 102
  #define ID_STATUSBAR_SHOW108
  #define ID_STATUSBAR_TEXT109

This is would be good until you make a new rc file change which results in VS 
writing out the resource.h (back in its own form) - (even clang-format VS 
plugin to format on save doesn't resolve this. The writing of resource.h seems 
outside of the normal save system)

This situation is made worse, if it encounters a long symbol, in the VS case it 
treats this as a one off, but clang-format will assume this is the new minimum.

  #define IDP_OLE_INIT_FAILED 100
  #define IDP_FAILED_TO_CREATE102
  #define ID_VERYVERYVERYVERY_LONG_LONG_LONG_LONG_RESOURCE 33221
  #define ID_STATUSBAR_SHOW   108
  #define ID_STATUSBAR_TEXT   109

and will become via clang-format

  #define IDP_OLE_INIT_FAILED  100
  #define IDP_FAILED_TO_CREATE 102
  #define ID_VERYVERYVERYVERY_LONG_LONG_LONG_LONG_RESOURCE 33221
  #define ID_STATUSBAR_SHOW108
  #define ID_STATUSBAR_TEXT109

This patch contains 2 new options

1. Set the minimum to a fixed integer (which for VS should be 40), this means 
all id numbers will begin at 40
2. An option to allow very long macro names to break the Alignment, meaning the 
next line will reset back to the previous configured minimum (40 in our case)

These 2 option have functionality that could be useful on their own, however 
the goal is to allow `AlignConsecutiveMacros` to be useful for Windows Win32 
developers and minimize the clang-format changes that the RC editor causes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112019

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -14954,6 +14954,31 @@
Style));
 }
 
+TEST_F(FormatTest, AlignConsecutiveMacrosMinWidth) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
+  verifyFormat("#define a3\n"
+   "#define  4\n"
+   "#define ccc  (5)",
+   Style);
+  Style.AlignConsecutiveMacrosMinWidth = 30;
+  verifyFormat("#define a 3\n"
+   "#define   4\n"
+   "#define ccc   (5)",
+   Style);
+
+  verifyFormat("#define a 3\n"
+   "#define vveylonglonglongmacro 4\n"
+   "#define ccc   (5)",
+   Style);
+
+  Style.AlignConsecutiveMacrosIgnoreMax = true;
+  verifyFormat("#define a 3\n"
+   "#define vveylonglonglongmacro 4\n"
+   "#define ccc   (5)",
+   Style);
+}
+
 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
   FormatStyle Alignment = getLLVMStyle();
   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
@@ -18245,6 +18270,7 @@
 TEST_F(FormatTest, ParsesConfigurationBools) {
   FormatStyle Style = {};
   Style.Language = FormatStyle::LK_Cpp;
+  CHECK_PARSE_BOOL(AlignConsecutiveMacrosIgnoreMax);
   CHECK_PARSE_BOOL(AlignTrailingComments);
   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
@@ -18367,6 +18393,9 @@
   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
   AlignConsecutiveAssignments,
   FormatStyle::ACS_AcrossEmptyLinesAndComments);
+  CHECK_PARSE("AlignConsecutiveMacrosMinWidth: 32",
+  AlignConsecutiveMacrosMinWidth, 3

[PATCH] D112020: [RISCV] Use clang_builtin_alias for all RISCV vector intrinsics.

2021-10-18 Thread Craig Topper via Phabricator via cfe-commits
craig.topper created this revision.
craig.topper added reviewers: khchen, arcbbb, kito-cheng, HsiangKai, evandro.
Herald added subscribers: achieveartificialintelligence, jeroen.dobbelaere, 
StephenFan, vkmr, frasercrmck, luismarques, apazos, sameer.abuasal, s.egerton, 
Jim, benna, psnobl, jocewei, PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, 
edward-jones, zzheng, jrtc27, shiva0217, niosHD, sabuasal, simoncook, 
johnrusso, rbar, asb.
craig.topper requested review of this revision.
Herald added a subscriber: MaskRay.
Herald added a project: clang.

Previously we used builtin_alias for overloaded intrinsics, but
macros for the non-overloaded version. This patch changes the
non-overloaded versions to also use builtin_alias, but without
the overloadable attribute.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112020

Files:
  clang/utils/TableGen/RISCVVEmitter.cpp


Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -202,7 +202,7 @@
   void emitCodeGenSwitchBody(raw_ostream &o) const;
 
   // Emit the macros for mapping C/C++ intrinsic function to builtin functions.
-  void emitIntrinsicMacro(raw_ostream &o) const;
+  void emitIntrinsicFuncDef(raw_ostream &o) const;
 
   // Emit the mangled function definition.
   void emitMangledFuncDef(raw_ostream &o) const;
@@ -860,21 +860,17 @@
   OS << "  break;\n";
 }
 
-void RVVIntrinsic::emitIntrinsicMacro(raw_ostream &OS) const {
-  OS << "#define " << getName() << "(";
-  if (!InputTypes.empty()) {
-ListSeparator LS;
-for (unsigned i = 0, e = InputTypes.size(); i != e; ++i)
-  OS << LS << "op" << i;
-  }
-  OS << ") \\\n";
-  OS << "__builtin_rvv_" << getName() << "(";
+void RVVIntrinsic::emitIntrinsicFuncDef(raw_ostream &OS) const {
+  OS << "__attribute__((clang_builtin_alias(";
+  OS << "__builtin_rvv_" << getName() << ")))\n";
+  OS << OutputType->getTypeStr() << " " << getName() << "(";
+  // Emit function arguments
   if (!InputTypes.empty()) {
 ListSeparator LS;
-for (unsigned i = 0, e = InputTypes.size(); i != e; ++i)
-  OS << LS << "(" << InputTypes[i]->getTypeStr() << ")(op" << i << ")";
+for (unsigned i = 0; i < InputTypes.size(); ++i)
+  OS << LS << InputTypes[i]->getTypeStr() << " op" << i;
   }
-  OS << ")\n";
+  OS << ");\n\n";
 }
 
 void RVVIntrinsic::emitMangledFuncDef(raw_ostream &OS) const {
@@ -986,11 +982,17 @@
  return A->getRISCVExtensions() < B->getRISCVExtensions();
});
 
+  OS << "#define __rvv_ai static inline "
+"__attribute__((__always_inline__, __nodebug__))\n";
+
   // Print intrinsic functions with macro
   emitArchMacroAndBody(Defs, OS, [](raw_ostream &OS, const RVVIntrinsic &Inst) 
{
-Inst.emitIntrinsicMacro(OS);
+OS << "__rvv_ai ";
+Inst.emitIntrinsicFuncDef(OS);
   });
 
+  OS << "#undef __rvv_ai\n";
+
   OS << "#define __riscv_v_intrinsic_overloading 1\n";
 
   // Print Overloaded APIs
@@ -1004,6 +1006,8 @@
 Inst.emitMangledFuncDef(OS);
   });
 
+  OS << "#undef __rvv_overloaded\n";
+
   OS << "\n#ifdef __cplusplus\n";
   OS << "}\n";
   OS << "#endif // __cplusplus\n";


Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -202,7 +202,7 @@
   void emitCodeGenSwitchBody(raw_ostream &o) const;
 
   // Emit the macros for mapping C/C++ intrinsic function to builtin functions.
-  void emitIntrinsicMacro(raw_ostream &o) const;
+  void emitIntrinsicFuncDef(raw_ostream &o) const;
 
   // Emit the mangled function definition.
   void emitMangledFuncDef(raw_ostream &o) const;
@@ -860,21 +860,17 @@
   OS << "  break;\n";
 }
 
-void RVVIntrinsic::emitIntrinsicMacro(raw_ostream &OS) const {
-  OS << "#define " << getName() << "(";
-  if (!InputTypes.empty()) {
-ListSeparator LS;
-for (unsigned i = 0, e = InputTypes.size(); i != e; ++i)
-  OS << LS << "op" << i;
-  }
-  OS << ") \\\n";
-  OS << "__builtin_rvv_" << getName() << "(";
+void RVVIntrinsic::emitIntrinsicFuncDef(raw_ostream &OS) const {
+  OS << "__attribute__((clang_builtin_alias(";
+  OS << "__builtin_rvv_" << getName() << ")))\n";
+  OS << OutputType->getTypeStr() << " " << getName() << "(";
+  // Emit function arguments
   if (!InputTypes.empty()) {
 ListSeparator LS;
-for (unsigned i = 0, e = InputTypes.size(); i != e; ++i)
-  OS << LS << "(" << InputTypes[i]->getTypeStr() << ")(op" << i << ")";
+for (unsigned i = 0; i < InputTypes.size(); ++i)
+  OS << LS << InputTypes[i]->getTypeStr() << " op" << i;
   }
-  OS << ")\n";
+  OS << ");\n\n";
 }
 
 void RVVIntrinsic::emitMangledFuncDef(raw_ostream &OS) const {
@@ -986,11 +982,17 @@
  return A->getRISCVExtensions() < B->getRISCVExtensions();
}

[PATCH] D112022: [WebAssembly] Add prototype relaxed swizzle instructions

2021-10-18 Thread Ng Zhi An via Phabricator via cfe-commits
ngzhian created this revision.
ngzhian added a reviewer: tlively.
Herald added subscribers: ecnelises, sunfish, hiraditya, jgravelle-google, 
sbc100, dschuff.
ngzhian requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, aheejin.
Herald added projects: clang, LLVM.

Add i8x16 relaxed_swizzle instructions. These are only
exposed as builtins, and require user opt-in.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112022

Files:
  clang/include/clang/Basic/BuiltinsWebAssembly.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/builtins-wasm.c
  llvm/include/llvm/IR/IntrinsicsWebAssembly.td
  llvm/lib/Target/WebAssembly/WebAssemblyISD.def
  llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td
  llvm/test/CodeGen/WebAssembly/simd-intrinsics.ll
  llvm/test/MC/WebAssembly/simd-encodings.s

Index: llvm/test/MC/WebAssembly/simd-encodings.s
===
--- llvm/test/MC/WebAssembly/simd-encodings.s
+++ llvm/test/MC/WebAssembly/simd-encodings.s
@@ -803,4 +803,7 @@
 # CHECK: i64x2.laneselect # encoding: [0xfd,0xd3,0x01]
 i64x2.laneselect
 
+# CHECK: i8x16.relaxed_swizzle # encoding: [0xfd,0xa2,0x01]
+i8x16.relaxed_swizzle
+
 end_function
Index: llvm/test/CodeGen/WebAssembly/simd-intrinsics.ll
===
--- llvm/test/CodeGen/WebAssembly/simd-intrinsics.ll
+++ llvm/test/CodeGen/WebAssembly/simd-intrinsics.ll
@@ -192,6 +192,16 @@
   ret <16 x i8> %v
 }
 
+; CHECK-LABEL: relaxed_swizzle_v16i8:
+; CHECK-NEXT: .functype relaxed_swizzle_v16i8 (v128, v128) -> (v128){{$}}
+; CHECK-NEXT: i8x16.relaxed_swizzle $push[[R:[0-9]+]]=, $0, $1{{$}}
+; CHECK-NEXT: return $pop[[R]]{{$}}
+declare <16 x i8> @llvm.wasm.relaxed.swizzle(<16 x i8>, <16 x i8>)
+define <16 x i8> @relaxed_swizzle_v16i8(<16 x i8> %x, <16 x i8> %y) {
+  %a = call <16 x i8> @llvm.wasm.relaxed.swizzle(<16 x i8> %x, <16 x i8> %y)
+  ret <16 x i8> %a
+}
+
 ; ==
 ; 8 x i16
 ; ==
Index: llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td
===
--- llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td
+++ llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td
@@ -1361,3 +1361,14 @@
 defm "" : SIMDLANESELECT;
 defm "" : SIMDLANESELECT;
 defm "" : SIMDLANESELECT;
+
+def wasm_relaxed_swizzle : SDNode<"WebAssemblyISD::RELAXED_SWIZZLE", wasm_swizzle_t>;
+
+defm RELAXED_SWIZZLE :
+  RELAXED_I<(outs V128:$dst), (ins V128:$src, V128:$mask), (outs), (ins),
+ [(set (v16i8 V128:$dst),
+   (wasm_relaxed_swizzle (v16i8 V128:$src), (v16i8 V128:$mask)))],
+ "i8x16.relaxed_swizzle\t$dst, $src, $mask", "i8x16.relaxed_swizzle", 162>;
+
+def : Pat<(int_wasm_relaxed_swizzle (v16i8 V128:$src), (v16i8 V128:$mask)),
+  (RELAXED_SWIZZLE $src, $mask)>;
Index: llvm/lib/Target/WebAssembly/WebAssemblyISD.def
===
--- llvm/lib/Target/WebAssembly/WebAssemblyISD.def
+++ llvm/lib/Target/WebAssembly/WebAssemblyISD.def
@@ -49,3 +49,6 @@
 HANDLE_MEM_NODETYPE(GLOBAL_GET)
 HANDLE_MEM_NODETYPE(GLOBAL_SET)
 HANDLE_MEM_NODETYPE(TABLE_SET)
+
+// Relaxed SIMD proposal.
+HANDLE_NODETYPE(RELAXED_SWIZZLE)
Index: llvm/include/llvm/IR/IntrinsicsWebAssembly.td
===
--- llvm/include/llvm/IR/IntrinsicsWebAssembly.td
+++ llvm/include/llvm/IR/IntrinsicsWebAssembly.td
@@ -200,6 +200,11 @@
 [LLVMMatchType<0>, LLVMMatchType<0>, LLVMMatchType<0>],
 [IntrNoMem, IntrSpeculatable]>;
 
+def int_wasm_relaxed_swizzle :
+  Intrinsic<[llvm_v16i8_ty],
+[llvm_v16i8_ty, llvm_v16i8_ty],
+[IntrNoMem, IntrSpeculatable]>;
+
 //===--===//
 // Thread-local storage intrinsics
 //===--===//
Index: clang/test/CodeGen/builtins-wasm.c
===
--- clang/test/CodeGen/builtins-wasm.c
+++ clang/test/CodeGen/builtins-wasm.c
@@ -732,3 +732,8 @@
   // WEBASSEMBLY-SAME: <2 x i64> %a, <2 x i64> %b, <2 x i64> %c)
   // WEBASSEMBLY-NEXT: ret
 }
+
+i8x16 relaxed_swizzle_i8x16(i8x16 x, i8x16 y) {
+  return __builtin_wasm_relaxed_swizzle_i8x16(x, y);
+  // WEBASSEMBLY: call <16 x i8> @llvm.wasm.relaxed.swizzle(<16 x i8> %x, <16 x i8> %y)
+}
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -18319,6 +18319,12 @@
 CGM.getIntrinsic(Intrinsic::wasm_laneselect, A->getType());
 return Builder.CreateCall(Callee, {A, B, C});
   }
+  case We

[PATCH] D112022: [WebAssembly] Add prototype relaxed swizzle instructions

2021-10-18 Thread Ng Zhi An via Phabricator via cfe-commits
ngzhian added inline comments.



Comment at: llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td:1365
+
+def wasm_relaxed_swizzle : SDNode<"WebAssemblyISD::RELAXED_SWIZZLE", 
wasm_swizzle_t>;
+

@tlively i'm not 100% sure if this is needed or the right thing to do, i looked 
at what i8x16.swizzle currently does and just replaced the name and opcode. LMK 
if this needs to be changed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112022

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


[clang] 5b949a6 - Fix crash when diagnosing a CTAD failure in an array new expression

2021-10-18 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-10-18T14:01:55-04:00
New Revision: 5b949a649aff0406a878e8eb8d7d5efba0a55e4a

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

LOG: Fix crash when diagnosing a CTAD failure in an array new expression

This appears to be a think-o where the developer was trying to check for a null
pointer but was actually checking (redundantly) whether the optional held a
valid value or not. We now properly check the pointer for null.

This fixes PR51547.

Added: 
clang/test/SemaCXX/new-delete-array.cpp

Modified: 
clang/lib/Sema/SemaExprCXX.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 6b091364c911f..0f3f50c8f6c6f 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -1967,10 +1967,10 @@ Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
   if (Deduced && isa(Deduced)) {
 if (ArraySize)
   return ExprError(
-  Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
+  Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
diag::err_deduced_class_template_compound_type)
   << /*array*/ 2
-  << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
+  << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
 
 InitializedEntity Entity
   = InitializedEntity::InitializeNew(StartLoc, AllocType);

diff  --git a/clang/test/SemaCXX/new-delete-array.cpp 
b/clang/test/SemaCXX/new-delete-array.cpp
new file mode 100644
index 0..fca1ec132acca
--- /dev/null
+++ b/clang/test/SemaCXX/new-delete-array.cpp
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++17 %s -verify=cxx17
+// RUN: %clang_cc1 -fsyntax-only -std=c++14 %s -verify=cxx14
+
+namespace PR51547 {
+template struct A; // cxx14-note {{template is declared here}}
+auto p = new A[]{}; // cxx14-error {{use of class template 'A' requires 
template arguments}} \
+   cxx17-error {{cannot form array of deduced class 
template specialization type}}
+}
+



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


[PATCH] D112024: [clang] diagnose_as attribute for Fortify diagnosing like builtins.

2021-10-18 Thread Michael Benfield via Phabricator via cfe-commits
mbenfield created this revision.
mbenfield added a reviewer: george.burgess.iv.
Herald added a reviewer: aaron.ballman.
mbenfield requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112024

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Sema/warn-fortify-source.c

Index: clang/test/Sema/warn-fortify-source.c
===
--- clang/test/Sema/warn-fortify-source.c
+++ clang/test/Sema/warn-fortify-source.c
@@ -181,6 +181,17 @@
   sprintf(buf, "5%.1e", 9.f); // expected-warning {{'sprintf' will always overflow; destination buffer has size 6, but format string expands to at least 8}}
 }
 
+void *test_memcpy(const void *src, size_t c, void *dst) __attribute__((diagnose_as(__builtin_memcpy, 3, 1, 2))) {
+  return __builtin_memcpy(dst, src, c);
+}
+
+void call_test_memcpy() {
+  char bufferA[10];
+  char bufferB[11];
+  test_memcpy(bufferB, 10, bufferA);
+  test_memcpy(bufferB, 11, bufferA); // expected-warning {{'memcpy' will always overflow; destination buffer has size 10, but size argument is 11}}
+}
+
 #ifdef __cplusplus
 template  struct S {
   void mf() const {
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -1001,6 +1001,38 @@
 };
 }
 
+static void handleDiagnoseAsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
+  SmallVector Indices;
+  for (unsigned I = 1; I < AL.getNumArgs(); ++I) {
+if (!AL.isArgExpr(I)) {
+  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
+  << AL << AANT_ArgumentIntegerConstant;
+  return;
+}
+
+Expr *IndexExpr = AL.getArgAsExpr(I);
+uint32_t Index;
+
+// If the expression is not parseable as a uint32_t we have a problem.
+if (!checkUInt32Argument(S, AL, IndexExpr, Index, UINT_MAX, false)) {
+  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
+  << AL << I << IndexExpr->getSourceRange();
+  return;
+}
+
+Indices.push_back(Index - 1);
+  }
+
+  if (!AL.isArgExpr(0)) {
+S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
+<< AL << AANT_ArgumentConstantExpr;
+return;
+  }
+
+  D->addAttr(::new (S.Context) DiagnoseAsAttr(S.Context, AL, AL.getArgAsExpr(0),
+  Indices.data(), Indices.size()));
+}
+
 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
   S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
 
@@ -8029,6 +8061,9 @@
   case ParsedAttr::AT_DiagnoseIf:
 handleDiagnoseIfAttr(S, D, AL);
 break;
+  case ParsedAttr::AT_DiagnoseAs:
+handleDiagnoseAsAttr(S, D, AL);
+break;
   case ParsedAttr::AT_NoBuiltin:
 handleNoBuiltinAttr(S, D, AL);
 break;
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -594,20 +594,51 @@
   isConstantEvaluated())
 return;
 
-  unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
+  bool UseDAIAttr = false;
+  FunctionDecl *UseDecl = FD;
+
+  auto DAIAttr = FD->getAttr();
+  if (DAIAttr) {
+DeclRefExpr *F = dyn_cast_or_null(DAIAttr->getFunction());
+if (!F)
+  return;
+FunctionDecl *AttrDecl = dyn_cast_or_null(F->getFoundDecl());
+if (!AttrDecl)
+  return;
+UseDecl = AttrDecl;
+UseDAIAttr = true;
+  }
+
+  unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
+
   if (!BuiltinID)
 return;
 
   const TargetInfo &TI = getASTContext().getTargetInfo();
   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
 
+  auto TranslateIndex = [&](unsigned Index) -> Optional {
+if (UseDAIAttr) {
+  if (Index >= DAIAttr->argIndices_size())
+return llvm::None;
+  return DAIAttr->argIndices_begin()[Index];
+}
+return Index;
+  };
+
   auto ComputeExplicitObjectSizeArgument =
   [&](unsigned Index) -> Optional {
+auto IndexOptional = TranslateIndex(Index);
+if (!IndexOptional)
+  return llvm::None;
+unsigned NewIndex = IndexOptional.getValue();
 Expr::EvalResult Result;
-Expr *SizeArg = TheCall->getArg(Index);
+Expr *SizeArg = TheCall->getArg(NewIndex);
 if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
   return llvm::None;
-return Result.Val.getInt();
+auto Integer = Result.Val.getInt();
+Integer.setIsUnsigned(true);
+return Integer;
   };
 
   auto ComputeSizeArgument = [&](unsigned Index) -> Optional {
@@ -616,10 +647,15 @@
 // type 0.
 int BOSType = 0;
 if (const auto *POS =
-FD->getParamDecl(Index)->getAttr())
+UseDecl->getParamDecl(Ind

[PATCH] D111529: Specify Clang vector builtins.

2021-10-18 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:557
+``i in [0, Number of elements / 2)``. If the numbers of elements is not a
+power of 2, the vector is widening with neutral elements for the reduction
+at the end to the next power of 2.

widening -> widened


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111529

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


[PATCH] D112001: [Clang] Add min/max reduction builtins.

2021-10-18 Thread Florian Hahn via Phabricator via cfe-commits
fhahn updated this revision to Diff 380486.
fhahn added a comment.

Remove stray `!TyA->getAs()` check.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112001

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-elementwise-math.c
  clang/test/Sema/builtins-elementwise-math.c

Index: clang/test/Sema/builtins-elementwise-math.c
===
--- clang/test/Sema/builtins-elementwise-math.c
+++ clang/test/Sema/builtins-elementwise-math.c
@@ -61,3 +61,31 @@
   i = __builtin_elementwise_min(v, iv);
   // expected-error@-1 {{argument types do not match, 'float4' (vector of 4 'float' values) != 'int3' (vector of 3 'int' values)}}
 }
+
+void test_builtin_reduce_max(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_max(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_reduce_max(v, v);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_reduce_max();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_reduce_max(i);
+  // expected-error@-1 {{argument must have a vector type, but was 'int'}}
+}
+
+void test_builtin_reduce_min(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_min(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_reduce_min(v, v);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_reduce_min();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_reduce_min(i);
+  // expected-error@-1 {{argument must have a vector type, but was 'int'}}
+}
Index: clang/test/CodeGen/builtins-elementwise-math.c
===
--- clang/test/CodeGen/builtins-elementwise-math.c
+++ clang/test/CodeGen/builtins-elementwise-math.c
@@ -110,3 +110,33 @@
   // CHECK-NEXT: call <4 x i32> @llvm.umin.v4i32(<4 x i32> [[VU1]], <4 x i32> [[VU2]])
   vu1 = __builtin_elementwise_min(vu1, vu2);
 }
+
+void test_builtin_reduce_max(float4 vf1, si8 vi1, u4 vu1) {
+  // CHECK-LABEL: define void @test_builtin_reduce_max(
+  // CHECK:  [[VF1:%.+]] = load <4 x float>, <4 x float>* %vf1.addr, align 16
+  // CHECK-NEXT: call float @llvm.vector.reduce.fmax.v4f32(<4 x float> [[VF1]])
+  float r1 = __builtin_reduce_max(vf1);
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.smax.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_max(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.umax.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_max(vu1);
+}
+
+void test_builtin_reduce_min(float4 vf1, si8 vi1, u4 vu1) {
+  // CHECK-LABEL: define void @test_builtin_reduce_min(
+  // CHECK:  [[VF1:%.+]] = load <4 x float>, <4 x float>* %vf1.addr, align 16
+  // CHECK-NEXT: call float @llvm.vector.reduce.fmin.v4f32(<4 x float> [[VF1]])
+  float r1 = __builtin_reduce_min(vf1);
+
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.smin.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_min(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.umin.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_min(vu1);
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -1978,11 +1978,14 @@
 
   case Builtin::BI__builtin_elementwise_abs:
 return SemaBuiltinElementwiseMathOneArg(TheCall, TheCallResult);
-
   case Builtin::BI__builtin_elementwise_min:
   case Builtin::BI__builtin_elementwise_max:
 return SemaBuiltinElementwiseMathTwoArgs(TheCall, TheCallResult);
 
+  case Builtin::BI__builtin_reduce_max:
+  case Builtin::BI__builtin_reduce_min:
+return SemaBuiltinReduceMath(TheCall, TheCallResult);
+
   case Builtin::BI__builtin_matrix_transpose:
 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
   case Builtin::BI__builtin_matrix_column_major_load:
@@ -16656,6 +16659,23 @@
  _2, _3, _4));
 }
 
+ExprResult Sema::SemaBuiltinReduceMath(CallExpr *TheCall,
+   ExprResult CallResult) {
+  if (checkArgCount(*this, TheCall, 1))
+return ExprError();
+
+  Expr *A = TheCall->getArg(0);
+  QualType TyA = A->getType();
+
+  const VectorType *VecTy 

[PATCH] D112001: [Clang] Add min/max reduction builtins.

2021-10-18 Thread Florian Hahn via Phabricator via cfe-commits
fhahn marked an inline comment as done.
fhahn added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:16673
+  if (!VecTy)
+  if (!TyA->getAs())
+  return Diag(A->getBeginLoc(), 
diag::err_elementwise_math_invalid_arg_type_2)

craig.topper wrote:
> Is this indented incorrectly? There appear to be 2 ifs at the same level
Yes they were, thanks! The `if (!TyA->getAs())` was a left-over 
from an earlier iteration. Removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112001

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


[PATCH] D111986: [Clang] Add elementwise abs builtin.

2021-10-18 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:3109
+  Result = Builder.CreateBinaryIntrinsic(
+  llvm::Intrinsic::abs, Op0, Builder.getFalse(), nullptr, "elt.abs");
+else

craig.topper wrote:
> Did we discuss that this is different than __builtin_abs which is undefined 
> for INT_MIN?
I don't think we add nsw to vector signed integer subtract, so I guess using 
false here is consistent.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111986

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


[PATCH] D105168: [RISCV] Unify the arch string parsing logic to RISCVISAInfo.

2021-10-18 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

In D105168#3069499 , @teemperor wrote:

> This broke the modules build:
>
>   While building module 'LLVM_Utils' imported from 
> lvm/lib/Support/TargetParser.cpp:14:
>   In file included from :209:
>   llvm/include/llvm/Support/RISCVISAInfo.h:15:10: fatal error: could not 
> build module 'LLVM_Option'
>   #include "llvm/Option/ArgList.h"
>^~~
>   llvm/lib/Support/TargetParser.cpp:14:10: fatal error: could not build 
> module 'LLVM_Utils'
>   #include "llvm/Support/TargetParser.h"
>^
>
> `Support` headers can't include `Option` headers (as `Option` depends on 
> `Support` already, so that would be a cyclic dependency). I believe folks 
> here are in the US time zone, so I went ahead and replaced the header include 
> with a forward decl to unbreak the bots (see 
> de4d2f80b75e2a1e4b0ac5c25e20f20839633688 
>  )
>
> FWIW, I think there is a better place than `Support` for this new class. 
> `Support` is a dependency of nearly every single LLVM component, but this 
> class seems to be used by a handful of files. Could we maybe move this to 
> some other/new part of LLVM (and make the few components that need it depend 
> on that)?

Thanks for the header fix. I think we also need to fix the library circular 
dependency that still exists. The Support library should not use anything from 
the Option library. Maybe we can partition the function some way that moves the 
MakeArgStr back into the clang driver code.

I don't know if we have a better library for this new class. I think Support is 
the only common library between the clang driver and LLVM's MC layer. I 
supposed we could create a new library, but that might be a hard sell for one 
file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105168

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


[PATCH] D111371: [Support][ThinLTO] Move ThinLTO caching to LLVM Support library.

2021-10-18 Thread Petr Hosek via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG92b8cc52bbc8: [Support][ThinLTO] Move ThinLTO caching to 
LLVM Support library (authored by noajshu, committed by phosek).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111371

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  lld/COFF/LTO.cpp
  lld/ELF/LTO.cpp
  lld/MachO/LTO.cpp
  lld/wasm/LTO.cpp
  llvm/include/llvm/LTO/Caching.h
  llvm/include/llvm/LTO/LTO.h
  llvm/include/llvm/LTO/legacy/LTOCodeGenerator.h
  llvm/include/llvm/Support/Caching.h
  llvm/lib/LTO/CMakeLists.txt
  llvm/lib/LTO/Caching.cpp
  llvm/lib/LTO/LTOCodeGenerator.cpp
  llvm/lib/Support/CMakeLists.txt
  llvm/lib/Support/Caching.cpp
  llvm/tools/gold/gold-plugin.cpp
  llvm/tools/llvm-lto/llvm-lto.cpp
  llvm/tools/llvm-lto2/llvm-lto2.cpp

Index: llvm/tools/llvm-lto2/llvm-lto2.cpp
===
--- llvm/tools/llvm-lto2/llvm-lto2.cpp
+++ llvm/tools/llvm-lto2/llvm-lto2.cpp
@@ -19,10 +19,10 @@
 #include "llvm/CodeGen/CommandFlags.h"
 #include "llvm/Config/llvm-config.h"
 #include "llvm/IR/DiagnosticPrinter.h"
-#include "llvm/LTO/Caching.h"
 #include "llvm/LTO/LTO.h"
 #include "llvm/Passes/PassPlugin.h"
 #include "llvm/Remarks/HotnessThresholdParser.h"
+#include "llvm/Support/Caching.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/InitLLVM.h"
@@ -362,14 +362,13 @@
   if (HasErrors)
 return 1;
 
-  auto AddStream =
-  [&](size_t Task) -> std::unique_ptr {
+  auto AddStream = [&](size_t Task) -> std::unique_ptr {
 std::string Path = OutputFilename + "." + utostr(Task);
 
 std::error_code EC;
 auto S = std::make_unique(Path, EC, sys::fs::OF_None);
 check(EC, Path);
-return std::make_unique(std::move(S));
+return std::make_unique(std::move(S));
   };
 
   auto AddBuffer = [&](size_t Task, std::unique_ptr MB) {
@@ -378,7 +377,8 @@
 
   NativeObjectCache Cache;
   if (!CacheDir.empty())
-Cache = check(localCache(CacheDir, AddBuffer), "failed to create cache");
+Cache = check(localCache("ThinLTO", "Thin", CacheDir, AddBuffer),
+  "failed to create cache");
 
   check(Lto.run(AddStream, Cache), "LTO::run failed");
   return 0;
Index: llvm/tools/llvm-lto/llvm-lto.cpp
===
--- llvm/tools/llvm-lto/llvm-lto.cpp
+++ llvm/tools/llvm-lto/llvm-lto.cpp
@@ -1097,8 +1097,7 @@
 error("writing merged module failed.");
 }
 
-auto AddStream =
-[&](size_t Task) -> std::unique_ptr {
+auto AddStream = [&](size_t Task) -> std::unique_ptr {
   std::string PartFilename = OutputFilename;
   if (Parallelism != 1)
 PartFilename += "." + utostr(Task);
@@ -1108,7 +1107,7 @@
   std::make_unique(PartFilename, EC, sys::fs::OF_None);
   if (EC)
 error("error opening the file '" + PartFilename + "': " + EC.message());
-  return std::make_unique(std::move(S));
+  return std::make_unique(std::move(S));
 };
 
 if (!CodeGen.compileOptimized(AddStream, Parallelism))
Index: llvm/tools/gold/gold-plugin.cpp
===
--- llvm/tools/gold/gold-plugin.cpp
+++ llvm/tools/gold/gold-plugin.cpp
@@ -1081,12 +1081,11 @@
   size_t MaxTasks = Lto->getMaxTasks();
   std::vector, bool>> Files(MaxTasks);
 
-  auto AddStream =
-  [&](size_t Task) -> std::unique_ptr {
+  auto AddStream = [&](size_t Task) -> std::unique_ptr {
 Files[Task].second = !SaveTemps;
 int FD = getOutputFileName(Filename, /* TempOutFile */ !SaveTemps,
Files[Task].first, Task);
-return std::make_unique(
+return std::make_unique(
 std::make_unique(FD, true));
   };
 
@@ -1096,7 +1095,7 @@
 
   NativeObjectCache Cache;
   if (!options::cache_dir.empty())
-Cache = check(localCache(options::cache_dir, AddBuffer));
+Cache = check(localCache("ThinLTO", "Thin", options::cache_dir, AddBuffer));
 
   check(Lto->run(AddStream, Cache));
 
Index: llvm/lib/Support/Caching.cpp
===
--- llvm/lib/Support/Caching.cpp
+++ llvm/lib/Support/Caching.cpp
@@ -1,4 +1,4 @@
-//===-Caching.cpp - LLVM Link Time Optimizer Cache Handling ---===//
+//===-Caching.cpp - LLVM File Cache Handling --===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -6,11 +6,11 @@
 //
 //===--===//
 //
-// This file implements the Caching for ThinLTO.
+// This file implements the Caching used by ThinLTO.
 //
 //===--===//
 
-#include "llvm/LTO/Ca

[clang] 92b8cc5 - [Support][ThinLTO] Move ThinLTO caching to LLVM Support library

2021-10-18 Thread Petr Hosek via cfe-commits

Author: Noah Shutty
Date: 2021-10-18T12:08:49-07:00
New Revision: 92b8cc52bbc8194f2cd6a5f742b874969421afca

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

LOG: [Support][ThinLTO] Move ThinLTO caching to LLVM Support library

We would like to move ThinLTO’s battle-tested file caching mechanism to
the LLVM Support library so that we can use it elsewhere in LLVM.

Patch By: noajshu

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

Added: 
llvm/include/llvm/Support/Caching.h
llvm/lib/Support/Caching.cpp

Modified: 
clang/lib/CodeGen/BackendUtil.cpp
lld/COFF/LTO.cpp
lld/ELF/LTO.cpp
lld/MachO/LTO.cpp
lld/wasm/LTO.cpp
llvm/include/llvm/LTO/LTO.h
llvm/include/llvm/LTO/legacy/LTOCodeGenerator.h
llvm/lib/LTO/CMakeLists.txt
llvm/lib/LTO/LTOCodeGenerator.cpp
llvm/lib/Support/CMakeLists.txt
llvm/tools/gold/gold-plugin.cpp
llvm/tools/llvm-lto/llvm-lto.cpp
llvm/tools/llvm-lto2/llvm-lto2.cpp

Removed: 
llvm/include/llvm/LTO/Caching.h
llvm/lib/LTO/Caching.cpp



diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 986c9e8104e9d..ff76ef1d9dd88 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -1561,7 +1561,7 @@ static void runThinLTOBackend(
 return;
 
   auto AddStream = [&](size_t Task) {
-return std::make_unique(std::move(OS));
+return std::make_unique(std::move(OS));
   };
   lto::Config Conf;
   if (CGOpts.SaveTempsFilePrefix != "") {

diff  --git a/lld/COFF/LTO.cpp b/lld/COFF/LTO.cpp
index ce9c4fd0d51b2..505360663f4f9 100644
--- a/lld/COFF/LTO.cpp
+++ b/lld/COFF/LTO.cpp
@@ -20,10 +20,10 @@
 #include "llvm/ADT/Twine.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
 #include "llvm/IR/DiagnosticPrinter.h"
-#include "llvm/LTO/Caching.h"
 #include "llvm/LTO/Config.h"
 #include "llvm/LTO/LTO.h"
 #include "llvm/Object/SymbolicFile.h"
+#include "llvm/Support/Caching.h"
 #include "llvm/Support/CodeGen.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/FileSystem.h"
@@ -164,16 +164,17 @@ std::vector 
BitcodeCompiler::compile(COFFLinkerContext &ctx) {
   // The /lldltocache option specifies the path to a directory in which to 
cache
   // native object files for ThinLTO incremental builds. If a path was
   // specified, configure LTO to use it as the cache directory.
-  lto::NativeObjectCache cache;
+  NativeObjectCache cache;
   if (!config->ltoCache.empty())
-cache = check(lto::localCache(
-config->ltoCache, [&](size_t task, std::unique_ptr mb) {
-  files[task] = std::move(mb);
-}));
+cache =
+check(localCache("ThinLTO", "Thin", config->ltoCache,
+ [&](size_t task, std::unique_ptr mb) {
+   files[task] = std::move(mb);
+ }));
 
   checkError(ltoObj->run(
   [&](size_t task) {
-return std::make_unique(
+return std::make_unique(
 std::make_unique(buf[task]));
   },
   cache));

diff  --git a/lld/ELF/LTO.cpp b/lld/ELF/LTO.cpp
index fb354f81d49d6..5f206fc97b3ca 100644
--- a/lld/ELF/LTO.cpp
+++ b/lld/ELF/LTO.cpp
@@ -23,10 +23,10 @@
 #include "llvm/Bitcode/BitcodeReader.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
 #include "llvm/IR/DiagnosticPrinter.h"
-#include "llvm/LTO/Caching.h"
 #include "llvm/LTO/Config.h"
 #include "llvm/LTO/LTO.h"
 #include "llvm/Object/SymbolicFile.h"
+#include "llvm/Support/Caching.h"
 #include "llvm/Support/CodeGen.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/FileSystem.h"
@@ -304,18 +304,18 @@ std::vector BitcodeCompiler::compile() {
   // The --thinlto-cache-dir option specifies the path to a directory in which
   // to cache native object files for ThinLTO incremental builds. If a path was
   // specified, configure LTO to use it as the cache directory.
-  lto::NativeObjectCache cache;
+  NativeObjectCache cache;
   if (!config->thinLTOCacheDir.empty())
-cache = check(
-lto::localCache(config->thinLTOCacheDir,
-[&](size_t task, std::unique_ptr mb) {
-  files[task] = std::move(mb);
-}));
+cache =
+check(localCache("ThinLTO", "Thin", config->thinLTOCacheDir,
+ [&](size_t task, std::unique_ptr mb) {
+   files[task] = std::move(mb);
+ }));
 
   if (!bitcodeFiles.empty())
 checkError(ltoObj->run(
 [&](size_t task) {
-  return std::make_unique(
+  return std::make_unique(
   std::make_unique(buf[task]));
 },
 cache));

diff  --git a/lld/MachO/LTO.cpp b/lld/MachO/LTO.cpp
index 09b05ed0dffee..d1eef6a6f8f82 100644
--- a/lld/MachO/LTO.cpp
+++ 

[PATCH] D111009: Update inline builtin handling to honor gnu inline attribute

2021-10-18 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

See also: https://github.com/ClangBuiltLinux/linux/issues/1477.  Surprising 
that this didn't show up in newer kernels, just older (but still supported) 
kernel versions. Sorry I missed that in my tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111009

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


[clang] 8e46e34 - Revert "[Support][ThinLTO] Move ThinLTO caching to LLVM Support library"

2021-10-18 Thread Petr Hosek via cfe-commits

Author: Petr Hosek
Date: 2021-10-18T12:24:05-07:00
New Revision: 8e46e34d243524b9a1f9487718ea60e990b35fa3

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

LOG: Revert "[Support][ThinLTO] Move ThinLTO caching to LLVM Support library"

This reverts commit 92b8cc52bbc8194f2cd6a5f742b874969421afca since
it broke the gold plugin.

Added: 
llvm/include/llvm/LTO/Caching.h
llvm/lib/LTO/Caching.cpp

Modified: 
clang/lib/CodeGen/BackendUtil.cpp
lld/COFF/LTO.cpp
lld/ELF/LTO.cpp
lld/MachO/LTO.cpp
lld/wasm/LTO.cpp
llvm/include/llvm/LTO/LTO.h
llvm/include/llvm/LTO/legacy/LTOCodeGenerator.h
llvm/lib/LTO/CMakeLists.txt
llvm/lib/LTO/LTOCodeGenerator.cpp
llvm/lib/Support/CMakeLists.txt
llvm/tools/gold/gold-plugin.cpp
llvm/tools/llvm-lto/llvm-lto.cpp
llvm/tools/llvm-lto2/llvm-lto2.cpp

Removed: 
llvm/include/llvm/Support/Caching.h
llvm/lib/Support/Caching.cpp



diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index ff76ef1d9dd88..986c9e8104e9d 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -1561,7 +1561,7 @@ static void runThinLTOBackend(
 return;
 
   auto AddStream = [&](size_t Task) {
-return std::make_unique(std::move(OS));
+return std::make_unique(std::move(OS));
   };
   lto::Config Conf;
   if (CGOpts.SaveTempsFilePrefix != "") {

diff  --git a/lld/COFF/LTO.cpp b/lld/COFF/LTO.cpp
index 505360663f4f9..ce9c4fd0d51b2 100644
--- a/lld/COFF/LTO.cpp
+++ b/lld/COFF/LTO.cpp
@@ -20,10 +20,10 @@
 #include "llvm/ADT/Twine.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
 #include "llvm/IR/DiagnosticPrinter.h"
+#include "llvm/LTO/Caching.h"
 #include "llvm/LTO/Config.h"
 #include "llvm/LTO/LTO.h"
 #include "llvm/Object/SymbolicFile.h"
-#include "llvm/Support/Caching.h"
 #include "llvm/Support/CodeGen.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/FileSystem.h"
@@ -164,17 +164,16 @@ std::vector 
BitcodeCompiler::compile(COFFLinkerContext &ctx) {
   // The /lldltocache option specifies the path to a directory in which to 
cache
   // native object files for ThinLTO incremental builds. If a path was
   // specified, configure LTO to use it as the cache directory.
-  NativeObjectCache cache;
+  lto::NativeObjectCache cache;
   if (!config->ltoCache.empty())
-cache =
-check(localCache("ThinLTO", "Thin", config->ltoCache,
- [&](size_t task, std::unique_ptr mb) {
-   files[task] = std::move(mb);
- }));
+cache = check(lto::localCache(
+config->ltoCache, [&](size_t task, std::unique_ptr mb) {
+  files[task] = std::move(mb);
+}));
 
   checkError(ltoObj->run(
   [&](size_t task) {
-return std::make_unique(
+return std::make_unique(
 std::make_unique(buf[task]));
   },
   cache));

diff  --git a/lld/ELF/LTO.cpp b/lld/ELF/LTO.cpp
index 5f206fc97b3ca..fb354f81d49d6 100644
--- a/lld/ELF/LTO.cpp
+++ b/lld/ELF/LTO.cpp
@@ -23,10 +23,10 @@
 #include "llvm/Bitcode/BitcodeReader.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
 #include "llvm/IR/DiagnosticPrinter.h"
+#include "llvm/LTO/Caching.h"
 #include "llvm/LTO/Config.h"
 #include "llvm/LTO/LTO.h"
 #include "llvm/Object/SymbolicFile.h"
-#include "llvm/Support/Caching.h"
 #include "llvm/Support/CodeGen.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/FileSystem.h"
@@ -304,18 +304,18 @@ std::vector BitcodeCompiler::compile() {
   // The --thinlto-cache-dir option specifies the path to a directory in which
   // to cache native object files for ThinLTO incremental builds. If a path was
   // specified, configure LTO to use it as the cache directory.
-  NativeObjectCache cache;
+  lto::NativeObjectCache cache;
   if (!config->thinLTOCacheDir.empty())
-cache =
-check(localCache("ThinLTO", "Thin", config->thinLTOCacheDir,
- [&](size_t task, std::unique_ptr mb) {
-   files[task] = std::move(mb);
- }));
+cache = check(
+lto::localCache(config->thinLTOCacheDir,
+[&](size_t task, std::unique_ptr mb) {
+  files[task] = std::move(mb);
+}));
 
   if (!bitcodeFiles.empty())
 checkError(ltoObj->run(
 [&](size_t task) {
-  return std::make_unique(
+  return std::make_unique(
   std::make_unique(buf[task]));
 },
 cache));

diff  --git a/lld/MachO/LTO.cpp b/lld/MachO/LTO.cpp
index d1eef6a6f8f82..09b05ed0dffee 100644
--- a/lld/MachO/LTO.cpp
+++ b/lld/MachO/LTO.cpp
@@ -17,9 +17,9 @@
 #include "lld/Common/ErrorHandler.h"
 #include "lld/Common/Strings.h"
 #in

[PATCH] D112028: [RISCV] Remove the HasSideEffects property from riscv_vector.td

2021-10-18 Thread Craig Topper via Phabricator via cfe-commits
craig.topper created this revision.
craig.topper added reviewers: HsiangKai, kito-cheng, arcbbb, khchen.
Herald added subscribers: achieveartificialintelligence, StephenFan, vkmr, 
frasercrmck, evandro, luismarques, apazos, sameer.abuasal, s.egerton, Jim, 
benna, psnobl, jocewei, PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, 
edward-jones, zzheng, jrtc27, shiva0217, niosHD, sabuasal, simoncook, 
johnrusso, rbar, asb.
craig.topper requested review of this revision.
Herald added a subscriber: MaskRay.
Herald added a project: clang.

It was being used to control the nothrow attribute on the builtins. The
nothrow attribute is for C++ exceptions. Even if the vector builtins
have side effects in IR, that's different than the nothrow attribute.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112028

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/utils/TableGen/RISCVVEmitter.cpp

Index: clang/utils/TableGen/RISCVVEmitter.cpp
===
--- clang/utils/TableGen/RISCVVEmitter.cpp
+++ clang/utils/TableGen/RISCVVEmitter.cpp
@@ -153,7 +153,6 @@
   std::string Name; // Builtin name
   std::string MangledName;
   std::string IRName;
-  bool HasSideEffects;
   bool IsMask;
   bool HasMaskedOffOperand;
   bool HasVL;
@@ -171,9 +170,9 @@
 
 public:
   RVVIntrinsic(StringRef Name, StringRef Suffix, StringRef MangledName,
-   StringRef MangledSuffix, StringRef IRName, bool HasSideEffects,
-   bool IsMask, bool HasMaskedOffOperand, bool HasVL,
-   bool HasPolicy, bool HasNoMaskedOverloaded, bool HasAutoDef,
+   StringRef MangledSuffix, StringRef IRName, bool IsMask,
+   bool HasMaskedOffOperand, bool HasVL, bool HasPolicy,
+   bool HasNoMaskedOverloaded, bool HasAutoDef,
StringRef ManualCodegen, const RVVTypes &Types,
const std::vector &IntrinsicTypes,
StringRef RequiredExtension, unsigned NF);
@@ -181,7 +180,6 @@
 
   StringRef getName() const { return Name; }
   StringRef getMangledName() const { return MangledName; }
-  bool hasSideEffects() const { return HasSideEffects; }
   bool hasMaskedOffOperand() const { return HasMaskedOffOperand; }
   bool hasVL() const { return HasVL; }
   bool hasPolicy() const { return HasPolicy; }
@@ -759,16 +757,16 @@
 //===--===//
 RVVIntrinsic::RVVIntrinsic(StringRef NewName, StringRef Suffix,
StringRef NewMangledName, StringRef MangledSuffix,
-   StringRef IRName, bool HasSideEffects, bool IsMask,
+   StringRef IRName, bool IsMask,
bool HasMaskedOffOperand, bool HasVL, bool HasPolicy,
bool HasNoMaskedOverloaded, bool HasAutoDef,
StringRef ManualCodegen, const RVVTypes &OutInTypes,
const std::vector &NewIntrinsicTypes,
StringRef RequiredExtension, unsigned NF)
-: IRName(IRName), HasSideEffects(HasSideEffects), IsMask(IsMask),
-  HasMaskedOffOperand(HasMaskedOffOperand), HasVL(HasVL),
-  HasPolicy(HasPolicy), HasNoMaskedOverloaded(HasNoMaskedOverloaded),
-  HasAutoDef(HasAutoDef), ManualCodegen(ManualCodegen.str()), NF(NF) {
+: IRName(IRName), IsMask(IsMask), HasMaskedOffOperand(HasMaskedOffOperand),
+  HasVL(HasVL), HasPolicy(HasPolicy),
+  HasNoMaskedOverloaded(HasNoMaskedOverloaded), HasAutoDef(HasAutoDef),
+  ManualCodegen(ManualCodegen.str()), NF(NF) {
 
   // Init Name and MangledName
   Name = NewName.str();
@@ -1024,11 +1022,7 @@
   OS << "#endif\n";
   for (auto &Def : Defs) {
 OS << "RISCVV_BUILTIN(__builtin_rvv_" << Def->getName() << ",\""
-   << Def->getBuiltinTypeStr() << "\", ";
-if (!Def->hasSideEffects())
-  OS << "\"n\")\n";
-else
-  OS << "\"\")\n";
+   << Def->getBuiltinTypeStr() << "\", \"n\")\n";
   }
   OS << "#undef RISCVV_BUILTIN\n";
 }
@@ -1099,7 +1093,6 @@
 bool HasVL = R->getValueAsBit("HasVL");
 bool HasPolicy = R->getValueAsBit("HasPolicy");
 bool HasNoMaskedOverloaded = R->getValueAsBit("HasNoMaskedOverloaded");
-bool HasSideEffects = R->getValueAsBit("HasSideEffects");
 std::vector Log2LMULList = R->getValueAsListOfInts("Log2LMUL");
 StringRef ManualCodegen = R->getValueAsString("ManualCodegen");
 StringRef ManualCodegenMask = R->getValueAsString("ManualCodegenMask");
@@ -1171,17 +1164,17 @@
 // Create a non-mask intrinsic
 Out.push_back(std::make_unique(
 Name, SuffixStr, MangledName, MangledSuffixStr, IRName,
-HasSideEffects, /*IsMask=*/false, /*HasMaskedOffOperand=*/false,
-HasVL, HasPolicy, HasNoMaskedOverloaded, HasAutoDef, ManualCodegen,
-Types.getValue(), IntrinsicTypes, RequiredExtension, NF));
+/*IsMask=*/

Re: [clang] 2edb89c - Lex arguments for __has_cpp_attribute and friends as expanded tokens

2021-10-18 Thread Richard Smith via cfe-commits
On Sun, 17 Oct 2021 at 04:58, Aaron Ballman via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

>
> Author: Aaron Ballman
> Date: 2021-10-17T07:54:48-04:00
> New Revision: 2edb89c746848c52964537268bf03e7906bf2542
>
> URL:
> https://github.com/llvm/llvm-project/commit/2edb89c746848c52964537268bf03e7906bf2542
> DIFF:
> https://github.com/llvm/llvm-project/commit/2edb89c746848c52964537268bf03e7906bf2542.diff
>
> LOG: Lex arguments for __has_cpp_attribute and friends as expanded tokens
>
> The C and C++ standards require the argument to __has_cpp_attribute and
> __has_c_attribute to be expanded ([cpp.cond]p5). It would make little sense
> to expand the argument to those operators but not expand the argument to
> __has_attribute and __has_declspec, so those were both also changed in this
> patch.
>
> Note that it might make sense for the other builtins to also expand their
> argument, but it wasn't as clear to me whether the behavior would be
> correct
> there, and so they were left for a future revision.
>
> Added:
> clang/test/Preprocessor/has_attribute_errors.cpp
>
> Modified:
> clang/docs/ReleaseNotes.rst
> clang/lib/Lex/PPMacroExpansion.cpp
> clang/test/Preprocessor/has_attribute.c
> clang/test/Preprocessor/has_attribute.cpp
> clang/test/Preprocessor/has_c_attribute.c
>
> Removed:
>
>
>
>
> 
> diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
> index 6501a4870e2a6..263eae83036df 100644
> --- a/clang/docs/ReleaseNotes.rst
> +++ b/clang/docs/ReleaseNotes.rst
> @@ -110,6 +110,13 @@ Attribute Changes in Clang
>attribute is handled instead, e.g. in ``handleDeclAttribute``.
>(This was changed in order to better support attributes in code
> completion).
>
> +- __has_cpp_attribute, __has_c_attribute, __has_attribute, and
> __has_declspec
> +  will now macro expand their argument. This causes a change in behavior
> for
> +  code using ``__has_cpp_attribute(__clang__::attr)`` (and same for
> +  ``__has_c_attribute``) where it would previously expand to ``0`` for all
> +  attributes, but will now issue an error due to the expansion of the
> +  predefined ``__clang__`` macro.
> +
>  Windows Support
>  ---
>
>
> diff  --git a/clang/lib/Lex/PPMacroExpansion.cpp
> b/clang/lib/Lex/PPMacroExpansion.cpp
> index bf19f538647e6..5a0fa5184e38b 100644
> --- a/clang/lib/Lex/PPMacroExpansion.cpp
> +++ b/clang/lib/Lex/PPMacroExpansion.cpp
> @@ -1293,7 +1293,7 @@ static bool EvaluateHasIncludeNext(Token &Tok,
>  /// integer values.
>  static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
>  Token &Tok, IdentifierInfo
> *II,
> -Preprocessor &PP,
> +Preprocessor &PP, bool
> ExpandArgs,
>  llvm::function_ref<
>int(Token &Tok,
>bool &HasLexedNextTok)>
> Op) {
> @@ -1319,7 +1319,10 @@ static void
> EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
>bool SuppressDiagnostic = false;
>while (true) {
>  // Parse next token.
> -PP.LexUnexpandedToken(Tok);
> +if (ExpandArgs)
> +  PP.Lex(Tok);
> +else
> +  PP.LexUnexpandedToken(Tok);
>

How does this handle things like:

#define RPAREN )
#if __has_attribute(clang::fallthrough RPAREN

? I think that should be an error: the ) token should not be produced by
macro expansion, analogous to the behavior of function-like macros. But I
imagine unless we're careful here, we'll allow that macro expansion to
terminate the "macro".

 already_lexed:
>  switch (Tok.getKind()) {
> @@ -1609,21 +1612,21 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
>  OS << CounterValue++;
>  Tok.setKind(tok::numeric_constant);
>} else if (II == Ident__has_feature) {
> -EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
> +EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
>[this](Token &Tok, bool &HasLexedNextToken) -> int {
>  IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
>
> diag::err_feature_check_malformed);
>  return II && HasFeature(*this, II->getName());
>});
>} else if (II == Ident__has_extension) {
> -EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
> +EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
>[this](Token &Tok, bool &HasLexedNextToken) -> int {
>  IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
>
> diag::err_feature_check_malformed);
>  return II && HasExtension(*this, II->getName());
>});
>} else if (II == Ident__has_builtin) {
> -EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
> +EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
>[this](T

  1   2   >