[PATCH] D156027: [clang][Interp] Rework how initializers work

2023-07-25 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

In D156027#4534090 , @tbaeder wrote:

> Note that this patch also supercedes:
>
> 1. https://reviews.llvm.org/D153616
> 2. https://reviews.llvm.org/D153653
> 3. https://reviews.llvm.org/D147591
>
> since it handles those cases more generally.

Can you abandon the revisions you are no longer pursuing? Thanks!


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

https://reviews.llvm.org/D156027

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


[PATCH] D148982: [clang][Interp] Fix ignoring conditional operators

2023-07-25 Thread Timm Bäder 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 rG2606545b0204: [clang][Interp] Fix ignoring conditional 
operators (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148982

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/literals.cpp


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -857,6 +857,9 @@
 
   (void)5, (void)6;
 
+  1 ? 0 : 1; // expected-warning {{unused}} \
+ // ref-warning {{unused}}
+
   return 0;
 }
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -595,8 +595,9 @@
 template 
 bool ByteCodeExprGen::VisitAbstractConditionalOperator(
 const AbstractConditionalOperator *E) {
-  return this->visitConditional(
-  E, [this](const Expr *E) { return this->visit(E); });
+  return this->visitConditional(E, [this](const Expr *E) {
+return DiscardResult ? this->discard(E) : this->visit(E);
+  });
 }
 
 template 


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -857,6 +857,9 @@
 
   (void)5, (void)6;
 
+  1 ? 0 : 1; // expected-warning {{unused}} \
+ // ref-warning {{unused}}
+
   return 0;
 }
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -595,8 +595,9 @@
 template 
 bool ByteCodeExprGen::VisitAbstractConditionalOperator(
 const AbstractConditionalOperator *E) {
-  return this->visitConditional(
-  E, [this](const Expr *E) { return this->visit(E); });
+  return this->visitConditional(E, [this](const Expr *E) {
+return DiscardResult ? this->discard(E) : this->visit(E);
+  });
 }
 
 template 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2606545 - [clang][Interp] Fix ignoring conditional operators

2023-07-25 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-07-26T07:46:04+02:00
New Revision: 2606545b0204e7d2d6434e78640d5732d9381837

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

LOG: [clang][Interp] Fix ignoring conditional operators

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/literals.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 5e42cca6762104..ff40fd3da13f76 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -595,8 +595,9 @@ bool ByteCodeExprGen::VisitOpaqueValueExpr(const 
OpaqueValueExpr *E) {
 template 
 bool ByteCodeExprGen::VisitAbstractConditionalOperator(
 const AbstractConditionalOperator *E) {
-  return this->visitConditional(
-  E, [this](const Expr *E) { return this->visit(E); });
+  return this->visitConditional(E, [this](const Expr *E) {
+return DiscardResult ? this->discard(E) : this->visit(E);
+  });
 }
 
 template 

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index cf5e86658e3b38..25c40755c2d495 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -857,6 +857,9 @@ constexpr int ignoredExprs() {
 
   (void)5, (void)6;
 
+  1 ? 0 : 1; // expected-warning {{unused}} \
+ // ref-warning {{unused}}
+
   return 0;
 }
 



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


[PATCH] D156214: [LLVM][RISCV] Check more extension dependencies

2023-07-25 Thread Kiva via Phabricator via cfe-commits
imkiva added a comment.

Looks like I am reading a very old version of the spec haha. Anyway, thank you 
all for giving me the newest information and useful links! Thanks!!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156214

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


[PATCH] D148925: [clang][Interp] Fix discarding void-typed comma expressions

2023-07-25 Thread Timm Bäder 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 rGaed9646d8e29: [clang][Interp] Fix discarding void-typed 
comma expressions (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D148925?vs=515800=544214#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148925

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/literals.cpp


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -855,9 +855,23 @@
   (a); // expected-warning {{unused}} \
// ref-warning {{unused}}
 
+  (void)5, (void)6;
+
   return 0;
 }
 
+/// Ignored comma expressions still have their
+/// expressions evaluated.
+constexpr int Comma(int start) {
+int i = start;
+
+(void)i++;
+(void)i++,(void)i++;
+return i;
+}
+constexpr int Value = Comma(5);
+static_assert(Value == 8, "");
+
 #endif
 
 namespace PredefinedExprs {
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -223,8 +223,12 @@
 
   // Deal with operations which have composite or void types.
   if (BO->isCommaOp()) {
-if (!discard(LHS))
+if (!this->discard(LHS))
   return false;
+if (RHS->getType()->isVoidType())
+  return this->discard(RHS);
+
+// Otherwise, visit RHS and optionally discard its value.
 return Discard(this->visit(RHS));
   }
 
@@ -1642,10 +1646,12 @@
   if (!visit(Exp))
 return false;
 
+  if (Exp->getType()->isVoidType())
+return this->emitRetVoid(Exp);
+
   if (std::optional T = classify(Exp))
 return this->emitRet(*T, Exp);
-  else
-return this->emitRetValue(Exp);
+  return this->emitRetValue(Exp);
 }
 
 /// Toplevel visitDecl().


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -855,9 +855,23 @@
   (a); // expected-warning {{unused}} \
// ref-warning {{unused}}
 
+  (void)5, (void)6;
+
   return 0;
 }
 
+/// Ignored comma expressions still have their
+/// expressions evaluated.
+constexpr int Comma(int start) {
+int i = start;
+
+(void)i++;
+(void)i++,(void)i++;
+return i;
+}
+constexpr int Value = Comma(5);
+static_assert(Value == 8, "");
+
 #endif
 
 namespace PredefinedExprs {
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -223,8 +223,12 @@
 
   // Deal with operations which have composite or void types.
   if (BO->isCommaOp()) {
-if (!discard(LHS))
+if (!this->discard(LHS))
   return false;
+if (RHS->getType()->isVoidType())
+  return this->discard(RHS);
+
+// Otherwise, visit RHS and optionally discard its value.
 return Discard(this->visit(RHS));
   }
 
@@ -1642,10 +1646,12 @@
   if (!visit(Exp))
 return false;
 
+  if (Exp->getType()->isVoidType())
+return this->emitRetVoid(Exp);
+
   if (std::optional T = classify(Exp))
 return this->emitRet(*T, Exp);
-  else
-return this->emitRetValue(Exp);
+  return this->emitRetValue(Exp);
 }
 
 /// Toplevel visitDecl().
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] aed9646 - [clang][Interp] Fix discarding void-typed comma expressions

2023-07-25 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-07-26T07:45:02+02:00
New Revision: aed9646d8e29c1c5c86be65a2fd97029edf628d9

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

LOG: [clang][Interp] Fix discarding void-typed comma expressions

First, we need to handle void types in visitExpr, so we don't run into
an assertion there when we try to pop a return value from the stack
that isn't there.

Secondly, we need to handle it when visiting comma expressions so we
don't do the same thing there.

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/literals.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 40792fa6f4a284..5e42cca6762104 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -223,8 +223,12 @@ bool ByteCodeExprGen::VisitBinaryOperator(const 
BinaryOperator *BO) {
 
   // Deal with operations which have composite or void types.
   if (BO->isCommaOp()) {
-if (!discard(LHS))
+if (!this->discard(LHS))
   return false;
+if (RHS->getType()->isVoidType())
+  return this->discard(RHS);
+
+// Otherwise, visit RHS and optionally discard its value.
 return Discard(this->visit(RHS));
   }
 
@@ -1642,10 +1646,12 @@ bool ByteCodeExprGen::visitExpr(const Expr 
*Exp) {
   if (!visit(Exp))
 return false;
 
+  if (Exp->getType()->isVoidType())
+return this->emitRetVoid(Exp);
+
   if (std::optional T = classify(Exp))
 return this->emitRet(*T, Exp);
-  else
-return this->emitRetValue(Exp);
+  return this->emitRetValue(Exp);
 }
 
 /// Toplevel visitDecl().

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index f0513810eb4b7e..cf5e86658e3b38 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -855,9 +855,23 @@ constexpr int ignoredExprs() {
   (a); // expected-warning {{unused}} \
// ref-warning {{unused}}
 
+  (void)5, (void)6;
+
   return 0;
 }
 
+/// Ignored comma expressions still have their
+/// expressions evaluated.
+constexpr int Comma(int start) {
+int i = start;
+
+(void)i++;
+(void)i++,(void)i++;
+return i;
+}
+constexpr int Value = Comma(5);
+static_assert(Value == 8, "");
+
 #endif
 
 namespace PredefinedExprs {



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


[PATCH] D156277: [Parser][ObjC] Stop parsing on eof

2023-07-25 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/Parse/ParseObjc.cpp:749
+  if (!Tok.is(tok::eof))
+ConsumeToken();
   break;

Why is there a `ConsumeToken()` call at all here? The token is already being 
consumed in line 729.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156277

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


[PATCH] D147591: [clang][Interp] Handle CXXTemporaryObjectExprs

2023-07-25 Thread Timm Bäder 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 rGe45d1997686c: [clang][Interp] Handle CXXTemporaryObjectExprs 
(authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D147591?vs=520361=544213#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147591

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/test/AST/Interp/records.cpp

Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -311,16 +311,36 @@
 int Pos = 0;
 
 {
-  auto T = Test(Arr, Pos);
+  Test(Arr, Pos);
   // End of scope, should destroy Test.
 }
 
 return Arr[Index];
   }
-
   static_assert(T(0) == 1);
   static_assert(T(1) == 2);
   static_assert(T(2) == 3);
+
+  // Invalid destructor.
+  struct S {
+constexpr S() {}
+constexpr ~S() noexcept(false) { throw 12; } // expected-error {{cannot use 'throw'}} \
+ // expected-note {{declared here}} \
+ // ref-error {{cannot use 'throw'}} \
+ // ref-error {{never produces a constant expression}} \
+ // ref-note 2{{subexpression not valid}}
+  };
+
+  constexpr int f() {
+S{}; // ref-note {{in call to 'S{}.~S()'}}
+return 12; // expected-note {{undefined function '~S'}}
+  }
+  static_assert(f() == 12); // expected-error {{not an integral constant expression}} \
+// expected-note {{in call to 'f()'}} \
+// ref-error {{not an integral constant expression}} \
+// ref-note {{in call to 'f()'}}
+
+
 #endif
 }
 
@@ -572,17 +592,18 @@
 constexpr ~S() { // expected-error {{never produces a constant expression}} \
  // ref-error {{never produces a constant expression}}
   int i = 1 / 0; // expected-warning {{division by zero}} \
- // expected-note {{division by zero}} \
+ // expected-note 2{{division by zero}} \
  // ref-warning {{division by zero}} \
  // ref-note 2{{division by zero}}
 }
   };
   constexpr int testS() {
 S{}; // ref-note {{in call to 'S{}.~S()'}}
-return 1;
+return 1; // expected-note {{in call to '{}->~S()'}}
   // FIXME: ^ Wrong line
   }
   static_assert(testS() == 1); // expected-error {{not an integral constant expression}} \
+   // expected-note {{in call to 'testS()'}} \
// ref-error {{not an integral constant expression}} \
// ref-note {{in call to 'testS()'}}
 }
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -91,6 +91,8 @@
   bool VisitPointerCompoundAssignOperator(const CompoundAssignOperator *E);
   bool VisitExprWithCleanups(const ExprWithCleanups *E);
   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
+  bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E);
+  bool VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
   bool VisitTypeTraitExpr(const TypeTraitExpr *E);
   bool VisitLambdaExpr(const LambdaExpr *E);
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -886,6 +886,24 @@
   return false;
 }
 
+template 
+bool ByteCodeExprGen::VisitCXXBindTemporaryExpr(
+const CXXBindTemporaryExpr *E) {
+
+  return this->visit(E->getSubExpr());
+}
+
+template 
+bool ByteCodeExprGen::VisitCXXTemporaryObjectExpr(
+const CXXTemporaryObjectExpr *E) {
+
+  if (std::optional LocalIndex =
+  allocateLocal(E, /*IsExtended=*/false)) {
+return this->visitLocalInitializer(E, *LocalIndex);
+  }
+  return false;
+}
+
 template 
 bool ByteCodeExprGen::VisitCompoundLiteralExpr(
 const CompoundLiteralExpr *E) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] e45d199 - [clang][Interp] Handle CXXTemporaryObjectExprs

2023-07-25 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-07-26T07:36:26+02:00
New Revision: e45d1997686c6cb0f98c0dc00191d35b3d3e5f95

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

LOG: [clang][Interp] Handle CXXTemporaryObjectExprs

This is a CXXConstructExpr, so create a local temporary variable and
initialize it.

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/ByteCodeExprGen.h
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index d700a3e9be72bc..40792fa6f4a284 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -886,6 +886,24 @@ bool 
ByteCodeExprGen::VisitMaterializeTemporaryExpr(
   return false;
 }
 
+template 
+bool ByteCodeExprGen::VisitCXXBindTemporaryExpr(
+const CXXBindTemporaryExpr *E) {
+
+  return this->visit(E->getSubExpr());
+}
+
+template 
+bool ByteCodeExprGen::VisitCXXTemporaryObjectExpr(
+const CXXTemporaryObjectExpr *E) {
+
+  if (std::optional LocalIndex =
+  allocateLocal(E, /*IsExtended=*/false)) {
+return this->visitLocalInitializer(E, *LocalIndex);
+  }
+  return false;
+}
+
 template 
 bool ByteCodeExprGen::VisitCompoundLiteralExpr(
 const CompoundLiteralExpr *E) {

diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 57b0af9459e3ab..a031aaa9fae1dd 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -91,6 +91,8 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitPointerCompoundAssignOperator(const CompoundAssignOperator *E);
   bool VisitExprWithCleanups(const ExprWithCleanups *E);
   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
+  bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E);
+  bool VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
   bool VisitTypeTraitExpr(const TypeTraitExpr *E);
   bool VisitLambdaExpr(const LambdaExpr *E);

diff  --git a/clang/test/AST/Interp/records.cpp 
b/clang/test/AST/Interp/records.cpp
index d315e31a13e525..b708f5f6a00911 100644
--- a/clang/test/AST/Interp/records.cpp
+++ b/clang/test/AST/Interp/records.cpp
@@ -311,16 +311,36 @@ namespace InitializerTemporaries {
 int Pos = 0;
 
 {
-  auto T = Test(Arr, Pos);
+  Test(Arr, Pos);
   // End of scope, should destroy Test.
 }
 
 return Arr[Index];
   }
-
   static_assert(T(0) == 1);
   static_assert(T(1) == 2);
   static_assert(T(2) == 3);
+
+  // Invalid destructor.
+  struct S {
+constexpr S() {}
+constexpr ~S() noexcept(false) { throw 12; } // expected-error {{cannot 
use 'throw'}} \
+ // expected-note {{declared 
here}} \
+ // ref-error {{cannot use 
'throw'}} \
+ // ref-error {{never produces 
a constant expression}} \
+ // ref-note 2{{subexpression 
not valid}}
+  };
+
+  constexpr int f() {
+S{}; // ref-note {{in call to 'S{}.~S()'}}
+return 12; // expected-note {{undefined function '~S'}}
+  }
+  static_assert(f() == 12); // expected-error {{not an integral constant 
expression}} \
+// expected-note {{in call to 'f()'}} \
+// ref-error {{not an integral constant 
expression}} \
+// ref-note {{in call to 'f()'}}
+
+
 #endif
 }
 
@@ -572,17 +592,18 @@ namespace Destructors {
 constexpr ~S() { // expected-error {{never produces a constant 
expression}} \
  // ref-error {{never produces a constant expression}}
   int i = 1 / 0; // expected-warning {{division by zero}} \
- // expected-note {{division by zero}} \
+ // expected-note 2{{division by zero}} \
  // ref-warning {{division by zero}} \
  // ref-note 2{{division by zero}}
 }
   };
   constexpr int testS() {
 S{}; // ref-note {{in call to 'S{}.~S()'}}
-return 1;
+return 1; // expected-note {{in call to '{}->~S()'}}
   // FIXME: ^ Wrong line
   }
   static_assert(testS() == 1); // expected-error {{not an integral constant 
expression}} \
+   // expected-note {{in call to 'testS()'}} \
// ref-error {{not an integral constant 
expression}} \
// ref-note {{in call to 'testS()'}}
 }




[PATCH] D152793: [RISCV] Add MC layer support for Zicfiss.

2023-07-25 Thread Yeting Kuo via Phabricator via cfe-commits
fakepaper56 updated this revision to Diff 544212.
fakepaper56 marked 5 inline comments as done.
fakepaper56 added a comment.

Use RVInstI for SS_Push.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152793

Files:
  clang/test/Preprocessor/riscv-target-features.c
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
  llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h
  llvm/lib/Target/RISCV/RISCVFeatures.td
  llvm/lib/Target/RISCV/RISCVInstrInfo.td
  llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td
  llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp
  llvm/lib/Target/RISCV/RISCVRegisterInfo.td
  llvm/test/MC/RISCV/attribute-arch.s
  llvm/test/MC/RISCV/zicfiss-invalid.s
  llvm/test/MC/RISCV/zicfiss-valid.s

Index: llvm/test/MC/RISCV/zicfiss-valid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/zicfiss-valid.s
@@ -0,0 +1,110 @@
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zicfiss,+c -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zicfiss,+c -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-zicfiss,+c < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zicfiss -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+experimental-zicfiss,+c < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zicfiss -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+#
+# RUN: not llvm-mc -triple riscv32 -riscv-no-aliases -show-encoding < %s 2>&1 \
+# RUN: | FileCheck -check-prefixes=CHECK-NO-EXT %s
+# RUN: not llvm-mc -triple riscv64 -riscv-no-aliases -show-encoding < %s 2>&1 \
+# RUN: | FileCheck -check-prefixes=CHECK-NO-EXT %s
+
+# CHECK-ASM-AND-OBJ: ssload x1
+# CHECK-ASM: encoding: [0xf3,0x40,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload x1
+
+# CHECK-ASM-AND-OBJ: ssload x1
+# CHECK-ASM: encoding: [0xf3,0x40,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload ra
+
+# CHECK-ASM-AND-OBJ: ssload x5
+# CHECK-ASM: encoding: [0xf3,0x42,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload x5
+
+# CHECK-ASM-AND-OBJ: ssload x5
+# CHECK-ASM: encoding: [0xf3,0x42,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload t0
+
+# CHECK-ASM-AND-OBJ: sspopchk x1
+# CHECK-ASM: encoding: [0x73,0xc0,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk x1
+
+# CHECK-ASM-AND-OBJ: sspopchk x1
+# CHECK-ASM: encoding: [0x73,0xc0,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk ra
+
+# CHECK-ASM-AND-OBJ: sspopchk x5
+# CHECK-ASM: encoding: [0x73,0xc0,0xc2,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk x5
+
+# CHECK-ASM-AND-OBJ: sspopchk x5
+# CHECK-ASM: encoding: [0x73,0xc0,0xc2,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk t0
+
+# CHECK-ASM-AND-OBJ: sspinc 4
+# CHECK-ASM: encoding: [0x73,0x40,0xd2,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspinc 4
+
+# CHECK-ASM-AND-OBJ: sspush ra
+# CHECK-ASM: encoding: [0x73,0x40,0x10,0x8a]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush x1
+
+# CHECK-ASM-AND-OBJ: sspush ra
+# CHECK-ASM: encoding: [0x73,0x40,0x10,0x8a]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush ra
+
+# check-asm-and-obj: sspush t0
+# check-asm: encoding: [0x73,0x40,0x50,0x8a]
+# check-no-ext: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush x5
+
+# check-asm-and-obj: sspush t0
+# check-asm: encoding: [0x73,0x40,0x50,0x8a]
+# check-no-ext: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush t0
+
+# CHECK-ASM-AND-OBJ: ssprr ra
+# CHECK-ASM: encoding: [0xf3,0x40,0x00,0x86]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssprr ra
+
+# CHECK-ASM-AND-OBJ: ssamoswap t0, zero, (a0)
+# CHECK-ASM: encoding: [0xf3,0x42,0x05,0x82]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssamoswap t0, x0, (a0)
+
+# CHECK-ASM-AND-OBJ: c.sspush x1
+# CHECK-ASM: encoding: [0x81,0x60]
+# CHECK-NO-EXT: error: instruction requires the following: 'C' (Compressed Instructions), 'Zicfiss' 

[PATCH] D150040: [clang][Interp] Call invalid destructors

2023-07-25 Thread Timm Bäder 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 rG10020791b18f: [clang][Interp] Call invalid destructors 
(authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D150040?vs=520092=544211#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150040

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/records.cpp


Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -566,6 +566,25 @@
 return i;
   }
   static_assert(test() == 1);
+
+  struct S {
+constexpr S() {}
+constexpr ~S() { // expected-error {{never produces a constant 
expression}} \
+ // ref-error {{never produces a constant expression}}
+  int i = 1 / 0; // expected-warning {{division by zero}} \
+ // expected-note {{division by zero}} \
+ // ref-warning {{division by zero}} \
+ // ref-note 2{{division by zero}}
+}
+  };
+  constexpr int testS() {
+S{}; // ref-note {{in call to 'S{}.~S()'}}
+return 1;
+  // FIXME: ^ Wrong line
+  }
+  static_assert(testS() == 1); // expected-error {{not an integral constant 
expression}} \
+   // ref-error {{not an integral constant 
expression}} \
+   // ref-note {{in call to 'testS()'}}
 }
 
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2158,8 +2158,7 @@
   // Now emit the destructor and recurse into base classes.
   if (const CXXDestructorDecl *Dtor = R->getDestructor();
   Dtor && !Dtor->isTrivial()) {
-const Function *DtorFunc = getFunction(Dtor);
-if (DtorFunc && DtorFunc->isConstexpr()) {
+if (const Function *DtorFunc = getFunction(Dtor)) {
   assert(DtorFunc->hasThisPointer());
   assert(DtorFunc->getNumParams() == 1);
   if (!this->emitDupPtr(SourceInfo{}))


Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -566,6 +566,25 @@
 return i;
   }
   static_assert(test() == 1);
+
+  struct S {
+constexpr S() {}
+constexpr ~S() { // expected-error {{never produces a constant expression}} \
+ // ref-error {{never produces a constant expression}}
+  int i = 1 / 0; // expected-warning {{division by zero}} \
+ // expected-note {{division by zero}} \
+ // ref-warning {{division by zero}} \
+ // ref-note 2{{division by zero}}
+}
+  };
+  constexpr int testS() {
+S{}; // ref-note {{in call to 'S{}.~S()'}}
+return 1;
+  // FIXME: ^ Wrong line
+  }
+  static_assert(testS() == 1); // expected-error {{not an integral constant expression}} \
+   // ref-error {{not an integral constant expression}} \
+   // ref-note {{in call to 'testS()'}}
 }
 
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2158,8 +2158,7 @@
   // Now emit the destructor and recurse into base classes.
   if (const CXXDestructorDecl *Dtor = R->getDestructor();
   Dtor && !Dtor->isTrivial()) {
-const Function *DtorFunc = getFunction(Dtor);
-if (DtorFunc && DtorFunc->isConstexpr()) {
+if (const Function *DtorFunc = getFunction(Dtor)) {
   assert(DtorFunc->hasThisPointer());
   assert(DtorFunc->getNumParams() == 1);
   if (!this->emitDupPtr(SourceInfo{}))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 1002079 - [clang][Interp] Call invalid destructors

2023-07-25 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-07-26T07:19:02+02:00
New Revision: 10020791b18f344dc480b60712f6f3a5d63e86a2

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

LOG: [clang][Interp] Call invalid destructors

We need to call them like any other function, so we can generate proper
diagnostics.

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index c7c87d966cbe7f..d700a3e9be72bc 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2158,8 +2158,7 @@ bool 
ByteCodeExprGen::emitRecordDestruction(const Descriptor *Desc) {
   // Now emit the destructor and recurse into base classes.
   if (const CXXDestructorDecl *Dtor = R->getDestructor();
   Dtor && !Dtor->isTrivial()) {
-const Function *DtorFunc = getFunction(Dtor);
-if (DtorFunc && DtorFunc->isConstexpr()) {
+if (const Function *DtorFunc = getFunction(Dtor)) {
   assert(DtorFunc->hasThisPointer());
   assert(DtorFunc->getNumParams() == 1);
   if (!this->emitDupPtr(SourceInfo{}))

diff  --git a/clang/test/AST/Interp/records.cpp 
b/clang/test/AST/Interp/records.cpp
index fcdf75cfa9502b..d315e31a13e525 100644
--- a/clang/test/AST/Interp/records.cpp
+++ b/clang/test/AST/Interp/records.cpp
@@ -566,6 +566,25 @@ namespace Destructors {
 return i;
   }
   static_assert(test() == 1);
+
+  struct S {
+constexpr S() {}
+constexpr ~S() { // expected-error {{never produces a constant 
expression}} \
+ // ref-error {{never produces a constant expression}}
+  int i = 1 / 0; // expected-warning {{division by zero}} \
+ // expected-note {{division by zero}} \
+ // ref-warning {{division by zero}} \
+ // ref-note 2{{division by zero}}
+}
+  };
+  constexpr int testS() {
+S{}; // ref-note {{in call to 'S{}.~S()'}}
+return 1;
+  // FIXME: ^ Wrong line
+  }
+  static_assert(testS() == 1); // expected-error {{not an integral constant 
expression}} \
+   // ref-error {{not an integral constant 
expression}} \
+   // ref-note {{in call to 'testS()'}}
 }
 
 



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


[PATCH] D146368: [clang-tidy] Add readability-reference-to-constructed-temporary check

2023-07-25 Thread Shivam Gupta via Phabricator via cfe-commits
xgupta added a comment.

This LGTM, I will wait for two days before accepting the revision in case other 
reviewers might have some more comments/suggestions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146368

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


[PATCH] D152793: [RISCV] Add MC layer support for Zicfiss.

2023-07-25 Thread Yeting Kuo via Phabricator via cfe-commits
fakepaper56 updated this revision to Diff 544209.
fakepaper56 added a comment.

Address Craig's comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152793

Files:
  clang/test/Preprocessor/riscv-target-features.c
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
  llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h
  llvm/lib/Target/RISCV/RISCVFeatures.td
  llvm/lib/Target/RISCV/RISCVInstrInfo.td
  llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td
  llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp
  llvm/lib/Target/RISCV/RISCVRegisterInfo.td
  llvm/test/MC/RISCV/attribute-arch.s
  llvm/test/MC/RISCV/zicfiss-invalid.s
  llvm/test/MC/RISCV/zicfiss-valid.s

Index: llvm/test/MC/RISCV/zicfiss-valid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/zicfiss-valid.s
@@ -0,0 +1,110 @@
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zicfiss,+c -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zicfiss,+c -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-zicfiss,+c < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zicfiss -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+experimental-zicfiss,+c < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zicfiss -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+#
+# RUN: not llvm-mc -triple riscv32 -riscv-no-aliases -show-encoding < %s 2>&1 \
+# RUN: | FileCheck -check-prefixes=CHECK-NO-EXT %s
+# RUN: not llvm-mc -triple riscv64 -riscv-no-aliases -show-encoding < %s 2>&1 \
+# RUN: | FileCheck -check-prefixes=CHECK-NO-EXT %s
+
+# CHECK-ASM-AND-OBJ: ssload x1
+# CHECK-ASM: encoding: [0xf3,0x40,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload x1
+
+# CHECK-ASM-AND-OBJ: ssload x1
+# CHECK-ASM: encoding: [0xf3,0x40,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload ra
+
+# CHECK-ASM-AND-OBJ: ssload x5
+# CHECK-ASM: encoding: [0xf3,0x42,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload x5
+
+# CHECK-ASM-AND-OBJ: ssload x5
+# CHECK-ASM: encoding: [0xf3,0x42,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload t0
+
+# CHECK-ASM-AND-OBJ: sspopchk x1
+# CHECK-ASM: encoding: [0x73,0xc0,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk x1
+
+# CHECK-ASM-AND-OBJ: sspopchk x1
+# CHECK-ASM: encoding: [0x73,0xc0,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk ra
+
+# CHECK-ASM-AND-OBJ: sspopchk x5
+# CHECK-ASM: encoding: [0x73,0xc0,0xc2,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk x5
+
+# CHECK-ASM-AND-OBJ: sspopchk x5
+# CHECK-ASM: encoding: [0x73,0xc0,0xc2,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk t0
+
+# CHECK-ASM-AND-OBJ: sspinc 4
+# CHECK-ASM: encoding: [0x73,0x40,0xd2,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspinc 4
+
+# CHECK-ASM-AND-OBJ: sspush ra
+# CHECK-ASM: encoding: [0x73,0x40,0x10,0x8a]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush x1
+
+# CHECK-ASM-AND-OBJ: sspush ra
+# CHECK-ASM: encoding: [0x73,0x40,0x10,0x8a]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush ra
+
+# check-asm-and-obj: sspush t0
+# check-asm: encoding: [0x73,0x40,0x50,0x8a]
+# check-no-ext: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush x5
+
+# check-asm-and-obj: sspush t0
+# check-asm: encoding: [0x73,0x40,0x50,0x8a]
+# check-no-ext: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush t0
+
+# CHECK-ASM-AND-OBJ: ssprr ra
+# CHECK-ASM: encoding: [0xf3,0x40,0x00,0x86]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssprr ra
+
+# CHECK-ASM-AND-OBJ: ssamoswap t0, zero, (a0)
+# CHECK-ASM: encoding: [0xf3,0x42,0x05,0x82]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssamoswap t0, x0, (a0)
+
+# CHECK-ASM-AND-OBJ: c.sspush x1
+# CHECK-ASM: encoding: [0x81,0x60]
+# CHECK-NO-EXT: error: instruction requires the following: 'C' (Compressed Instructions), 'Zicfiss' (Shadow stack)
+c.sspush x1
+
+# 

[PATCH] D148690: [clang][Interp] Handle __extension__ unary operators

2023-07-25 Thread Timm Bäder 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 rG78e774e0c827: [clang][Interp] Handle __extension__ unary 
operators (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D148690?vs=514844=544207#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148690

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/literals.cpp


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -880,5 +880,16 @@
 static_assert(strings_match(__func__, "foo"), "");
 static_assert(strings_match(__PRETTY_FUNCTION__, "void 
PredefinedExprs::foo()"), "");
   }
+
+  constexpr char heh(unsigned index) {
+__FUNCTION__;   // ref-warning {{result unused}} \
+// expected-warning {{result unused}}
+__extension__ __FUNCTION__; // ref-warning {{result unused}} \
+// expected-warning {{result unused}}
+return __FUNCTION__[index];
+  }
+  static_assert(heh(0) == 'h', "");
+  static_assert(heh(1) == 'e', "");
+  static_assert(heh(2) == 'h', "");
 #endif
 }
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2004,6 +2004,9 @@
   case UO_Real:   // __real x
   case UO_Imag:   // __imag x
   case UO_Extension:
+if (DiscardResult)
+  return this->discard(SubExpr);
+return this->visit(SubExpr);
   case UO_Coawait:
 assert(false && "Unhandled opcode");
   }


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -880,5 +880,16 @@
 static_assert(strings_match(__func__, "foo"), "");
 static_assert(strings_match(__PRETTY_FUNCTION__, "void PredefinedExprs::foo()"), "");
   }
+
+  constexpr char heh(unsigned index) {
+__FUNCTION__;   // ref-warning {{result unused}} \
+// expected-warning {{result unused}}
+__extension__ __FUNCTION__; // ref-warning {{result unused}} \
+// expected-warning {{result unused}}
+return __FUNCTION__[index];
+  }
+  static_assert(heh(0) == 'h', "");
+  static_assert(heh(1) == 'e', "");
+  static_assert(heh(2) == 'h', "");
 #endif
 }
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2004,6 +2004,9 @@
   case UO_Real:   // __real x
   case UO_Imag:   // __imag x
   case UO_Extension:
+if (DiscardResult)
+  return this->discard(SubExpr);
+return this->visit(SubExpr);
   case UO_Coawait:
 assert(false && "Unhandled opcode");
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 78e774e - [clang][Interp] Handle __extension__ unary operators

2023-07-25 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-07-26T07:16:45+02:00
New Revision: 78e774e0c827803ce917da7f1cbdbb40892a1788

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

LOG: [clang][Interp] Handle __extension__ unary operators

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/literals.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index d2995fb57d8bef..c7c87d966cbe7f 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2004,6 +2004,9 @@ bool ByteCodeExprGen::VisitUnaryOperator(const 
UnaryOperator *E) {
   case UO_Real:   // __real x
   case UO_Imag:   // __imag x
   case UO_Extension:
+if (DiscardResult)
+  return this->discard(SubExpr);
+return this->visit(SubExpr);
   case UO_Coawait:
 assert(false && "Unhandled opcode");
   }

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index 5df7b7e5e6e8b0..f0513810eb4b7e 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -880,5 +880,16 @@ namespace PredefinedExprs {
 static_assert(strings_match(__func__, "foo"), "");
 static_assert(strings_match(__PRETTY_FUNCTION__, "void 
PredefinedExprs::foo()"), "");
   }
+
+  constexpr char heh(unsigned index) {
+__FUNCTION__;   // ref-warning {{result unused}} \
+// expected-warning {{result unused}}
+__extension__ __FUNCTION__; // ref-warning {{result unused}} \
+// expected-warning {{result unused}}
+return __FUNCTION__[index];
+  }
+  static_assert(heh(0) == 'h', "");
+  static_assert(heh(1) == 'e', "");
+  static_assert(heh(2) == 'h', "");
 #endif
 }



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


[clang] 5b78868 - [clang][Interp][NFC] Make some locals const

2023-07-25 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-07-26T07:12:47+02:00
New Revision: 5b78868661f42a70fa3006b1db41f78a6178d596

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

LOG: [clang][Interp][NFC] Make some locals const

Added: 


Modified: 
clang/lib/AST/Interp/Context.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Context.cpp 
b/clang/lib/AST/Interp/Context.cpp
index 2e5d721590edc6..d025586d91b7d3 100644
--- a/clang/lib/AST/Interp/Context.cpp
+++ b/clang/lib/AST/Interp/Context.cpp
@@ -134,13 +134,13 @@ std::optional Context::classify(QualType T) 
const {
   if (T->isReferenceType() || T->isPointerType())
 return PT_Ptr;
 
-  if (auto *AT = dyn_cast(T))
+  if (const auto *AT = dyn_cast(T))
 return classify(AT->getValueType());
 
-  if (auto *DT = dyn_cast(T))
+  if (const auto *DT = dyn_cast(T))
 return classify(DT->getUnderlyingType());
 
-  if (auto *DT = dyn_cast(T))
+  if (const auto *DT = dyn_cast(T))
 return classify(DT->getPointeeType());
 
   return {};



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


[PATCH] D146368: [clang-tidy] Add readability-reference-to-constructed-temporary check

2023-07-25 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL updated this revision to Diff 544205.
PiotrZSL marked an inline comment as done.
PiotrZSL added a comment.

Rename value to str in doc.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146368

Files:
  clang-tools-extra/clang-tidy/readability/CMakeLists.txt
  clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
  
clang-tools-extra/clang-tidy/readability/ReferenceToConstructedTemporaryCheck.cpp
  
clang-tools-extra/clang-tidy/readability/ReferenceToConstructedTemporaryCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/docs/clang-tidy/checks/readability/reference-to-constructed-temporary.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability/reference-to-constructed-temporary.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability/reference-to-constructed-temporary.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability/reference-to-constructed-temporary.cpp
@@ -0,0 +1,30 @@
+// RUN: %check_clang_tidy -std=c++11-or-later %s readability-reference-to-constructed-temporary %t
+
+struct WithConstructor
+{
+WithConstructor(int, int);
+};
+
+struct WithoutConstructor
+{
+int a, b;
+};
+
+void test()
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:27: warning: reference variable 'tmp1' extends the lifetime of a just-constructed temporary object 'const WithConstructor', consider changing reference to value [readability-reference-to-constructed-temporary]
+   const WithConstructor& tmp1{1,2};
+
+// CHECK-MESSAGES: :[[@LINE+1]]:30: warning: reference variable 'tmp2' extends the lifetime of a just-constructed temporary object 'const WithoutConstructor', consider changing reference to value [readability-reference-to-constructed-temporary]
+   const WithoutConstructor& tmp2{1,2};
+
+
+// CHECK-MESSAGES: :[[@LINE+1]]:22: warning: reference variable 'tmp3' extends the lifetime of a just-constructed temporary object 'WithConstructor', consider changing reference to value [readability-reference-to-constructed-temporary]
+   WithConstructor&& tmp3{1,2};
+
+// CHECK-MESSAGES: :[[@LINE+1]]:25: warning: reference variable 'tmp4' extends the lifetime of a just-constructed temporary object 'WithoutConstructor', consider changing reference to value [readability-reference-to-constructed-temporary]
+   WithoutConstructor&& tmp4{1,2};
+
+   WithConstructor tmp5{1,2};
+   WithoutConstructor tmp6{1,2};
+}
Index: clang-tools-extra/docs/clang-tidy/checks/readability/reference-to-constructed-temporary.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/readability/reference-to-constructed-temporary.rst
@@ -0,0 +1,32 @@
+.. title:: clang-tidy - readability-reference-to-constructed-temporary
+
+readability-reference-to-constructed-temporary
+==
+
+Detects C++ code where a reference variable is used to extend the lifetime of
+a temporary object that has just been constructed.
+
+This construction is often the result of multiple code refactorings or a lack
+of developer knowledge, leading to confusion or subtle bugs. In most cases,
+what the developer really wanted to do is create a new variable rather than
+extending the lifetime of a temporary object.
+
+Examples of problematic code include:
+
+.. code-block:: c++
+
+   const std::string& str("hello");
+
+   struct Point { int x; int y; };
+   const Point& p = { 1, 2 };
+
+In the first example, a ``const std::string&`` reference variable ``str`` is
+assigned a temporary object created by the ``std::string("hello")``
+constructor. In the second example, a ``const Point&`` reference variable ``p``
+is assigned an object that is constructed from an initializer list ``{ 1, 2 }``.
+Both of these examples extend the lifetime of the temporary object to the
+lifetime of the reference variable, which can make it difficult to reason about
+and may lead to subtle bugs or misunderstanding.
+
+To avoid these issues, it is recommended to change the reference variable to a
+(``const``) value variable.
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -379,6 +379,7 @@
`readability-redundant-smartptr-get `_, "Yes"
`readability-redundant-string-cstr `_, "Yes"
`readability-redundant-string-init `_, "Yes"
+   `readability-reference-to-constructed-temporary `_,
`readability-simplify-boolean-expr `_, "Yes"
`readability-simplify-subscript-expr `_, "Yes"
`readability-static-accessed-through-instance `_, "Yes"
Index: clang-tools-extra/docs/ReleaseNotes.rst

[PATCH] D146368: [clang-tidy] Add readability-reference-to-constructed-temporary check

2023-07-25 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL marked 2 inline comments as done.
PiotrZSL added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability/reference-to-constructed-temporary.rst:18
+
+   const std::string& value("hello");
+

xgupta wrote:
> PiotrZSL wrote:
> > xgupta wrote:
> > > The below comment is not matching,  do you want to write - 
> > > `const std::string& str = std::string("hello");`
> > > ?
> > actually comment is +- fine, constructor to std::string will be called 
> > anyway, and for compiler I think those 2 are equal.
> > Will verify.
> but you have written below `reference variable ``str`` is assigned a 
> temporary object` and there is no str variable.
Ok, that's actually a bug. It's `value`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146368

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


[PATCH] D144164: [clang][Interp] Handle PtrMemOps

2023-07-25 Thread Timm Bäder 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 rG8cb6e476ccaa: [clang][Interp] Handle PtrMemOps (authored by 
tbaeder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144164

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/Context.cpp
  clang/lib/AST/Interp/Interp.h
  clang/test/AST/Interp/literals.cpp
  clang/test/AST/Interp/records.cpp

Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -689,5 +689,52 @@
 // ref-note {{initializer of 'D2' is not a constant expression}}
 
 }
+
+namespace VirtualFunctionPointers {
+  struct S {
+virtual constexpr int func() const { return 1; }
+  };
+
+  struct Middle : S {
+constexpr Middle(int i) : i(i) {}
+int i;
+  };
+
+  struct Other {
+constexpr Other(int k) : k(k) {}
+int k;
+  };
+
+  struct S2 : Middle, Other {
+int j;
+constexpr S2(int i, int j, int k) : Middle(i), Other(k), j(j) {}
+virtual constexpr int func() const { return i + j + k  + S::func(); }
+  };
+
+  constexpr S s;
+  constexpr decltype(::func) foo = ::func;
+  constexpr int value = (s.*foo)();
+  static_assert(value == 1);
+
+
+  constexpr S2 s2(1, 2, 3);
+  static_assert(s2.i == 1);
+  static_assert(s2.j == 2);
+  static_assert(s2.k == 3);
+
+  constexpr int value2 = s2.func();
+  constexpr int value3 = (s2.*foo)();
+  static_assert(value3 == 7);
+
+  constexpr int dynamicDispatch(const S ) {
+constexpr decltype(::func) SFunc = ::func;
+
+return (s.*SFunc)();
+  }
+
+  static_assert(dynamicDispatch(s) == 1);
+  static_assert(dynamicDispatch(s2) == 7);
+};
+
 };
 #endif
Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -149,13 +149,10 @@
 // ref-error{{to a function type}}
 
 
-
-  /// FIXME: The following code should be accepted.
   struct S {
 void func();
   };
-  constexpr void (S::*Func)() = ::func; // expected-error {{must be initialized by a constant expression}} \
-  // expected-error {{interpreter failed to evaluate an expression}}
+  constexpr void (S::*Func)() = ::func;
   static_assert(sizeof(Func) == sizeof(::func), "");
 
 
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -1716,6 +1716,9 @@
   if (!F || !F->isConstexpr())
 return false;
 
+  if (F->isVirtual())
+return CallVirt(S, OpPC, F);
+
   return Call(S, OpPC, F);
 }
 
Index: clang/lib/AST/Interp/Context.cpp
===
--- clang/lib/AST/Interp/Context.cpp
+++ clang/lib/AST/Interp/Context.cpp
@@ -88,12 +88,6 @@
 const LangOptions ::getLangOpts() const { return Ctx.getLangOpts(); }
 
 std::optional Context::classify(QualType T) const {
-  if (T->isFunctionPointerType() || T->isFunctionReferenceType())
-return PT_FnPtr;
-
-  if (T->isReferenceType() || T->isPointerType())
-return PT_Ptr;
-
   if (T->isBooleanType())
 return PT_Bool;
 
@@ -133,9 +127,22 @@
   if (T->isFloatingType())
 return PT_Float;
 
+  if (T->isFunctionPointerType() || T->isFunctionReferenceType() ||
+  T->isFunctionType())
+return PT_FnPtr;
+
+  if (T->isReferenceType() || T->isPointerType())
+return PT_Ptr;
+
   if (auto *AT = dyn_cast(T))
 return classify(AT->getValueType());
 
+  if (auto *DT = dyn_cast(T))
+return classify(DT->getUnderlyingType());
+
+  if (auto *DT = dyn_cast(T))
+return classify(DT->getPointeeType());
+
   return {};
 }
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -207,13 +207,13 @@
   const Expr *LHS = BO->getLHS();
   const Expr *RHS = BO->getRHS();
 
+  if (BO->isPtrMemOp())
+return this->visit(RHS);
+
   // Typecheck the args.
   std::optional LT = classify(LHS->getType());
   std::optional RT = classify(RHS->getType());
   std::optional T = classify(BO->getType());
-  if (!LT || !RT || !T) {
-return this->bail(BO);
-  }
 
   auto Discard = [this, T, BO](bool Result) {
 if (!Result)
@@ -228,6 +228,9 @@
 return Discard(this->visit(RHS));
   }
 
+  if (!LT || !RT || !T)
+return this->bail(BO);
+
   // Pointer arithmetic special case.
   if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub) {
 if (T == PT_Ptr || (LT == PT_Ptr && RT == PT_Ptr))

[clang] 8cb6e47 - [clang][Interp] Handle PtrMemOps

2023-07-25 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-07-26T07:04:21+02:00
New Revision: 8cb6e476ccaa62b2621a5f68689a6070592f221d

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

LOG: [clang][Interp] Handle PtrMemOps

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/Context.cpp
clang/lib/AST/Interp/Interp.h
clang/test/AST/Interp/literals.cpp
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 9f3eb158576fd8..d2995fb57d8bef 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -207,13 +207,13 @@ bool ByteCodeExprGen::VisitBinaryOperator(const 
BinaryOperator *BO) {
   const Expr *LHS = BO->getLHS();
   const Expr *RHS = BO->getRHS();
 
+  if (BO->isPtrMemOp())
+return this->visit(RHS);
+
   // Typecheck the args.
   std::optional LT = classify(LHS->getType());
   std::optional RT = classify(RHS->getType());
   std::optional T = classify(BO->getType());
-  if (!LT || !RT || !T) {
-return this->bail(BO);
-  }
 
   auto Discard = [this, T, BO](bool Result) {
 if (!Result)
@@ -228,6 +228,9 @@ bool ByteCodeExprGen::VisitBinaryOperator(const 
BinaryOperator *BO) {
 return Discard(this->visit(RHS));
   }
 
+  if (!LT || !RT || !T)
+return this->bail(BO);
+
   // Pointer arithmetic special case.
   if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub) {
 if (T == PT_Ptr || (LT == PT_Ptr && RT == PT_Ptr))

diff  --git a/clang/lib/AST/Interp/Context.cpp 
b/clang/lib/AST/Interp/Context.cpp
index eeb7fa9379f5cc..2e5d721590edc6 100644
--- a/clang/lib/AST/Interp/Context.cpp
+++ b/clang/lib/AST/Interp/Context.cpp
@@ -88,12 +88,6 @@ bool Context::evaluateAsInitializer(State , const 
VarDecl *VD,
 const LangOptions ::getLangOpts() const { return Ctx.getLangOpts(); }
 
 std::optional Context::classify(QualType T) const {
-  if (T->isFunctionPointerType() || T->isFunctionReferenceType())
-return PT_FnPtr;
-
-  if (T->isReferenceType() || T->isPointerType())
-return PT_Ptr;
-
   if (T->isBooleanType())
 return PT_Bool;
 
@@ -133,9 +127,22 @@ std::optional Context::classify(QualType T) 
const {
   if (T->isFloatingType())
 return PT_Float;
 
+  if (T->isFunctionPointerType() || T->isFunctionReferenceType() ||
+  T->isFunctionType())
+return PT_FnPtr;
+
+  if (T->isReferenceType() || T->isPointerType())
+return PT_Ptr;
+
   if (auto *AT = dyn_cast(T))
 return classify(AT->getValueType());
 
+  if (auto *DT = dyn_cast(T))
+return classify(DT->getUnderlyingType());
+
+  if (auto *DT = dyn_cast(T))
+return classify(DT->getPointeeType());
+
   return {};
 }
 

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index ff67e873a08445..0acaf764353215 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1716,6 +1716,9 @@ inline bool CallPtr(InterpState , CodePtr OpPC) {
   if (!F || !F->isConstexpr())
 return false;
 
+  if (F->isVirtual())
+return CallVirt(S, OpPC, F);
+
   return Call(S, OpPC, F);
 }
 

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index b9d1d2d59d11a3..5df7b7e5e6e8b0 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -149,13 +149,10 @@ namespace SizeOf {
 // ref-error{{to a function type}}
 
 
-
-  /// FIXME: The following code should be accepted.
   struct S {
 void func();
   };
-  constexpr void (S::*Func)() = ::func; // expected-error {{must be 
initialized by a constant expression}} \
-  // expected-error {{interpreter 
failed to evaluate an expression}}
+  constexpr void (S::*Func)() = ::func;
   static_assert(sizeof(Func) == sizeof(::func), "");
 
 

diff  --git a/clang/test/AST/Interp/records.cpp 
b/clang/test/AST/Interp/records.cpp
index 5fd423eff025be..fcdf75cfa9502b 100644
--- a/clang/test/AST/Interp/records.cpp
+++ b/clang/test/AST/Interp/records.cpp
@@ -689,5 +689,52 @@ namespace CtorDtor {
 // ref-note {{initializer of 'D2' is not a 
constant expression}}
 
 }
+
+namespace VirtualFunctionPointers {
+  struct S {
+virtual constexpr int func() const { return 1; }
+  };
+
+  struct Middle : S {
+constexpr Middle(int i) : i(i) {}
+int i;
+  };
+
+  struct Other {
+constexpr Other(int k) : k(k) {}
+int k;
+  };
+
+  struct S2 : Middle, Other {
+int j;
+constexpr S2(int i, int j, int k) : Middle(i), Other(k), j(j) {}
+virtual constexpr int func() const { return i + j + k  + S::func(); }
+  };
+
+  

[PATCH] D152054: [OpenMP] Codegen support for thread_limit on target directive

2023-07-25 Thread Sandeep via Phabricator via cfe-commits
sandeepkosuri updated this revision to Diff 544201.
sandeepkosuri added a comment.

Explicitly mentioned `-fopenmp-version=51` in LIT test cases


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152054

Files:
  clang/include/clang/Basic/OpenMPKinds.h
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/test/OpenMP/target_codegen.cpp
  clang/test/OpenMP/target_parallel_for_simd_tl_codegen.cpp
  clang/test/OpenMP/target_parallel_for_tl_codegen.cpp
  clang/test/OpenMP/target_parallel_generic_loop_tl_codegen.cpp
  clang/test/OpenMP/target_parallel_tl_codegen.cpp
  clang/test/OpenMP/target_simd_tl_codegen.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td
  llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
  openmp/runtime/src/kmp.h
  openmp/runtime/src/kmp_csupport.cpp
  openmp/runtime/src/kmp_ftn_entry.h
  openmp/runtime/src/kmp_global.cpp
  openmp/runtime/src/kmp_runtime.cpp
  openmp/runtime/test/target/target_thread_limit.cpp

Index: openmp/runtime/test/target/target_thread_limit.cpp
===
--- /dev/null
+++ openmp/runtime/test/target/target_thread_limit.cpp
@@ -0,0 +1,168 @@
+// RUN: %libomp-cxx-compile -fopenmp-version=51
+// RUN: %libomp-run | FileCheck %s --check-prefix OMP51
+
+#include 
+#include 
+
+void foo() {
+#pragma omp parallel num_threads(10)
+  { printf("\ntarget: foo(): parallel num_threads(10)"); }
+}
+
+int main(void) {
+
+  int tl = 4;
+  printf("\nmain: thread_limit = %d", omp_get_thread_limit());
+  // OMP51: main: thread_limit = {{[0-9]+}}
+
+#pragma omp target thread_limit(tl)
+  {
+printf("\ntarget: thread_limit = %d", omp_get_thread_limit());
+// OMP51: target: thread_limit = 4
+// check whether thread_limit is honoured
+#pragma omp parallel
+{ printf("\ntarget: parallel"); }
+// OMP51: target: parallel
+// OMP51: target: parallel
+// OMP51: target: parallel
+// OMP51: target: parallel
+// OMP51-NOT: target: parallel
+
+// check whether num_threads is honoured
+#pragma omp parallel num_threads(2)
+{ printf("\ntarget: parallel num_threads(2)"); }
+// OMP51: target: parallel num_threads(2)
+// OMP51: target: parallel num_threads(2)
+// OMP51-NOT: target: parallel num_threads(2)
+
+// check whether thread_limit is honoured when there is a conflicting
+// num_threads
+#pragma omp parallel num_threads(10)
+{ printf("\ntarget: parallel num_threads(10)"); }
+// OMP51: target: parallel num_threads(10)
+// OMP51: target: parallel num_threads(10)
+// OMP51: target: parallel num_threads(10)
+// OMP51: target: parallel num_threads(10)
+// OMP51-NOT: target: parallel num_threads(10)
+
+// check whether threads are limited across functions
+foo();
+// OMP51: target: foo(): parallel num_threads(10)
+// OMP51: target: foo(): parallel num_threads(10)
+// OMP51: target: foo(): parallel num_threads(10)
+// OMP51: target: foo(): parallel num_threads(10)
+// OMP51-NOT: target: foo(): parallel num_threads(10)
+
+// check if user can set num_threads at runtime
+omp_set_num_threads(2);
+#pragma omp parallel
+{ printf("\ntarget: parallel with omp_set_num_thread(2)"); }
+// OMP51: target: parallel with omp_set_num_thread(2)
+// OMP51: target: parallel with omp_set_num_thread(2)
+// OMP51-NOT: target: parallel with omp_set_num_thread(2)
+
+// make sure thread_limit is unaffected by omp_set_num_threads
+printf("\ntarget: thread_limit = %d", omp_get_thread_limit());
+// OMP51: target: thread_limit = 4
+  }
+
+// checking consecutive target regions with different thread_limits
+#pragma omp target thread_limit(3)
+  {
+printf("\nsecond target: thread_limit = %d", omp_get_thread_limit());
+// OMP51: second target: thread_limit = 3
+#pragma omp parallel
+{ printf("\nsecond target: parallel"); }
+// OMP51: second target: parallel
+// OMP51: second target: parallel
+// OMP51: second target: parallel
+// OMP51-NOT: second target: parallel
+  }
+
+  // confirm that thread_limit's effects are limited to target region
+  printf("\nmain: thread_limit = %d", omp_get_thread_limit());
+  // OMP51: main: thread_limit = {{[0-9]+}}
+#pragma omp parallel num_threads(10)
+  { printf("\nmain: parallel num_threads(10)"); }
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51: main: parallel num_threads(10)
+  // OMP51-NOT: main: parallel num_threads(10)
+
+// check combined target directives which support thread_limit
+// 

[PATCH] D156027: [clang][Interp] Rework how initializers work

2023-07-25 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

Note that this patch also supercedes:

1. https://reviews.llvm.org/D153616
2. https://reviews.llvm.org/D153653
3. https://reviews.llvm.org/D147591

since it handles those cases more generally.




Comment at: clang/lib/AST/Interp/Context.cpp:131
   if (T->isFunctionPointerType() || T->isFunctionReferenceType() ||
-  T->isFunctionType())
+  T->isFunctionType() || 
T->isSpecificBuiltinType(BuiltinType::BoundMember))
 return PT_FnPtr;

I've removed this change in https://reviews.llvm.org/D144164 since it didn't  
seem necessary, but it //is// necessary after applying this patch.


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

https://reviews.llvm.org/D156027

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


[PATCH] D142569: [OpenMP] Introduce kernel environment

2023-07-25 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 updated this revision to Diff 544183.
tianshilei1992 added a comment.

rebase and fix test issues


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142569

Files:
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/test/OpenMP/amdgcn_target_codegen.cpp
  clang/test/OpenMP/amdgcn_target_device_vla.cpp
  clang/test/OpenMP/amdgpu_target_with_aligned_attribute.c
  clang/test/OpenMP/declare_target_codegen_globalization.cpp
  clang/test/OpenMP/nvptx_SPMD_codegen.cpp
  clang/test/OpenMP/nvptx_data_sharing.cpp
  clang/test/OpenMP/nvptx_distribute_parallel_generic_mode_codegen.cpp
  clang/test/OpenMP/nvptx_lambda_capturing.cpp
  clang/test/OpenMP/nvptx_multi_target_parallel_codegen.cpp
  clang/test/OpenMP/nvptx_nested_parallel_codegen.cpp
  clang/test/OpenMP/nvptx_parallel_codegen.cpp
  clang/test/OpenMP/nvptx_parallel_for_codegen.cpp
  clang/test/OpenMP/nvptx_target_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_num_threads_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_proc_bind_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_reduction_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_reduction_codegen_tbaa_PR46146.cpp
  clang/test/OpenMP/nvptx_target_printf_codegen.c
  clang/test/OpenMP/nvptx_target_simd_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_distribute_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_distribute_parallel_for_codegen.cpp
  
clang/test/OpenMP/nvptx_target_teams_distribute_parallel_for_generic_mode_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_distribute_parallel_for_simd_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_distribute_simd_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_generic_loop_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_generic_loop_generic_mode_codegen.cpp
  clang/test/OpenMP/nvptx_teams_codegen.cpp
  clang/test/OpenMP/nvptx_teams_reduction_codegen.cpp
  clang/test/OpenMP/reduction_implicit_map.cpp
  clang/test/OpenMP/remarks_parallel_in_multiple_target_state_machines.c
  clang/test/OpenMP/remarks_parallel_in_target_state_machine.c
  clang/test/OpenMP/target_parallel_debug_codegen.cpp
  clang/test/OpenMP/target_parallel_for_debug_codegen.cpp
  clang/test/OpenMP/target_parallel_generic_loop_codegen-3.cpp
  clang/test/OpenMP/target_parallel_generic_loop_codegen.cpp
  clang/test/OpenMP/target_teams_generic_loop_codegen.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/lib/Transforms/IPO/OpenMPOpt.cpp
  llvm/test/Transforms/Attributor/reduced/aa_execution_domain_wrong_fn.ll
  llvm/test/Transforms/Attributor/value-simplify-local-remote.ll
  llvm/test/Transforms/OpenMP/add_attributes.ll
  llvm/test/Transforms/OpenMP/always_inline_device.ll
  llvm/test/Transforms/OpenMP/custom_state_machines.ll
  llvm/test/Transforms/OpenMP/custom_state_machines_pre_lto.ll
  llvm/test/Transforms/OpenMP/custom_state_machines_remarks.ll
  llvm/test/Transforms/OpenMP/deduplication_target.ll
  llvm/test/Transforms/OpenMP/get_hardware_num_threads_in_block_fold.ll
  llvm/test/Transforms/OpenMP/get_hardware_num_threads_in_block_fold_optnone.ll
  llvm/test/Transforms/OpenMP/global_constructor.ll
  llvm/test/Transforms/OpenMP/globalization_remarks.ll
  llvm/test/Transforms/OpenMP/gpu_state_machine_function_ptr_replacement.ll
  llvm/test/Transforms/OpenMP/is_spmd_exec_mode_fold.ll
  llvm/test/Transforms/OpenMP/nested_parallelism.ll
  llvm/test/Transforms/OpenMP/parallel_level_fold.ll
  llvm/test/Transforms/OpenMP/remove_globalization.ll
  llvm/test/Transforms/OpenMP/replace_globalization.ll
  llvm/test/Transforms/OpenMP/single_threaded_execution.ll
  llvm/test/Transforms/OpenMP/spmdization.ll
  llvm/test/Transforms/OpenMP/spmdization_assumes.ll
  llvm/test/Transforms/OpenMP/spmdization_constant_prop.ll
  llvm/test/Transforms/OpenMP/spmdization_guarding.ll
  llvm/test/Transforms/OpenMP/spmdization_guarding_two_reaching_kernels.ll
  llvm/test/Transforms/OpenMP/spmdization_no_guarding_two_reaching_kernels.ll
  llvm/test/Transforms/OpenMP/spmdization_remarks.ll
  llvm/test/Transforms/OpenMP/value-simplify-openmp-opt.ll
  llvm/test/Transforms/PhaseOrdering/openmp-opt-module.ll
  llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
  mlir/test/Target/LLVMIR/omptarget-region-device-llvm.mlir
  openmp/libomptarget/DeviceRTL/CMakeLists.txt
  openmp/libomptarget/DeviceRTL/include/Debug.h
  openmp/libomptarget/DeviceRTL/include/Interface.h
  openmp/libomptarget/DeviceRTL/include/State.h
  openmp/libomptarget/DeviceRTL/src/Configuration.cpp
  openmp/libomptarget/DeviceRTL/src/Debug.cpp
  openmp/libomptarget/DeviceRTL/src/Kernel.cpp
  openmp/libomptarget/DeviceRTL/src/State.cpp
  openmp/libomptarget/include/DeviceEnvironment.h
  openmp/libomptarget/include/Environment.h
  

[PATCH] D156223: [RISCV] Resolve a few bugs in RISCVVIntrinsicUtils.cpp

2023-07-25 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng added a comment.

Does it possible to add a precommit test case to show that we accept unexpected 
combination of the type?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156223

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


[clang] c56514f - Reland "[LoongArch] Support -march=native and -mtune="

2023-07-25 Thread Weining Lu via cfe-commits

Author: Weining Lu
Date: 2023-07-26T10:26:38+08:00
New Revision: c56514f21b2cf08eaa7ac3a57ba4ce403a9c8956

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

LOG: Reland "[LoongArch] Support -march=native and -mtune="

As described in [1][2], `-mtune=` is used to select the type of target
microarchitecture, defaults to the value of `-march`. The set of
possible values should be a superset of `-march` values. Currently
possible values of `-march=` and `-mtune=` are `native`, `loongarch64`
and `la464`.

D136146 has supported `-march={loongarch64,la464}` and this patch adds
support for `-march=native` and `-mtune=`.

A new ProcessorModel called `loongarch64` is defined in LoongArch.td
to support `-mtune=loongarch64`.

`llvm::sys::getHostCPUName()` returns `generic` on unknown or future
LoongArch CPUs, e.g. the not yet added `la664`, leading to
`llvm::LoongArch::isValidArchName()` failing to parse the arch name.
In this case, use `loongarch64` as the default arch name for 64-bit
CPUs.

And these two preprocessor macros are defined:
- __loongarch_arch
- __loongarch_tune

[1]: 
https://github.com/loongson/LoongArch-Documentation/blob/2023.04.20/docs/LoongArch-toolchain-conventions-EN.adoc
[2]: 
https://github.com/loongson/la-softdev-convention/blob/v0.1/la-softdev-convention.adoc

Reviewed By: xen0n, wangleiat

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

Added: 
clang/test/Driver/loongarch-mtune-error.c
clang/test/Driver/loongarch-mtune.c
llvm/test/CodeGen/LoongArch/cpus-invalid.ll
llvm/test/CodeGen/LoongArch/cpus.ll

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Basic/Targets/LoongArch.cpp
clang/lib/Basic/Targets/LoongArch.h
clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Preprocessor/init-loongarch.c
llvm/include/llvm/TargetParser/LoongArchTargetParser.h
llvm/lib/Target/LoongArch/LoongArch.td
llvm/lib/TargetParser/LoongArchTargetParser.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6a762a6e92eb5a..98f50b428c2dc3 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -139,6 +139,9 @@ Windows Support
 LoongArch Support
 ^
 
+- The ``-march=native`` ``-mtune=`` options and ``__loongarch_{arch,tune}``
+  macros are now supported.
+
 RISC-V Support
 ^^
 

diff  --git a/clang/lib/Basic/Targets/LoongArch.cpp 
b/clang/lib/Basic/Targets/LoongArch.cpp
index 6958479cd7c42d..f08e5e732b0354 100644
--- a/clang/lib/Basic/Targets/LoongArch.cpp
+++ b/clang/lib/Basic/Targets/LoongArch.cpp
@@ -15,7 +15,7 @@
 #include "clang/Basic/MacroBuilder.h"
 #include "clang/Basic/TargetBuiltins.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/TargetParser/TargetParser.h"
+#include "llvm/TargetParser/LoongArchTargetParser.h"
 
 using namespace clang;
 using namespace clang::targets;
@@ -198,7 +198,19 @@ void LoongArchTargetInfo::getTargetDefines(const 
LangOptions ,
   else
 Builder.defineMacro("__loongarch_frlen", "0");
 
-  // TODO: define __loongarch_arch and __loongarch_tune.
+  // Define __loongarch_arch.
+  StringRef Arch = llvm::LoongArch::getArch();
+  if (Arch.empty())
+Arch = llvm::LoongArch::getDefaultArch(GRLen == 64);
+  if (!Arch.empty())
+Builder.defineMacro("__loongarch_arch", Arch);
+
+  // Define __loongarch_tune.
+  StringRef TuneCPU = llvm::LoongArch::getTuneCPU();
+  if (TuneCPU.empty())
+TuneCPU = Arch;
+  if (!TuneCPU.empty())
+Builder.defineMacro("__loongarch_tune", TuneCPU);
 
   StringRef ABI = getABI();
   if (ABI == "lp64d" || ABI == "lp64f" || ABI == "lp64s")
@@ -270,3 +282,12 @@ bool LoongArchTargetInfo::handleTargetFeatures(
   }
   return true;
 }
+
+bool LoongArchTargetInfo::isValidTuneCPUName(StringRef Name) const {
+  return llvm::LoongArch::isValidTuneCPUName(Name);
+}
+
+void LoongArchTargetInfo::fillValidTuneCPUList(
+SmallVectorImpl ) const {
+  llvm::LoongArch::fillValidTuneCPUList(Values);
+}

diff  --git a/clang/lib/Basic/Targets/LoongArch.h 
b/clang/lib/Basic/Targets/LoongArch.h
index 52c4ce4253689e..60d545566b30fb 100644
--- a/clang/lib/Basic/Targets/LoongArch.h
+++ b/clang/lib/Basic/Targets/LoongArch.h
@@ -80,6 +80,9 @@ class LLVM_LIBRARY_VISIBILITY LoongArchTargetInfo : public 
TargetInfo {
  const std::vector ) const override;
 
   bool hasFeature(StringRef Feature) const override;
+
+  bool isValidTuneCPUName(StringRef Name) const override;
+  void fillValidTuneCPUList(SmallVectorImpl ) const override;
 };
 
 class LLVM_LIBRARY_VISIBILITY LoongArch32TargetInfo

diff  --git a/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp 
b/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
index 856ad58f3bd9db..6cbb06b9a91f5e 100644

[PATCH] D153114: [clangd] [C++20] [Modules] Support C++20 modules for clangd

2023-07-25 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

@sammccall gentle ping~


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

https://reviews.llvm.org/D153114

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


[PATCH] D146368: [clang-tidy] Add readability-reference-to-constructed-temporary check

2023-07-25 Thread Shivam Gupta via Phabricator via cfe-commits
xgupta added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability/reference-to-constructed-temporary.rst:18
+
+   const std::string& value("hello");
+

PiotrZSL wrote:
> xgupta wrote:
> > The below comment is not matching,  do you want to write - 
> > `const std::string& str = std::string("hello");`
> > ?
> actually comment is +- fine, constructor to std::string will be called 
> anyway, and for compiler I think those 2 are equal.
> Will verify.
but you have written below `reference variable ``str`` is assigned a temporary 
object` and there is no str variable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146368

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


[PATCH] D153914: [clang-cl] Enable concatenation of predefined identifiers

2023-07-25 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann accepted this revision.
tahonermann added a comment.
This revision is now accepted and ready to land.

I'm happy with this. I noted one last rename suggestion to maintain 
consistency, but am accepting. Please give Corentin a final chance to raise any 
concerns. Thank you for being so responsive through all the review iterations!




Comment at: clang/include/clang/Basic/DiagnosticGroups.td:1210
 def MicrosoftInitFromPredefined : DiagGroup<"microsoft-init-from-predefined">;
+def MicrosoftStringLiteralFromPredefined : 
DiagGroup<"microsoft-concat-predefined">;
 

We should probably name the diag group to match.
  - microsoft-concat-predefined -> microsoft-string-literal-from-predefined


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153914

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


[PATCH] D156247: [Clang] Add a warning on uses of coroutine keywords

2023-07-25 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

> however, if there are important unresolved issues, why did we set 
> __cpp_impl_coroutine ?

The discussion is here: 
https://discourse.llvm.org/t/rfc-could-we-mark-coroutines-as-unreleased-now/69220.
 My short summary may be:
(1) It is not necessary to claim a feature is completed only after there is no 
related open issues. For example, GCC claims coroutines (and many other 
features) as completed in the early stage and there are still many following 
bug reports then. 
(2) Coroutines are used widely and deeply around the C++ world. People from 
Meta (Meta should be, at least, one of the most heavy user of coroutines in the 
past years) said they would love to approve to the idea even if it is not bug 
free.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156247

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


[PATCH] D156201: [ASTImporter] Fix corrupted RecordLayout introduced by circular referenced fields

2023-07-25 Thread Ding Fei via Phabricator via cfe-commits
danix800 updated this revision to Diff 544168.
danix800 added a comment.

Remove case #1 (fixed by https://reviews.llvm.org/D155574 from @balazske which 
is better).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156201

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
@@ -10,6 +10,7 @@
 //
 
//===--===//
 
+#include "clang/AST/RecordLayout.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/Support/SmallVectorMemoryBuffer.h"
@@ -8028,6 +8029,45 @@
   Import(FromF, Lang_CXX11);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportCirularRefFieldsWithoutCorruptedRecordLayoutCacheTest) {
+  // Import sequence: A => A.b => B => B.f() => ... => UnaryOperator(&) => ...
+  //
+  // UnaryOperator(&) should not introduce invalid RecordLayout since 'A' is
+  // still not completely imported.
+  auto Code =
+  R"(
+  class B;
+  class A {
+B* b;
+int c;
+  };
+  class B {
+A *f() { return &((B *)0)->a; }
+A a;
+  };
+  )";
+
+  auto *FromR = FirstDeclMatcher().match(
+  getTuDecl(Code, Lang_CXX11), cxxRecordDecl(hasName("A")));
+  FromR = FromR->getDefinition();
+  auto  = FromR->getASTContext();
+  auto *ToR = Import(FromR, Lang_CXX11);
+  auto  = ToR->getASTContext();
+
+  uint64_t SecondFieldOffset = FromAST.getTypeSize(FromAST.VoidPtrTy);
+
+  EXPECT_TRUE(FromR->isCompleteDefinition());
+  const auto  = FromAST.getASTRecordLayout(FromR);
+  EXPECT_TRUE(FromLayout.getFieldOffset(0) == 0);
+  EXPECT_TRUE(FromLayout.getFieldOffset(1) == SecondFieldOffset);
+
+  EXPECT_TRUE(ToR->isCompleteDefinition());
+  const auto  = ToAST.getASTRecordLayout(ToR);
+  EXPECT_TRUE(ToLayout.getFieldOffset(0) == 0);
+  EXPECT_TRUE(ToLayout.getFieldOffset(1) == SecondFieldOffset);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase,
ImportRecordWithLayoutRequestingExpr) {
   TranslationUnitDecl *FromTU = getTuDecl(
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -7394,10 +7394,15 @@
   if (Err)
 return std::move(Err);
 
-  return UnaryOperator::Create(
-  Importer.getToContext(), ToSubExpr, E->getOpcode(), ToType,
-  E->getValueKind(), E->getObjectKind(), ToOperatorLoc, E->canOverflow(),
-  E->getFPOptionsOverride());
+  auto *UO = UnaryOperator::CreateEmpty(Importer.getToContext(),
+E->hasStoredFPFeatures());
+  UO->setType(ToType);
+  UO->setSubExpr(ToSubExpr);
+  UO->setOpcode(E->getOpcode());
+  UO->setOperatorLoc(ToOperatorLoc);
+  UO->setCanOverflow(E->canOverflow());
+
+  return UO;
 }
 
 ExpectedStmt


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -10,6 +10,7 @@
 //
 //===--===//
 
+#include "clang/AST/RecordLayout.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/Support/SmallVectorMemoryBuffer.h"
@@ -8028,6 +8029,45 @@
   Import(FromF, Lang_CXX11);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportCirularRefFieldsWithoutCorruptedRecordLayoutCacheTest) {
+  // Import sequence: A => A.b => B => B.f() => ... => UnaryOperator(&) => ...
+  //
+  // UnaryOperator(&) should not introduce invalid RecordLayout since 'A' is
+  // still not completely imported.
+  auto Code =
+  R"(
+  class B;
+  class A {
+B* b;
+int c;
+  };
+  class B {
+A *f() { return &((B *)0)->a; }
+A a;
+  };
+  )";
+
+  auto *FromR = FirstDeclMatcher().match(
+  getTuDecl(Code, Lang_CXX11), cxxRecordDecl(hasName("A")));
+  FromR = FromR->getDefinition();
+  auto  = FromR->getASTContext();
+  auto *ToR = Import(FromR, Lang_CXX11);
+  auto  = ToR->getASTContext();
+
+  uint64_t SecondFieldOffset = FromAST.getTypeSize(FromAST.VoidPtrTy);
+
+  EXPECT_TRUE(FromR->isCompleteDefinition());
+  const auto  = FromAST.getASTRecordLayout(FromR);
+  EXPECT_TRUE(FromLayout.getFieldOffset(0) == 0);
+  EXPECT_TRUE(FromLayout.getFieldOffset(1) == SecondFieldOffset);
+
+  EXPECT_TRUE(ToR->isCompleteDefinition());
+  const auto  = ToAST.getASTRecordLayout(ToR);
+  EXPECT_TRUE(ToLayout.getFieldOffset(0) == 0);
+  EXPECT_TRUE(ToLayout.getFieldOffset(1) == SecondFieldOffset);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase,

[PATCH] D156214: [LLVM][RISCV] Check more extension dependencies

2023-07-25 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

I have deleted the two TODOs in r02c11c5aed59624046125cf512c12f70d2fa358d


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156214

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


[PATCH] D156214: [LLVM][RISCV] Check more extension dependencies

2023-07-25 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: llvm/lib/Support/RISCVISAInfo.cpp:948
-  // TODO: The 'q' extension requires rv64.
-  // TODO: It is illegal to specify 'e' extensions with 'f' and 'd'.
 

craig.topper wrote:
> asb wrote:
> > imkiva wrote:
> > > wangpc wrote:
> > > > I think the comment is outdated here. `E` can be combined with all 
> > > > other extensions according to spec:
> > > > > Unless otherwise stated, standard extensions compatible with RV32I 
> > > > > and RV64I are also compatible with RV32E and RV64E, respectively.
> > > > And, please see also D70401 for more context.
> > > I downloaded the specification from 
> > > [here](https://github.com/riscv/riscv-isa-manual/releases/download/Ratified-IMAFDQC/riscv-spec-20191213.pdf),
> > >  and in page 34 the footnote says:
> > > 
> > > > RV32E can be combined with all current standard extensions. Defining 
> > > > the F, D, and Q extensions as having a 16-entry floating point register 
> > > > file when combined with RV32E was considered but **decided against**. 
> > > > To support systems with reduced floating-point register state, we 
> > > > intend to define a “Zfinx” extension...
> > > 
> > > It seems in the spec version 20191213, they rejected the combination of 
> > > `E` with standard floating-point extensions, instead, a separate 
> > > extension `Zfinx` is chosen for the original purpose.
> > > I am not sure if there's any newer specification that decides to allow 
> > > this combination.
> > > 
> > > 
> > There's a link to the ratified version on 
> > https://wiki.riscv.org/display/HOME/Recently+Ratified+Extensions - see 
> > https://drive.google.com/file/d/1GjHmphVKvJlOBJydAt36g0Oc8yCOPtKw/view
> > 
> > As @wangpc says, the restriction was removed and so the comment is out of 
> > date.
> > RV32E can be combined with all current standard extensions. Defining the F, 
> > D, and Q extensions as having a 16-entry floating point register file when 
> > combined with RV32E was considered but decided against. To support systems 
> > with reduced floating-point register state, we intend to define a “Zfinx” 
> > extension...
> 
> That really only says that the register file for F and D is still 32 entries 
> with RV32E. It doesn't say they are incompatible. Maybe there was some even 
> older text?
There was older text removed here 
https://github.com/riscv/riscv-isa-manual/commit/4845f5d61f96a827ec4d21d2c5a80b6bf7881e56


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156214

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


[PATCH] D156214: [LLVM][RISCV] Check more extension dependencies

2023-07-25 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: llvm/lib/Support/RISCVISAInfo.cpp:948
-  // TODO: The 'q' extension requires rv64.
-  // TODO: It is illegal to specify 'e' extensions with 'f' and 'd'.
 

asb wrote:
> imkiva wrote:
> > wangpc wrote:
> > > I think the comment is outdated here. `E` can be combined with all other 
> > > extensions according to spec:
> > > > Unless otherwise stated, standard extensions compatible with RV32I and 
> > > > RV64I are also compatible with RV32E and RV64E, respectively.
> > > And, please see also D70401 for more context.
> > I downloaded the specification from 
> > [here](https://github.com/riscv/riscv-isa-manual/releases/download/Ratified-IMAFDQC/riscv-spec-20191213.pdf),
> >  and in page 34 the footnote says:
> > 
> > > RV32E can be combined with all current standard extensions. Defining the 
> > > F, D, and Q extensions as having a 16-entry floating point register file 
> > > when combined with RV32E was considered but **decided against**. To 
> > > support systems with reduced floating-point register state, we intend to 
> > > define a “Zfinx” extension...
> > 
> > It seems in the spec version 20191213, they rejected the combination of `E` 
> > with standard floating-point extensions, instead, a separate extension 
> > `Zfinx` is chosen for the original purpose.
> > I am not sure if there's any newer specification that decides to allow this 
> > combination.
> > 
> > 
> There's a link to the ratified version on 
> https://wiki.riscv.org/display/HOME/Recently+Ratified+Extensions - see 
> https://drive.google.com/file/d/1GjHmphVKvJlOBJydAt36g0Oc8yCOPtKw/view
> 
> As @wangpc says, the restriction was removed and so the comment is out of 
> date.
> RV32E can be combined with all current standard extensions. Defining the F, 
> D, and Q extensions as having a 16-entry floating point register file when 
> combined with RV32E was considered but decided against. To support systems 
> with reduced floating-point register state, we intend to define a “Zfinx” 
> extension...

That really only says that the register file for F and D is still 32 entries 
with RV32E. It doesn't say they are incompatible. Maybe there was some even 
older text?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156214

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


[PATCH] D156214: [LLVM][RISCV] Check more extension dependencies

2023-07-25 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: llvm/lib/Support/RISCVISAInfo.cpp:948
   // Additional dependency checks.
-  // TODO: The 'q' extension requires rv64.
-  // TODO: It is illegal to specify 'e' extensions with 'f' and 'd'.
+  // The 'q' extension requires rv64.
+  if (XLen != 64 && Exts.count("q"))

craig.topper wrote:
> I'm not sure this is true.
The restriction was removed 4 years ago 
https://github.com/riscv/riscv-isa-manual/commit/013ba6dc8a504ee4ad7bee42554fecaef7ba797f


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156214

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


[PATCH] D156239: [X86] Support -march=arrowlake, arrowlake-s, lunarlake

2023-07-25 Thread Freddy, Ye via Phabricator via cfe-commits
FreddyYe updated this revision to Diff 544159.
FreddyYe marked an inline comment as done.
FreddyYe added a comment.

Address comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156239

Files:
  clang/lib/Basic/Targets/X86.cpp
  clang/test/CodeGen/attr-cpuspecific-cpus.c
  clang/test/CodeGen/attr-target-mv.c
  clang/test/CodeGen/target-builtin-noerror.c
  clang/test/Driver/x86-march.c
  clang/test/Misc/target-invalid-cpu-note.c
  clang/test/Preprocessor/predefined-arch-macros.c
  compiler-rt/lib/builtins/cpu_model.c
  llvm/include/llvm/TargetParser/X86TargetParser.def
  llvm/include/llvm/TargetParser/X86TargetParser.h
  llvm/lib/Target/X86/X86.td
  llvm/lib/TargetParser/Host.cpp
  llvm/lib/TargetParser/X86TargetParser.cpp
  llvm/test/CodeGen/X86/cpus-intel.ll

Index: llvm/test/CodeGen/X86/cpus-intel.ll
===
--- llvm/test/CodeGen/X86/cpus-intel.ll
+++ llvm/test/CodeGen/X86/cpus-intel.ll
@@ -32,6 +32,10 @@
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=graniterapids 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=graniterapids-d 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=emeraldrapids 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=arrowlake 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=arrowlake-s 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=arrowlake_s 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=lunarlake 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 
 ; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=nocona 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=core2 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
@@ -90,6 +94,10 @@
 ; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=grandridge 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=graniterapids 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=graniterapids-d 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=arrowlake 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=arrowlake-s 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=arrowlake_s 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=lunarlake 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 
 define void @foo() {
   ret void
Index: llvm/lib/TargetParser/X86TargetParser.cpp
===
--- llvm/lib/TargetParser/X86TargetParser.cpp
+++ llvm/lib/TargetParser/X86TargetParser.cpp
@@ -237,6 +237,8 @@
 FeatureENQCMD | FeatureAVXNECONVERT | FeatureAVXVNNIINT8;
 constexpr FeatureBitset FeaturesGrandridge =
 FeaturesSierraforest | FeatureRAOINT;
+constexpr FeatureBitset FeaturesArrowlakeS = FeaturesSierraforest |
+FeatureAVXVNNIINT16 | FeatureSHA512 | FeatureSM3 | FeatureSM4;
 
 // Geode Processor.
 constexpr FeatureBitset FeaturesGeode =
@@ -422,6 +424,12 @@
   { {"raptorlake"}, CK_Raptorlake, FEATURE_AVX2, FeaturesAlderlake, 'p', false },
   // Meteorlake microarchitecture based processors.
   { {"meteorlake"}, CK_Meteorlake, FEATURE_AVX2, FeaturesAlderlake, 'p', false },
+  // Arrowlake microarchitecture based processors.
+  { {"arrowlake"}, CK_Arrowlake, FEATURE_AVX2, FeaturesSierraforest, 'p', false },
+  { {"arrowlake-s"}, CK_ArrowlakeS, FEATURE_AVX2, FeaturesArrowlakeS, '\0', false },
+  { {"arrowlake_s"}, CK_Lunarlake, FEATURE_AVX2, FeaturesArrowlakeS, 'p', true },
+  // Lunarlake microarchitecture based processors.
+  { {"lunarlake"}, CK_Lunarlake, FEATURE_AVX2, FeaturesArrowlakeS, 'p', false },
   // Sierraforest microarchitecture based processors.
   { {"sierraforest"}, CK_Sierraforest, FEATURE_AVX2, FeaturesSierraforest, 'p', false },
   // Grandridge microarchitecture based processors.
Index: llvm/lib/TargetParser/Host.cpp
===
--- 

[PATCH] D156234: [clang][deps] provide support for cc1 command line scanning

2023-07-25 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

This looks pretty good!

I'm not sure unit testing is the best choice here, since we're not checking for 
low-level properties or hard-to-observe behavior. In general LIT tests are 
easier to write/maintain/understand and don't require recompiling, so I'd 
suggest to transform the existing unit test into something similar to tests in 
`clang/test/ClangScanDeps/`.




Comment at: 
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp:414
+  std::vector Args = Action.takeLastCC1Arguments();
+  Consumer.handleBuildCommand({Executable, std::move(Args)});
+  return true;





Comment at: 
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp:507
+  // dependency scanning filesystem.
+  return createAndRunToolInvocation(Argv, Action, *FileMgr,
+PCHContainerOps, *Diags, Consumer);




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

https://reviews.llvm.org/D156234

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


[PATCH] D156214: [LLVM][RISCV] Check more extension dependencies

2023-07-25 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: llvm/lib/Support/RISCVISAInfo.cpp:948
   // Additional dependency checks.
-  // TODO: The 'q' extension requires rv64.
-  // TODO: It is illegal to specify 'e' extensions with 'f' and 'd'.
+  // The 'q' extension requires rv64.
+  if (XLen != 64 && Exts.count("q"))

I'm not sure this is true.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156214

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


[PATCH] D155524: [-Wunsafe-buffer-usage] Ignore the FixableGadgets that will not be fixed at an earlier stage

2023-07-25 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 added inline comments.



Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:1095-1102
   // Gadgets "claim" variables they're responsible for. Once this loop 
finishes,
   // the tracker will only track DREs that weren't claimed by any gadgets,
   // i.e. not understood by the analysis.
   for (const auto  : CB.FixableGadgets) {
 for (const auto *DRE : G->getClaimedVarUseSites()) {
   CB.Tracker.claimUse(DRE);
 }

NoQ wrote:
> ziqingluo-90 wrote:
> > NoQ wrote:
> > > Let's also skip this part when there are no warning gadgets? Your initial 
> > > patch was clearing the `FixableGadgets` list so it was naturally skipped, 
> > > but now it's active again.
> > Oh, I intentionally chose not to skip it:
> >  - 1. To keep the `Tracker` consistent with `CB.FixableGadgets` in case in 
> > the future we want to use these two objects even if there is no 
> > `WarningGadget`; 
> >  - 2. The `findGadgets` function can stay as straightforward as its name 
> > suggests.  It doesn't have to know the specific optimization for empty 
> > `WarningGadget`s.
> > 
> > But the two thoughts above probably aren't important enough.  I will change 
> > it back to skipping the loop when there is no warnings.
> > 
> > 
> Hmm, I agree that this turns into a confusing contract. Maybe move this loop 
> out of the function, to the call site, so that it was more obvious that we 
> skip it? This would leave the tracker in a mildly inconsistent state at 
> return, so the caller will have to make it consistent by doing the claiming, 
> but that's arguably less confusing because we clearly communicate that this 
> is an optional step. So the function will do exactly what it says it'll do: 
> find gadgets and that's it.
> 
> Separately, we can probably consider not searching for fixable gadgets at all 
> when no warning gadgets are found. This could be a performance improvement, 
> but definitely a story for another time.
Thanks for the suggestion.  I moved the loop to the end of the call to 
`findGadgets` and landed it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155524

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


[PATCH] D155524: [-Wunsafe-buffer-usage] Ignore the FixableGadgets that will not be fixed at an earlier stage

2023-07-25 Thread Ziqing Luo via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
ziqingluo-90 marked an inline comment as done.
Closed by commit rGcfcf76c6ad72: [-Wunsafe-buffer-usage] Ignore the 
FixableGadgets that will not be fixed at an… (authored by ziqingluo-90).

Changed prior to commit:
  https://reviews.llvm.org/D155524?vs=542199=544151#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155524

Files:
  clang/lib/Analysis/UnsafeBufferUsage.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-pragma-fixit.cpp

Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-pragma-fixit.cpp
===
--- clang/test/SemaCXX/warn-unsafe-buffer-usage-pragma-fixit.cpp
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-pragma-fixit.cpp
@@ -107,3 +107,128 @@
 
   p[5]; // not to note since the associated warning is suppressed
 }
+
+
+// Test suppressing interacts with variable grouping:
+
+// The implication edges are: `a` -> `b` -> `c`.
+// If the unsafe operation on `a` is supressed, none of the variables
+// will be fixed.
+void suppressedVarInGroup() {
+  int * a;
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
+  int * b;
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
+  int * c;
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
+
+#pragma clang unsafe_buffer_usage begin
+  a[5] = 5;
+#pragma clang unsafe_buffer_usage end
+  a = b;
+  b = c;
+}
+
+// To show that if `a[5]` is not suppressed in the
+// `suppressedVarInGroup` function above, all variables will be fixed.
+void suppressedVarInGroup_control() {
+  int * a;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:10}:"std::span a"
+  int * b;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:10}:"std::span b"
+  int * c;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:10}:"std::span c"
+
+  a[5] = 5;
+  a = b;
+  b = c;
+}
+
+// The implication edges are: `a` -> `b` -> `c`.
+// The unsafe operation on `b` is supressed, while the unsafe
+// operation on `a` is not suppressed. Variable `b` will still be
+// fixed when fixing `a`.
+void suppressedVarInGroup2() {
+  int * a;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:10}:"std::span a"
+  int * b;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:10}:"std::span b"
+  int * c;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:10}:"std::span c"
+
+  a[5] = 5;
+#pragma clang unsafe_buffer_usage begin
+  b[5] = 5;
+#pragma clang unsafe_buffer_usage end
+  a = b;
+  b = c;
+}
+
+// The implication edges are: `a` -> `b` -> `c`.
+// The unsafe operation on `b` is supressed, while the unsafe
+// operation on `c` is not suppressed. Only variable `c` will be fixed
+// then.
+void suppressedVarInGroup3() {
+  int * a;
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
+  int * b;
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
+  int * c;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:10}:"std::span c"
+
+  c[5] = 5;
+#pragma clang unsafe_buffer_usage begin
+  b[5] = 5;
+#pragma clang unsafe_buffer_usage end
+  a = b;
+  b = c;
+}
+
+// The implication edges are: `a` -> `b` -> `c` -> `a`.
+// The unsafe operation on `b` is supressed, while the unsafe
+// operation on `c` is not suppressed. Since the implication graph
+// forms a cycle, all variables will be fixed.
+void suppressedVarInGroup4() {
+  int * a;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:10}:"std::span a"
+  int * b;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:10}:"std::span b"
+  int * c;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:10}:"std::span c"
+
+  c[5] = 5;
+#pragma clang unsafe_buffer_usage begin
+  b[5] = 5;
+#pragma clang unsafe_buffer_usage end
+  a = b;
+  b = c;
+  c = a;
+}
+
+// There are two groups: `a` -> `b` -> `c` and `d` -> `e` -> `f`.
+// Suppressing unsafe operations on variables in one group does not
+// affect other groups.
+void suppressedVarInGroup5() {
+  int * a;
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
+  int * b;
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
+  int * c;
+  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:
+  int * d;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:10}:"std::span d"
+  int * e;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:10}:"std::span e"
+  int * f;
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:10}:"std::span f"
+
+#pragma clang unsafe_buffer_usage begin
+  a[5] = 5;
+#pragma clang unsafe_buffer_usage end
+  a = b;
+  b = c;
+
+  d[5] = 5;
+  d = e;
+  e = f;
+}
Index: clang/lib/Analysis/UnsafeBufferUsage.cpp
===
--- clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -1090,16 +1090,6 @@
   }
 
   M.match(*D->getBody(), D->getASTContext());
-
-  // Gadgets "claim" variables they're responsible for. Once 

[clang] cfcf76c - [-Wunsafe-buffer-usage] Ignore the FixableGadgets that will not be fixed at an earlier stage

2023-07-25 Thread Ziqing Luo via cfe-commits

Author: Ziqing Luo
Date: 2023-07-25T16:58:27-07:00
New Revision: cfcf76c6ad72581917fc65b598e3b64ca28c5ce1

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

LOG: [-Wunsafe-buffer-usage] Ignore the FixableGadgets that will not be fixed 
at an earlier stage

`FixableGadget`s are not always associated with variables that are unsafe
(warned). For example, they could be associated with variables whose
unsafe operations are suppressed or that are not used in any unsafe
operation. Such `FixableGadget`s will not be fixed. Removing these
`FixableGadget` as early as possible helps improve the performance
and stability of the analysis.

Reviewed by: NoQ (Artem Dergachev), t-rasmud (Rashmi Mudduluru)

Differential revision: https://reviews.llvm.org/D155524

Added: 


Modified: 
clang/lib/Analysis/UnsafeBufferUsage.cpp
clang/test/SemaCXX/warn-unsafe-buffer-usage-pragma-fixit.cpp

Removed: 




diff  --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 78f180447eef6f..7b1c5107a7e049 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -1090,16 +1090,6 @@ findGadgets(const Decl *D, const 
UnsafeBufferUsageHandler ,
   }
 
   M.match(*D->getBody(), D->getASTContext());
-
-  // Gadgets "claim" variables they're responsible for. Once this loop 
finishes,
-  // the tracker will only track DREs that weren't claimed by any gadgets,
-  // i.e. not understood by the analysis.
-  for (const auto  : CB.FixableGadgets) {
-for (const auto *DRE : G->getClaimedVarUseSites()) {
-  CB.Tracker.claimUse(DRE);
-}
-  }
-
   return {std::move(CB.FixableGadgets), std::move(CB.WarningGadgets),
   std::move(CB.Tracker)};
 }
@@ -2250,6 +2240,33 @@ void clang::checkUnsafeBufferUsage(const Decl *D,
 return;
   }
 
+  // If no `WarningGadget`s ever matched, there is no unsafe operations in the
+  //  function under the analysis. No need to fix any Fixables.
+  if (!WarningGadgets.empty()) {
+// Gadgets "claim" variables they're responsible for. Once this loop
+// finishes, the tracker will only track DREs that weren't claimed by any
+// gadgets, i.e. not understood by the analysis.
+for (const auto  : FixableGadgets) {
+  for (const auto *DRE : G->getClaimedVarUseSites()) {
+Tracker.claimUse(DRE);
+  }
+}
+  }
+
+  // If no `WarningGadget`s ever matched, there is no unsafe operations in the
+  // function under the analysis.  Thus, it early returns here as there is
+  // nothing needs to be fixed.
+  //
+  // Note this claim is based on the assumption that there is no unsafe
+  // variable whose declaration is invisible from the analyzing function.
+  // Otherwise, we need to consider if the uses of those unsafe varuables needs
+  // fix.
+  // So far, we are not fixing any global variables or class members. And,
+  // lambdas will be analyzed along with the enclosing function. So this early
+  // return is correct for now.
+  if (WarningGadgets.empty())
+return;
+
   UnsafeOps = groupWarningGadgetsByVar(std::move(WarningGadgets));
   FixablesForAllVars = groupFixablesByVar(std::move(FixableGadgets));
 
@@ -2356,6 +2373,34 @@ void clang::checkUnsafeBufferUsage(const Decl *D,
 }
   }
 
+  // Remove a `FixableGadget` if the associated variable is not in the graph
+  // computed above.  We do not want to generate fix-its for such variables,
+  // since they are neither warned nor reachable from a warned one.
+  //
+  // Note a variable is not warned if it is not directly used in any unsafe
+  // operation. A variable `v` is NOT reachable from an unsafe variable, if it
+  // does not exist another variable `u` such that `u` is warned and fixing `u`
+  // (transitively) implicates fixing `v`.
+  //
+  // For example,
+  // ```
+  // void f(int * p) {
+  //   int * a = p; *p = 0;
+  // }
+  // ```
+  // `*p = 0` is a fixable gadget associated with a variable `p` that is 
neither
+  // warned nor reachable from a warned one.  If we add `a[5] = 0` to the end 
of
+  // the function above, `p` becomes reachable from a warned variable.
+  for (auto I = FixablesForAllVars.byVar.begin();
+   I != FixablesForAllVars.byVar.end();) {
+// Note `VisitedVars` contain all the variables in the graph:
+if (VisitedVars.find((*I).first) == VisitedVars.end()) {
+  // no such var in graph:
+  I = FixablesForAllVars.byVar.erase(I);
+} else
+  ++I;
+  }
+
   Strategy NaiveStrategy = getNaiveStrategy(UnsafeVars);
 
   FixItsForVariableGroup =

diff  --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-pragma-fixit.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-pragma-fixit.cpp
index 9301e2a2f1bd6f..47ef0b79729512 100644
--- 

[PATCH] D156277: [Parser][ObjC] Stop parsing on eof

2023-07-25 Thread Ding Fei via Phabricator via cfe-commits
danix800 created this revision.
danix800 added a project: clang.
Herald added a project: All.
danix800 requested review of this revision.
Herald added a subscriber: cfe-commits.

Fixes https://github.com/llvm/llvm-project/issues/64065


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D156277

Files:
  clang/lib/Parse/ParseObjc.cpp
  clang/test/Parser/gh64065-nocrash.m


Index: clang/test/Parser/gh64065-nocrash.m
===
--- /dev/null
+++ clang/test/Parser/gh64065-nocrash.m
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+// expected-error@+4 {{missing '@end'}}
+// expected-note@+3 {{class started here}}
+// expected-error@+2 {{missing '@end'}}
+// expected-note@+1 {{class started here}}
+@interface Roo@interface
Index: clang/lib/Parse/ParseObjc.cpp
===
--- clang/lib/Parse/ParseObjc.cpp
+++ clang/lib/Parse/ParseObjc.cpp
@@ -745,7 +745,8 @@
   << FixItHint::CreateInsertion(AtLoc, "@end\n");
   Diag(CDecl->getBeginLoc(), diag::note_objc_container_start)
   << (int)Actions.getObjCContainerKind();
-  ConsumeToken();
+  if (!Tok.is(tok::eof))
+ConsumeToken();
   break;
 
 case tok::objc_required:


Index: clang/test/Parser/gh64065-nocrash.m
===
--- /dev/null
+++ clang/test/Parser/gh64065-nocrash.m
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+// expected-error@+4 {{missing '@end'}}
+// expected-note@+3 {{class started here}}
+// expected-error@+2 {{missing '@end'}}
+// expected-note@+1 {{class started here}}
+@interface Roo@interface
Index: clang/lib/Parse/ParseObjc.cpp
===
--- clang/lib/Parse/ParseObjc.cpp
+++ clang/lib/Parse/ParseObjc.cpp
@@ -745,7 +745,8 @@
   << FixItHint::CreateInsertion(AtLoc, "@end\n");
   Diag(CDecl->getBeginLoc(), diag::note_objc_container_start)
   << (int)Actions.getObjCContainerKind();
-  ConsumeToken();
+  if (!Tok.is(tok::eof))
+ConsumeToken();
   break;
 
 case tok::objc_required:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151373: [libclang] Expose arguments of clang::annotate{_type}

2023-07-25 Thread Fridtjof Mund via Phabricator via cfe-commits
fridtjof updated this revision to Diff 544142.
fridtjof added a comment.

I fixed the failing IBOutletCollection.m test - there was code to do special 
handling for the respective attribute type, which my patch accidentally skipped 
previously. I reordered the generic attribute handling to come after the 
special cases in VisitChildren.

I cleaned up my unit test. After trying a bit to fix it for testing 
annotate_type as well, I found out that for some unknown reason it is not 
exposed like usual attributes (maybe because it's a type attribute?).
Therefore, I decided to drop it from the test altogether.


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

https://reviews.llvm.org/D151373

Files:
  clang/docs/ReleaseNotes.rst
  clang/tools/libclang/CIndex.cpp
  clang/tools/libclang/CursorVisitor.h
  clang/unittests/libclang/LibclangTest.cpp

Index: clang/unittests/libclang/LibclangTest.cpp
===
--- clang/unittests/libclang/LibclangTest.cpp
+++ clang/unittests/libclang/LibclangTest.cpp
@@ -1246,6 +1246,50 @@
   EXPECT_EQ(fromCXString(clang_getCursorSpelling(*staticAssertCsr)), "");
 }
 
+TEST_F(LibclangParseTest, ExposesAnnotateArgs) {
+  const char testSource[] = R"cpp(
+[[clang::annotate("category", 42)]]
+void func() {}
+)cpp";
+  std::string fileName = "main.cpp";
+  WriteFile(fileName, testSource);
+
+  const char *Args[] = {"-xc++"};
+  ClangTU = clang_parseTranslationUnit(Index, fileName.c_str(), Args, 1,
+   nullptr, 0, TUFlags);
+
+  int attrCount = 0;
+
+  Traverse(
+  [](CXCursor cursor, CXCursor parent) -> CXChildVisitResult {
+if (cursor.kind == CXCursor_AnnotateAttr) {
+  int childCount = 0;
+  clang_visitChildren(
+  cursor,
+  [](CXCursor child, CXCursor,
+ CXClientData data) -> CXChildVisitResult {
+int *pcount = static_cast(data);
+
+// we only expect one argument here, so bail otherwise
+EXPECT_EQ(*pcount, 0);
+
+auto *result = clang_Cursor_Evaluate(child);
+EXPECT_NE(result, nullptr);
+EXPECT_EQ(clang_EvalResult_getAsInt(result), 42);
+++*pcount;
+
+return CXChildVisit_Recurse;
+  },
+  );
+  attrCount++;
+  return CXChildVisit_Continue;
+}
+return CXChildVisit_Recurse;
+  });
+
+  EXPECT_EQ(attrCount, 1);
+}
+
 class LibclangRewriteTest : public LibclangParseTest {
 public:
   CXRewriter Rew = nullptr;
Index: clang/tools/libclang/CursorVisitor.h
===
--- clang/tools/libclang/CursorVisitor.h
+++ clang/tools/libclang/CursorVisitor.h
@@ -276,7 +276,9 @@
   bool IsInRegionOfInterest(CXCursor C);
   bool RunVisitorWorkList(VisitorWorkList );
   void EnqueueWorkList(VisitorWorkList , const Stmt *S);
+  void EnqueueWorkList(VisitorWorkList , const Attr *A);
   LLVM_ATTRIBUTE_NOINLINE bool Visit(const Stmt *S);
+  LLVM_ATTRIBUTE_NOINLINE bool Visit(const Attr *A);
 
 private:
   std::optional handleDeclForVisitation(const Decl *D);
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -23,6 +23,7 @@
 #include "CursorVisitor.h"
 #include "clang-c/FatalErrorHandler.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/AttrVisitor.h"
 #include "clang/AST/DeclObjCCommon.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
@@ -575,6 +576,13 @@
   A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
   }
 
+  if (clang_isAttribute(Cursor.kind)) {
+if (const Attr *A = getCursorAttr(Cursor))
+  return Visit(A);
+
+return false;
+  }
+
   // If pointing inside a macro definition, check if the token is an identifier
   // that was ever defined as a macro. In such a case, create a "pseudo" macro
   // expansion cursor for that token.
@@ -2089,7 +2097,8 @@
 (SourceLocation::UIntTy)(uintptr_t)data[1]);
   }
 };
-class EnqueueVisitor : public ConstStmtVisitor {
+class EnqueueVisitor : public ConstStmtVisitor,
+   public ConstAttrVisitor {
   friend class OMPClauseEnqueue;
   VisitorWorkList 
   CXCursor Parent;
@@ -2231,6 +2240,10 @@
   void VisitOMPTargetTeamsDistributeSimdDirective(
   const OMPTargetTeamsDistributeSimdDirective *D);
 
+  // Attributes
+  void VisitAnnotateAttr(const AnnotateAttr *A);
+  void VisitAnnotateTypeAttr(const AnnotateTypeAttr *A);
+
 private:
   void AddDeclarationNameInfo(const Stmt *S);
   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
@@ -2242,6 +2255,11 @@
   void AddTypeLoc(TypeSourceInfo *TI);
   void EnqueueChildren(const Stmt *S);
   void EnqueueChildren(const OMPClause *S);
+  template ::value ||
+ 

[PATCH] D156274: [NFC] Avoid potential dereferencing of nullptr.

2023-07-25 Thread Sindhu Chittireddy via Phabricator via cfe-commits
schittir created this revision.
schittir added reviewers: aaron.ballman, tahonermann, erichkeane.
Herald added a project: All.
schittir requested review of this revision.
Herald added subscribers: cfe-commits, wangpc.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D156274

Files:
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/CodeGen/CGObjCMac.cpp
  clang/lib/Sema/SemaCodeComplete.cpp


Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -6601,7 +6601,7 @@
   // The "template" keyword can follow "::" in the grammar, but only
   // put it into the grammar if the nested-name-specifier is dependent.
   // FIXME: results is always empty, this appears to be dead.
-  if (!Results.empty() && NNS->isDependent())
+  if (!Results.empty() && NNS && NNS->isDependent())
 Results.AddResult("template");
 
   // If the scope is a concept-constrained type parameter, infer nested
Index: clang/lib/CodeGen/CGObjCMac.cpp
===
--- clang/lib/CodeGen/CGObjCMac.cpp
+++ clang/lib/CodeGen/CGObjCMac.cpp
@@ -1803,6 +1803,7 @@
 }
 
 // Complex types.
+assert(contBB);
 CGF.EmitBlock(contBB);
 CodeGenFunction::ComplexPairTy callResult = result.getComplexVal();
 
Index: clang/lib/AST/ItaniumMangle.cpp
===
--- clang/lib/AST/ItaniumMangle.cpp
+++ clang/lib/AST/ItaniumMangle.cpp
@@ -1656,6 +1656,7 @@
   // Otherwise, use the complete destructor name. This is relevant if a
   // class with a destructor is declared within a destructor.
   mangleCXXDtorType(Dtor_Complete);
+assert(ND);
 writeAbiTags(ND, AdditionalAbiTags);
 break;
 


Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -6601,7 +6601,7 @@
   // The "template" keyword can follow "::" in the grammar, but only
   // put it into the grammar if the nested-name-specifier is dependent.
   // FIXME: results is always empty, this appears to be dead.
-  if (!Results.empty() && NNS->isDependent())
+  if (!Results.empty() && NNS && NNS->isDependent())
 Results.AddResult("template");
 
   // If the scope is a concept-constrained type parameter, infer nested
Index: clang/lib/CodeGen/CGObjCMac.cpp
===
--- clang/lib/CodeGen/CGObjCMac.cpp
+++ clang/lib/CodeGen/CGObjCMac.cpp
@@ -1803,6 +1803,7 @@
 }
 
 // Complex types.
+assert(contBB);
 CGF.EmitBlock(contBB);
 CodeGenFunction::ComplexPairTy callResult = result.getComplexVal();
 
Index: clang/lib/AST/ItaniumMangle.cpp
===
--- clang/lib/AST/ItaniumMangle.cpp
+++ clang/lib/AST/ItaniumMangle.cpp
@@ -1656,6 +1656,7 @@
   // Otherwise, use the complete destructor name. This is relevant if a
   // class with a destructor is declared within a destructor.
   mangleCXXDtorType(Dtor_Complete);
+assert(ND);
 writeAbiTags(ND, AdditionalAbiTags);
 break;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D155544: [AIX][TLS][clang] Add -maix-small-local-exec-tls clang option.

2023-07-25 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast accepted this revision.
hubert.reinterpretcast added a comment.

LGTM for landing after D156203  and D155600 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155544

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


[PATCH] D76096: [clang] allow const structs/unions/arrays to be constant expressions for C

2023-07-25 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

Basically, I don't want order-of-magnitude compile-time regressions with large 
global variables.  There are basically two components to that:

- That the fast path for emitting globals in C continues be fast.
- That we rarely end up using evaluateValue() on large global arrays/structs in 
C, for reasons other than emitting them.  If we end up calling evaluateValue() 
on most globals anyway, the codegen fast-path is a lot less useful; most of the 
cost of the APValue codepath is generating the APValue, not lowering it.

This is not quite as concrete as I'd like, but I'm not sure how to describe it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76096

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


[PATCH] D154658: Optimize emission of `dynamic_cast` to final classes.

2023-07-25 Thread Matthias Braun via Phabricator via cfe-commits
MatzeB added a comment.

In D154658#4533476 , @MatzeB wrote:

> This change results in some of our builds (distributed Thin-LTO in case that 
> matters) to fail with missing symbols. At a first glance this seems to emit 
> VTables in some files where it didn't do this before and then fails to 
> resolve some members of that vtable. I'm in the process of analyzing this 
> further and making a small reproducer.

I just noticed b6847edfc235829b37dd6d734ef5bbfa0a58b6fc 
 mentioned 
in the task above which isn't part of our builds yet. I see even symbols 
emitted with that change and suspect it may resolves the undefined symbols 
problems then. Will know for sure in a day or two (and if you hear nothing all 
is working well).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154658

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


[PATCH] D155992: [clangd] Use xxh3_64bits for background index file digests

2023-07-25 Thread Fangrui Song via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG16d79d26b3b6: [clangd] Use xxh3_64bits for background index 
file digests (authored by MaskRay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155992

Files:
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/index/Background.cpp
  clang-tools-extra/clangd/index/Serialization.cpp
  clang-tools-extra/clangd/test/index-serialization/Inputs/sample.idx


Index: clang-tools-extra/clangd/index/Serialization.cpp
===
--- clang-tools-extra/clangd/index/Serialization.cpp
+++ clang-tools-extra/clangd/index/Serialization.cpp
@@ -457,7 +457,7 @@
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 18;
+constexpr static uint32_t Version = 19;
 
 llvm::Expected readRIFF(llvm::StringRef Data,
  SymbolOrigin Origin) {
Index: clang-tools-extra/clangd/index/Background.cpp
===
--- clang-tools-extra/clangd/index/Background.cpp
+++ clang-tools-extra/clangd/index/Background.cpp
@@ -155,7 +155,7 @@
 
 BackgroundQueue::Task BackgroundIndex::indexFileTask(std::string Path) {
   std::string Tag = filenameWithoutExtension(Path).str();
-  uint64_t Key = llvm::xxHash64(Path);
+  uint64_t Key = llvm::xxh3_64bits(Path);
   BackgroundQueue::Task T([this, Path(std::move(Path))] {
 std::optional WithProvidedContext;
 if (ContextProvider)
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -559,7 +559,7 @@
 }
 
 FileDigest digest(llvm::StringRef Content) {
-  uint64_t Hash{llvm::xxHash64(Content)};
+  uint64_t Hash{llvm::xxh3_64bits(Content)};
   FileDigest Result;
   for (unsigned I = 0; I < Result.size(); ++I) {
 Result[I] = uint8_t(Hash);


Index: clang-tools-extra/clangd/index/Serialization.cpp
===
--- clang-tools-extra/clangd/index/Serialization.cpp
+++ clang-tools-extra/clangd/index/Serialization.cpp
@@ -457,7 +457,7 @@
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 18;
+constexpr static uint32_t Version = 19;
 
 llvm::Expected readRIFF(llvm::StringRef Data,
  SymbolOrigin Origin) {
Index: clang-tools-extra/clangd/index/Background.cpp
===
--- clang-tools-extra/clangd/index/Background.cpp
+++ clang-tools-extra/clangd/index/Background.cpp
@@ -155,7 +155,7 @@
 
 BackgroundQueue::Task BackgroundIndex::indexFileTask(std::string Path) {
   std::string Tag = filenameWithoutExtension(Path).str();
-  uint64_t Key = llvm::xxHash64(Path);
+  uint64_t Key = llvm::xxh3_64bits(Path);
   BackgroundQueue::Task T([this, Path(std::move(Path))] {
 std::optional WithProvidedContext;
 if (ContextProvider)
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -559,7 +559,7 @@
 }
 
 FileDigest digest(llvm::StringRef Content) {
-  uint64_t Hash{llvm::xxHash64(Content)};
+  uint64_t Hash{llvm::xxh3_64bits(Content)};
   FileDigest Result;
   for (unsigned I = 0; I < Result.size(); ++I) {
 Result[I] = uint8_t(Hash);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 16d79d2 - [clangd] Use xxh3_64bits for background index file digests

2023-07-25 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2023-07-25T16:02:54-07:00
New Revision: 16d79d26b3b6b7ab4b024f478f05569e0a033c76

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

LOG: [clangd] Use xxh3_64bits for background index file digests

Many sources show that xxh3 is much better than xxh64. This particular
instance may or may not have noticeable difference, but this change
moves us toward removing xxHash64.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/SourceCode.cpp
clang-tools-extra/clangd/index/Background.cpp
clang-tools-extra/clangd/index/Serialization.cpp
clang-tools-extra/clangd/test/index-serialization/Inputs/sample.idx

Removed: 




diff  --git a/clang-tools-extra/clangd/SourceCode.cpp 
b/clang-tools-extra/clangd/SourceCode.cpp
index eb0a578b0f4a12..31323c08cf1ddf 100644
--- a/clang-tools-extra/clangd/SourceCode.cpp
+++ b/clang-tools-extra/clangd/SourceCode.cpp
@@ -559,7 +559,7 @@ TextEdit toTextEdit(const FixItHint , const 
SourceManager ,
 }
 
 FileDigest digest(llvm::StringRef Content) {
-  uint64_t Hash{llvm::xxHash64(Content)};
+  uint64_t Hash{llvm::xxh3_64bits(Content)};
   FileDigest Result;
   for (unsigned I = 0; I < Result.size(); ++I) {
 Result[I] = uint8_t(Hash);

diff  --git a/clang-tools-extra/clangd/index/Background.cpp 
b/clang-tools-extra/clangd/index/Background.cpp
index c35de750435cc4..cbeb74d145401c 100644
--- a/clang-tools-extra/clangd/index/Background.cpp
+++ b/clang-tools-extra/clangd/index/Background.cpp
@@ -155,7 +155,7 @@ static llvm::StringRef 
filenameWithoutExtension(llvm::StringRef Path) {
 
 BackgroundQueue::Task BackgroundIndex::indexFileTask(std::string Path) {
   std::string Tag = filenameWithoutExtension(Path).str();
-  uint64_t Key = llvm::xxHash64(Path);
+  uint64_t Key = llvm::xxh3_64bits(Path);
   BackgroundQueue::Task T([this, Path(std::move(Path))] {
 std::optional WithProvidedContext;
 if (ContextProvider)

diff  --git a/clang-tools-extra/clangd/index/Serialization.cpp 
b/clang-tools-extra/clangd/index/Serialization.cpp
index aaa1d517370fb9..b905f580c281c9 100644
--- a/clang-tools-extra/clangd/index/Serialization.cpp
+++ b/clang-tools-extra/clangd/index/Serialization.cpp
@@ -457,7 +457,7 @@ readCompileCommand(Reader CmdReader, 
llvm::ArrayRef Strings) {
 // The current versioning scheme is simple - non-current versions are rejected.
 // If you make a breaking change, bump this version number to invalidate stored
 // data. Later we may want to support some backward compatibility.
-constexpr static uint32_t Version = 18;
+constexpr static uint32_t Version = 19;
 
 llvm::Expected readRIFF(llvm::StringRef Data,
  SymbolOrigin Origin) {

diff  --git 
a/clang-tools-extra/clangd/test/index-serialization/Inputs/sample.idx 
b/clang-tools-extra/clangd/test/index-serialization/Inputs/sample.idx
index b59849472d57bf..0c04df86ae1c6c 100644
Binary files 
a/clang-tools-extra/clangd/test/index-serialization/Inputs/sample.idx and 
b/clang-tools-extra/clangd/test/index-serialization/Inputs/sample.idx 
diff er



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


[PATCH] D154658: Optimize emission of `dynamic_cast` to final classes.

2023-07-25 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

In D154658#4533476 , @MatzeB wrote:

> This change results in some of our builds (distributed Thin-LTO in case that 
> matters) to fail with missing symbols. At a first glance this seems to emit 
> VTables in some files where it didn't do this before and then fails to 
> resolve some members of that vtable. I'm in the process of analyzing this 
> further and making a small reproducer.

Please try again after rGb6847edfc235829b37dd6d734ef5bbfa0a58b6fc 
 and see 
if you're still having issues.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154658

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


[clang] 61c7a91 - Commit to a primary definition for a class when we load its first

2023-07-25 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2023-07-25T15:59:21-07:00
New Revision: 61c7a9140becb19c5b1bc644e54452c6f782f5d5

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

LOG: Commit to a primary definition for a class when we load its first
member.

Previously, we wouldn't do this if the first member loaded is within a
definition that's added to a class via an update record, which happens
when template instantiation adds a class definition to a declaration
that was imported from an AST file.

This would lead to classes having member functions whose getParent
returned a class declaration that wasn't the primary definition, which
in turn caused the vtable builder to build broken vtables.

I don't yet have a reduced testcase for the wrong-code bug here, because
the setup required to get us into the broken state is very subtle, but
have confirmed that this fixes it.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Serialization/ASTReaderDecl.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d8655e52aa3235..6a762a6e92eb5a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -98,6 +98,10 @@ Improvements to Clang's diagnostics
 
 Bug Fixes in This Version
 -
+- Fixed an issue where a class template specialization whose declaration is
+  instantiated in one module and whose definition is instantiated in another
+  module may end up with members associated with the wrong declaration of the
+  class, which can result in miscompiles in some cases.
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/lib/Serialization/ASTReaderDecl.cpp 
b/clang/lib/Serialization/ASTReaderDecl.cpp
index 10c92f8d214941..c8cbee14be4f02 100644
--- a/clang/lib/Serialization/ASTReaderDecl.cpp
+++ b/clang/lib/Serialization/ASTReaderDecl.cpp
@@ -181,6 +181,13 @@ namespace clang {
 static void setAnonymousDeclForMerging(ASTReader , DeclContext *DC,
unsigned Index, NamedDecl *D);
 
+/// Commit to a primary definition of the class RD, which is known to be
+/// a definition of the class. We might not have read the definition data
+/// for it yet. If we haven't then allocate placeholder definition data
+/// now too.
+static CXXRecordDecl *getOrFakePrimaryClassDefinition(ASTReader ,
+  CXXRecordDecl *RD);
+
 /// Results from loading a RedeclarableDecl.
 class RedeclarableResult {
   Decl *MergeWith;
@@ -598,7 +605,13 @@ void ASTDeclReader::VisitDecl(Decl *D) {
 auto *LexicalDC = readDeclAs();
 if (!LexicalDC)
   LexicalDC = SemaDC;
-DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
+// If the context is a class, we might not have actually merged it yet, in
+// the case where the definition comes from an update record.
+DeclContext *MergedSemaDC;
+if (auto *RD = dyn_cast(SemaDC))
+  MergedSemaDC = getOrFakePrimaryClassDefinition(Reader, RD);
+else
+  MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
 // Avoid calling setLexicalDeclContext() directly because it uses
 // Decl::getASTContext() internally which is unsafe during derialization.
 D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
@@ -3198,6 +3211,32 @@ uint64_t ASTReader::getGlobalBitOffset(ModuleFile , 
uint64_t LocalOffset) {
   return LocalOffset + M.GlobalBitOffset;
 }
 
+CXXRecordDecl *
+ASTDeclReader::getOrFakePrimaryClassDefinition(ASTReader ,
+   CXXRecordDecl *RD) {
+  // Try to dig out the definition.
+  auto *DD = RD->DefinitionData;
+  if (!DD)
+DD = RD->getCanonicalDecl()->DefinitionData;
+
+  // If there's no definition yet, then DC's definition is added by an update
+  // record, but we've not yet loaded that update record. In this case, we
+  // commit to DC being the canonical definition now, and will fix this when
+  // we load the update record.
+  if (!DD) {
+DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
+RD->setCompleteDefinition(true);
+RD->DefinitionData = DD;
+RD->getCanonicalDecl()->DefinitionData = DD;
+
+// Track that we did this horrible thing so that we can fix it later.
+Reader.PendingFakeDefinitionData.insert(
+std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
+  }
+
+  return DD->Definition;
+}
+
 /// Find the context in which we should search for previous declarations when
 /// looking for declarations to merge.
 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader ,
@@ -3205,29 +3244,8 @@ DeclContext 

[PATCH] D154658: Optimize emission of `dynamic_cast` to final classes.

2023-07-25 Thread Matthias Braun via Phabricator via cfe-commits
MatzeB added a comment.

This change results in some of our builds (distributed Thin-LTO in case that 
matters) to fail with missing symbols. At a first glance this seems to emit 
VTables in some files where it didn't do this before and then fails to resolve 
some members of that vtable. I'm in the process of analyzing this further and 
making a small reproducer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154658

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


[PATCH] D156234: [clang][deps] provide support for cc1 command line scanning

2023-07-25 Thread Connor Sughrue via Phabricator via cfe-commits
cpsughrue updated this revision to Diff 544127.
cpsughrue edited the summary of this revision.
cpsughrue added a comment.

Fixed formatting issues


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

https://reviews.llvm.org/D156234

Files:
  clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
  clang/unittests/Tooling/DependencyScannerTest.cpp

Index: clang/unittests/Tooling/DependencyScannerTest.cpp
===
--- clang/unittests/Tooling/DependencyScannerTest.cpp
+++ clang/unittests/Tooling/DependencyScannerTest.cpp
@@ -240,6 +240,36 @@
 "test.cpp.o: /root/test.cpp /root/header.h\n");
 }
 
+TEST(DependencyScanner, ScanDepsWithCC1) {
+  std::vector CommandLine = {
+  "clang","-cc1", "-triple",   "x86_64-apple-macosx10.7", "-x", "c++",
+  "test.cpp", "-o",   "test.cpp.o"};
+  StringRef CWD = "/root";
+
+  auto VFS = new llvm::vfs::InMemoryFileSystem();
+  VFS->setCurrentWorkingDirectory(CWD);
+  auto Sept = llvm::sys::path::get_separator();
+  std::string HeaderPath =
+  std::string(llvm::formatv("{0}root{0}header.h", Sept));
+  std::string TestPath = std::string(llvm::formatv("{0}root{0}test.cpp", Sept));
+
+  VFS->addFile(HeaderPath, 0, llvm::MemoryBuffer::getMemBuffer("\n"));
+  VFS->addFile(TestPath, 0,
+   llvm::MemoryBuffer::getMemBuffer("#include \"header.h\"\n"));
+
+  DependencyScanningService Service(ScanningMode::DependencyDirectivesScan,
+ScanningOutputFormat::Make);
+  DependencyScanningTool ScanTool(Service, VFS);
+
+  std::string DepFile;
+  ASSERT_THAT_ERROR(
+  ScanTool.getDependencyFile(CommandLine, CWD).moveInto(DepFile),
+  llvm::Succeeded());
+  using llvm::sys::path::convert_to_slash;
+  EXPECT_EQ(convert_to_slash(DepFile),
+"test.cpp.o: /root/test.cpp /root/header.h\n");
+}
+
 TEST(DependencyScanner, ScanDepsWithModuleLookup) {
   std::vector CommandLine = {
   "clang",
Index: clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -385,6 +385,9 @@
   if (!Compilation)
 return false;
 
+  if (Compilation->containsError())
+return false;
+
   for (const driver::Command  : Compilation->getJobs()) {
 if (!Callback(Job))
   return false;
@@ -392,6 +395,26 @@
   return true;
 }
 
+static bool createAndRunToolInvocation(
+std::vector CommandLine, DependencyScanningAction ,
+FileManager ,
+std::shared_ptr ,
+DiagnosticsEngine , DependencyConsumer ) {
+
+  // Save executable path before providing CommandLine to ToolInvocation
+  std::string Executable = CommandLine[0];
+  ToolInvocation Invocation(std::move(CommandLine), , ,
+PCHContainerOps);
+  Invocation.setDiagnosticConsumer(Diags.getClient());
+  Invocation.setDiagnosticOptions(());
+  if (!Invocation.run())
+return false;
+
+  std::vector Args = Action.takeLastCC1Arguments();
+  Consumer.handleBuildCommand({Executable, std::move(Args)});
+  return true;
+}
+
 bool DependencyScanningWorker::computeDependencies(
 StringRef WorkingDirectory, const std::vector ,
 DependencyConsumer , DependencyActionController ,
@@ -454,37 +477,37 @@
   DependencyScanningAction Action(WorkingDirectory, Consumer, Controller, DepFS,
   Format, OptimizeArgs, EagerLoadModules,
   DisableFree, ModuleName);
-  bool Success = forEachDriverJob(
-  FinalCommandLine, *Diags, *FileMgr, [&](const driver::Command ) {
-if (StringRef(Cmd.getCreator().getName()) != "clang") {
-  // Non-clang command. Just pass through to the dependency
-  // consumer.
-  Consumer.handleBuildCommand(
-  {Cmd.getExecutable(),
-   {Cmd.getArguments().begin(), Cmd.getArguments().end()}});
-  return true;
-}
-
-std::vector Argv;
-Argv.push_back(Cmd.getExecutable());
-Argv.insert(Argv.end(), Cmd.getArguments().begin(),
-Cmd.getArguments().end());
-
-// Create an invocation that uses the underlying file
-// system to ensure that any file system requests that
-// are made by the driver do not go through the
-// dependency scanning filesystem.
-ToolInvocation Invocation(std::move(Argv), , &*FileMgr,
-  PCHContainerOps);
-Invocation.setDiagnosticConsumer(Diags->getClient());
-Invocation.setDiagnosticOptions(>getDiagnosticOptions());
-if (!Invocation.run())
-  return false;
-
-std::vector Args = Action.takeLastCC1Arguments();
-Consumer.handleBuildCommand({Cmd.getExecutable(), std::move(Args)});
-return true;
-  });
+

[PATCH] D152793: [RISCV] Add MC layer support for Zicfiss.

2023-07-25 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/test/Preprocessor/riscv-target-features.c:75
 // CHECK-NOT: __riscv_zvfbfwma {{.*$}}
+// CHECK-NOT: __riscv_zicfisslp {{.*$}}
 

This needs to be renamed to remove lp



Comment at: clang/test/Preprocessor/riscv-target-features.c:725
+// RUN: %clang -target riscv32 -menable-experimental-extensions \
+// RUN: -march=rv32izicfisslp0p1 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZICFISSLP-EXT %s

This needs to be renamed to remove lp



Comment at: llvm/lib/Target/RISCV/RISCVFeatures.td:84
+: SubtargetFeature<"experimental-zicfiss", "HasStdExtZicfiss", "true",
+   "'zicfiss' (Shadow stack)">;
+def HasStdExtZicfiss : Predicate<"Subtarget->hasStdExtZicfiss()">,

Zicfiss



Comment at: llvm/lib/Target/RISCV/RISCVInstrInfo.td:1921
 include "RISCVInstrInfoZicond.td"
+include "RISCVInstrInfoZicfiss.td"
 

This needs to be rebased, the files here were moved into groups.



Comment at: llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td:1
+//===-- RISCVInstrInfoZ.td - RISC-V CFG -*- tablegen -*-===//
+//

Filename doesn't match



Comment at: llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td:35
+class RV_SSPop rd, bits<5> rs1, string opcodestr, string argstr> :
+  RVInst<(outs GPR:$rd), (ins GPR:$rs1), opcodestr, argstr, [], InstFormatI> {
+  let Inst{31-20} = 0b10011100;

Can we use RVInstI by adding `let imm12 = 0b10011100` to the body?



Comment at: llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td:66
+let Uses = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 0 in {
+def SSPINC : RVInst<(outs), (ins uimm5nonzero:$imm), "sspinc", "$imm", [], 
InstFormatI> {
+  bits<5> imm;

Can this use RVInstI with lets for imm12, rs1, and rd?



Comment at: llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td:75
+
+def SSPRR : RVInst<(outs GPRNoX0:$rd), (ins), "ssprr", "$rd", [], InstFormatR> 
{
+  bits<5> rd;

Can this use RVInstR?



Comment at: llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td:87
+let Uses = [SSP], Defs = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 1 
in {
+def SSPUSH : RVInst<(outs), (ins GPRRA:$rs2), "sspush", "$rs2", [], 
InstFormatR> {
+  bits<5> rs2;

Can this use RVInstR?



Comment at: llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td:98
+def SSAMOSWAP :
+  RVInst<(outs GPRNoX0:$dest), (ins GPR:$addr, GPR:$src),
+ "ssamoswap", "$dest, $src, (${addr})", [], InstFormatR> {

RVInstR


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152793

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


[PATCH] D76096: [clang] allow const structs/unions/arrays to be constant expressions for C

2023-07-25 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers updated this revision to Diff 544128.
nickdesaulniers added a comment.

- rebase for presubmit builders


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76096

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/AST/ExprConstant.cpp
  clang/test/CodeGen/builtin-constant-p.c
  clang/test/CodeGen/const-init.c
  clang/test/Sema/builtins.c
  clang/test/Sema/init.c

Index: clang/test/Sema/init.c
===
--- clang/test/Sema/init.c
+++ clang/test/Sema/init.c
@@ -164,3 +164,46 @@
 
 typedef struct { uintptr_t x : 2; } StructWithBitfield;
 StructWithBitfield bitfieldvar = { (uintptr_t) }; // expected-error {{initializer element is not a compile-time constant}}
+
+// PR45157
+struct PR4517_foo {
+  int x;
+};
+struct PR4517_bar {
+  struct PR4517_foo foo;
+};
+const struct PR4517_foo my_foo = {.x = 42};
+struct PR4517_bar my_bar = {
+.foo = my_foo, // no-warning
+};
+struct PR4517_bar my_bar2 = (struct PR4517_bar){
+.foo = my_foo, // no-warning
+};
+struct PR4517_bar my_bar3 = {
+my_foo, // no-warning
+};
+struct PR4517_bar my_bar4 = (struct PR4517_bar){
+my_foo // no-warning
+};
+extern const struct PR4517_foo my_foo2;
+struct PR4517_bar my_bar5 = {
+  .foo = my_foo2, // expected-error {{initializer element is not a compile-time constant}}
+};
+const struct PR4517_foo my_foo3 = {.x = my_foo.x};
+int PR4517_a[2] = {0, 1};
+const int PR4517_ca[2] = {0, 1};
+int PR4517_idx = 0;
+const int PR4517_idxc = 1;
+int PR4517_x1 = PR4517_a[PR4517_idx]; // expected-error {{initializer element is not a compile-time constant}}
+int PR4517_x2 = PR4517_a[PR4517_idxc]; // expected-error {{initializer element is not a compile-time constant}}
+int PR4517_x3 = PR4517_a[0]; // expected-error {{initializer element is not a compile-time constant}}
+int PR4517_y1 = PR4517_ca[PR4517_idx]; // expected-error {{initializer element is not a compile-time constant}}
+int PR4517_y2 = PR4517_ca[PR4517_idxc]; // no-warning
+int PR4517_y3 = PR4517_ca[0]; // no-warning
+union PR4517_u {
+int x;
+float y;
+};
+const union PR4517_u u1 = {4.0f};
+const union PR4517_u u2 = u1; // no-warning
+const union PR4517_u u3 = {u1.y}; // expected-error {{initializer element is not a compile-time constant}}
Index: clang/test/Sema/builtins.c
===
--- clang/test/Sema/builtins.c
+++ clang/test/Sema/builtins.c
@@ -131,7 +131,7 @@
 
 const int test17_n = 0;
 const char test17_c[] = {1, 2, 3, 0};
-const char test17_d[] = {1, 2, 3, 4};
+const char test17_d[] = {1, 2, 3, 4}; // Like test17_c but not NUL-terminated.
 typedef int __attribute__((vector_size(16))) IntVector;
 struct Aggregate { int n; char c; };
 enum Enum { EnumValue1, EnumValue2 };
@@ -178,9 +178,10 @@
   ASSERT(!OPT("abcd"));
   // In these cases, the strlen is non-constant, but the __builtin_constant_p
   // is 0: the array size is not an ICE but is foldable.
-  ASSERT(!OPT(test17_c));// expected-warning {{folding}}
-  ASSERT(!OPT(_c[0]));// expected-warning {{folding}}
-  ASSERT(!OPT((char*)test17_c)); // expected-warning {{folding}}
+  ASSERT(!OPT(test17_c));
+  ASSERT(!OPT(_c[0]));
+  ASSERT(!OPT((char*)test17_c));
+  // NOTE: test17_d is not NUL-termintated, so calling strlen on it is UB.
   ASSERT(!OPT(test17_d));// expected-warning {{folding}}
   ASSERT(!OPT(_d[0]));// expected-warning {{folding}}
   ASSERT(!OPT((char*)test17_d)); // expected-warning {{folding}}
Index: clang/test/CodeGen/const-init.c
===
--- clang/test/CodeGen/const-init.c
+++ clang/test/CodeGen/const-init.c
@@ -190,3 +190,28 @@
 struct { const float *floats; } compoundliteral = {
   (float[1]) { 0.1, },
 };
+
+struct PR4517_foo {
+  int x;
+};
+struct PR4517_bar {
+  struct PR4517_foo foo;
+};
+const struct PR4517_foo my_foo = {.x = 42};
+struct PR4517_bar my_bar = {.foo = my_foo};
+struct PR4517_bar my_bar2 = (struct PR4517_bar){.foo = my_foo};
+struct PR4517_bar my_bar3 = {my_foo};
+struct PR4517_bar my_bar4 = (struct PR4517_bar){my_foo};
+// CHECK: @my_foo = constant %struct.PR4517_foo { i32 42 }, align 4
+// CHECK: @my_bar = global %struct.PR4517_bar { %struct.PR4517_foo { i32 42 } }, align 4
+// CHECK: @my_bar2 = global %struct.PR4517_bar { %struct.PR4517_foo { i32 42 } }, align 4
+// CHECK: @my_bar3 = global %struct.PR4517_bar { %struct.PR4517_foo { i32 42 } }, align 4
+// CHECK: @my_bar4 = global %struct.PR4517_bar { %struct.PR4517_foo { i32 42 } }, align 4
+const int PR4517_arrc[2] = {41, 42};
+int PR4517_x = PR4517_arrc[1];
+const int PR4517_idx = 1;
+int PR4517_x2 = PR4517_arrc[PR4517_idx];
+// CHECK: @PR4517_arrc = constant [2 x i32] [i32 41, i32 42], align 4
+// CHECK: @PR4517_x = global i32 42, align 4
+// CHECK: @PR4517_idx = constant i32 1, align 4
+// CHECK: @PR4517_x2 = global i32 42, align 

[PATCH] D154784: [clang] Fix crash caused by PseudoObjectExprBitfields::NumSubExprs overflow

2023-07-25 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: clang/include/clang/AST/Stmt.h:596-597
 
-// These don't need to be particularly wide, because they're
-// strictly limited by the forms of expressions we permit.
-unsigned NumSubExprs : 8;
-unsigned ResultIndex : 32 - 8 - NumExprBits;
+unsigned NumSubExprs : 16;
+unsigned ResultIndex : 16;
   };

aaron.ballman wrote:
> dblaikie wrote:
> > Could/should we add some error checking in the ctor to assert that we don't 
> > overflow these longer values/just hit the bug later on?
> > 
> > (& could we use `unsigned short` here rather than bitfields?)
> We've already got them packed in with other bit-fields from the expression 
> bits, so I think it's reasonable to continue the pattern of using bit-fields 
> (that way we don't accidentally end up with padding between the unnamed bits 
> at the start and the named bits in this object).
> 
> I think adding some assertions would not be a bad idea as a follow-up.
Maybe some unconditional (rather than only in asserts builds) error handling? 
(report_fatal_error, if this is low priority enough to not have an elegant 
failure mode, but something where we don't just overflow and carry on would be 
good... )


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154784

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


[PATCH] D156175: [clang][ConstExprEmitter] handle NullToPointer ImplicitCastExpr

2023-07-25 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers updated this revision to Diff 544126.
nickdesaulniers added a comment.

- rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156175

Files:
  clang/lib/CodeGen/CGExprConstant.cpp


Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1131,6 +1131,10 @@
   if (const auto *S = dyn_cast(subExpr))
 return CGM.GetAddrOfConstantStringFromLiteral(S).getPointer();
   return nullptr;
+case CK_NullToPointer:
+  if (llvm::Constant *C = Visit(subExpr, destType))
+return CGM.EmitNullConstant(destType);
+  return nullptr;
 
 case CK_IntToOCLSampler:
   llvm_unreachable("global sampler variables are not generated");
@@ -1187,7 +1191,6 @@
 case CK_IntegralComplexToFloatingComplex:
 case CK_PointerToIntegral:
 case CK_PointerToBoolean:
-case CK_NullToPointer:
 case CK_IntegralCast:
 case CK_BooleanToSignedIntegral:
 case CK_IntegralToPointer:


Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1131,6 +1131,10 @@
   if (const auto *S = dyn_cast(subExpr))
 return CGM.GetAddrOfConstantStringFromLiteral(S).getPointer();
   return nullptr;
+case CK_NullToPointer:
+  if (llvm::Constant *C = Visit(subExpr, destType))
+return CGM.EmitNullConstant(destType);
+  return nullptr;
 
 case CK_IntToOCLSampler:
   llvm_unreachable("global sampler variables are not generated");
@@ -1187,7 +1191,6 @@
 case CK_IntegralComplexToFloatingComplex:
 case CK_PointerToIntegral:
 case CK_PointerToBoolean:
-case CK_NullToPointer:
 case CK_IntegralCast:
 case CK_BooleanToSignedIntegral:
 case CK_IntegralToPointer:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D156185: [clang][ConstExprEmitter] handle ArrayToPointerDecay ImplicitCastExpr of StringLiterals

2023-07-25 Thread Nick Desaulniers 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 rGd1199808afa5: [clang][ConstExprEmitter] handle 
ArrayToPointerDecay ImplicitCastExpr of… (authored by nickdesaulniers).

Changed prior to commit:
  https://reviews.llvm.org/D156185?vs=543740=544125#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156185

Files:
  clang/lib/CodeGen/CGExprConstant.cpp


Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1127,6 +1127,11 @@
 case CK_ConstructorConversion:
   return Visit(subExpr, destType);
 
+case CK_ArrayToPointerDecay:
+  if (const auto *S = dyn_cast(subExpr))
+return CGM.GetAddrOfConstantStringFromLiteral(S).getPointer();
+  return nullptr;
+
 case CK_IntToOCLSampler:
   llvm_unreachable("global sampler variables are not generated");
 
@@ -1164,7 +1169,6 @@
 case CK_CPointerToObjCPointerCast:
 case CK_BlockPointerToObjCPointerCast:
 case CK_AnyPointerToBlockPointerCast:
-case CK_ArrayToPointerDecay:
 case CK_FunctionToPointerDecay:
 case CK_BaseToDerived:
 case CK_DerivedToBase:


Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1127,6 +1127,11 @@
 case CK_ConstructorConversion:
   return Visit(subExpr, destType);
 
+case CK_ArrayToPointerDecay:
+  if (const auto *S = dyn_cast(subExpr))
+return CGM.GetAddrOfConstantStringFromLiteral(S).getPointer();
+  return nullptr;
+
 case CK_IntToOCLSampler:
   llvm_unreachable("global sampler variables are not generated");
 
@@ -1164,7 +1169,6 @@
 case CK_CPointerToObjCPointerCast:
 case CK_BlockPointerToObjCPointerCast:
 case CK_AnyPointerToBlockPointerCast:
-case CK_ArrayToPointerDecay:
 case CK_FunctionToPointerDecay:
 case CK_BaseToDerived:
 case CK_DerivedToBase:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] d119980 - [clang][ConstExprEmitter] handle ArrayToPointerDecay ImplicitCastExpr of StringLiterals

2023-07-25 Thread Nick Desaulniers via cfe-commits

Author: Nick Desaulniers
Date: 2023-07-25T15:27:08-07:00
New Revision: d1199808afa5b46dfb6738f123b869d0e2fa050a

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

LOG: [clang][ConstExprEmitter] handle ArrayToPointerDecay ImplicitCastExpr of 
StringLiterals

Consider the following statement:
const char* foo = "foo";

For the sub-AST:
`-ImplicitCastExpr  'const char *' 
  `-ImplicitCastExpr  'char *' 
`-StringLiteral  'char[4]' lvalue "foo"

The address of the StringLiteral can be emitted as the Constant.

Reviewed By: efriedma

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

Added: 


Modified: 
clang/lib/CodeGen/CGExprConstant.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGExprConstant.cpp 
b/clang/lib/CodeGen/CGExprConstant.cpp
index 836561a0fb7325..88dde7c9178829 100644
--- a/clang/lib/CodeGen/CGExprConstant.cpp
+++ b/clang/lib/CodeGen/CGExprConstant.cpp
@@ -1127,6 +1127,11 @@ class ConstExprEmitter :
 case CK_ConstructorConversion:
   return Visit(subExpr, destType);
 
+case CK_ArrayToPointerDecay:
+  if (const auto *S = dyn_cast(subExpr))
+return CGM.GetAddrOfConstantStringFromLiteral(S).getPointer();
+  return nullptr;
+
 case CK_IntToOCLSampler:
   llvm_unreachable("global sampler variables are not generated");
 
@@ -1164,7 +1169,6 @@ class ConstExprEmitter :
 case CK_CPointerToObjCPointerCast:
 case CK_BlockPointerToObjCPointerCast:
 case CK_AnyPointerToBlockPointerCast:
-case CK_ArrayToPointerDecay:
 case CK_FunctionToPointerDecay:
 case CK_BaseToDerived:
 case CK_DerivedToBase:



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


[PATCH] D155769: [Clang][docs][RFC] Add documentation for C++ Parallel Algorithm Offload

2023-07-25 Thread Ronan Keryell via Phabricator via cfe-commits
keryell added a comment.

Interesting.




Comment at: clang/docs/StdParSupport.rst:349
+
+thread t0{[&]() {
+  hipSetDevice(accelerator_0);





Comment at: clang/docs/StdParSupport.rst:354
+}};
+thread t1{[&]() {
+  hitSetDevice(accelerator_1);





Comment at: clang/docs/StdParSupport.rst:360-362
+t0.join();
+t1.join();
+





Comment at: clang/docs/StdParSupport.rst:366-367
+
+   Note that this is a temporary, unsafe workaround for a deficiency in the C++
+   Standard.
+

Another way could be to hide somehow a way to select the device in the policy 
like in https://github.com/KhronosGroup/SyclParallelSTL, which might be 
something included in your point "4." of "Open Questions / Future Developments".
Perhaps better than opening the TLS Pandora box?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155769

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


[PATCH] D76096: [clang] allow const structs/unions/arrays to be constant expressions for C

2023-07-25 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

what's the "exit criteria" for this patch (https://reviews.llvm.org/D76096)? in 
https://reviews.llvm.org/D76096#4523828 and 
https://reviews.llvm.org/D76096#4524003 you mention InitListExpr and 
StringLiteral. In https://reviews.llvm.org/D156185#4533274 I verified that 
StringLiteral is handled by the fast path. I believe that InitListExpr is as 
well.  Is your (@efriedma ) concern more so about large InitListExpr and large 
StringLiteral (more so than outright support)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76096

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


[PATCH] D156189: [-Wunsafe-buffer-usage] Refactor to let local variable fix-its and parameter fix-its share common code

2023-07-25 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 added inline comments.



Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:1824
+
+  if (!IdentText)
+return {};

t-rasmud wrote:
> When will this condition be satisfied? I just want to understand if there are 
> code examples where there is no identifier text or is it that 
> `getVarDeclIdentifierText` fails.
`!IdentText` if `getVarDeclIdentifierText` fails.  

`getVarDeclIdentifierText` assumes that the identifier text is a single token.  
 It starts with the begin location of the identifier and tries to obtain the 
end location via `Lexer::getLocForEndOfToken`.
So it could fail if 1) the identifier text is not a single token or 2) any 
unexpected failure happens in obtaining valid source locations.

Case 2) could be rare I think since I don't know when it could happen.  We just 
need to assume that it is NOT always successful in manipulating source 
locations.

For case 1), I originally thought that if the identifier is expanded from a 
macro with parameters, e.g., 
```
#define MACRO(x)  name
int * MACRO(x);
```
, `MACRO(x)` is not a single token.  But it seems I was wrong---it is one token 
to the `Lexer`.  See my test at 
`warn-unsafe-buffer-usage-fixits-local-var-span.cpp:186--206`.

In conclusion, `getVarDeclIdentifierText` could fail but it should be rare.


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

https://reviews.llvm.org/D156189

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


[PATCH] D153914: [clang-cl] Enable concatenation of predefined identifiers

2023-07-25 Thread Richard Dzenis via Phabricator via cfe-commits
RIscRIpt updated this revision to Diff 544114.
RIscRIpt marked 4 inline comments as done.
RIscRIpt added a comment.

Rename diagnostic messages constants


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153914

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Lex/LiteralSupport.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Lex/LiteralSupport.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/ms_predefined_expr.cpp
  clang/test/Sema/ms_wide_predefined_expr.cpp

Index: clang/test/Sema/ms_wide_predefined_expr.cpp
===
--- clang/test/Sema/ms_wide_predefined_expr.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-// RUN: %clang_cc1 %s -fsyntax-only -Wno-unused-value -Wmicrosoft -verify -fms-extensions
-// expected-no-diagnostics
-
-// Wide character predefined identifiers
-#define _STR2WSTR(str) L##str
-#define STR2WSTR(str) _STR2WSTR(str)
-void abcdefghi12(void) {
- const wchar_t (*ss)[12] = (__FUNCTION__);
- static int arr[sizeof(STR2WSTR(__FUNCTION__))==12*sizeof(wchar_t) ? 1 : -1];
- const wchar_t (*ss2)[31] = (__FUNCSIG__);
- static int arr2[sizeof(STR2WSTR(__FUNCSIG__))==31*sizeof(wchar_t) ? 1 : -1];
-}
-
-namespace PR13206 {
-void foo(const wchar_t *);
-
-template class A {
-public:
- void method() {
-  foo(L__FUNCTION__);
- }
-};
-
-void bar() {
- A x;
- x.method();
-}
-}
Index: clang/test/Sema/ms_predefined_expr.cpp
===
--- clang/test/Sema/ms_predefined_expr.cpp
+++ clang/test/Sema/ms_predefined_expr.cpp
@@ -1,9 +1,170 @@
 // RUN: %clang_cc1 %s -fsyntax-only -Wmicrosoft -verify -fms-extensions
 
-void f() {
+using size_t = __SIZE_TYPE__;
+
+// Test array initialization
+void array_init() {
  const char a[] = __FUNCTION__; // expected-warning{{initializing an array from a '__FUNCTION__' predefined identifier is a Microsoft extension}}
  const char b[] = __FUNCDNAME__; // expected-warning{{initializing an array from a '__FUNCDNAME__' predefined identifier is a Microsoft extension}}
  const char c[] = __FUNCSIG__; // expected-warning{{initializing an array from a '__FUNCSIG__' predefined identifier is a Microsoft extension}}
  const char d[] = __func__; // expected-warning{{initializing an array from a '__func__' predefined identifier is a Microsoft extension}}
  const char e[] = __PRETTY_FUNCTION__; // expected-warning{{initializing an array from a '__PRETTY_FUNCTION__' predefined identifier is a Microsoft extension}}
+ const wchar_t f[] = L__FUNCTION__; // expected-warning{{initializing an array from a 'L__FUNCTION__' predefined identifier is a Microsoft extension}}
+ const wchar_t g[] = L__FUNCSIG__; // expected-warning{{initializing an array from a 'L__FUNCSIG__' predefined identifier is a Microsoft extension}}
+}
+
+// Test function local identifiers outside of a function
+const char* g_function = __FUNCTION__;// expected-warning{{predefined identifier is only valid inside function}}
+const char* g_function_lconcat = "" __FUNCTION__; // expected-warning{{predefined identifier is only valid inside function}} \
+  // expected-warning{{expansion of predefined identifier '__FUNCTION__' to a string literal is a Microsoft extension}}
+const char* g_function_rconcat = __FUNCTION__ ""; // expected-warning{{predefined identifier is only valid inside function}} \
+  // expected-warning{{expansion of predefined identifier '__FUNCTION__' to a string literal is a Microsoft extension}}
+
+namespace NS
+{
+  const char* function = __FUNCTION__;// expected-warning{{predefined identifier is only valid inside function}}
+  const char* function_lconcat = "" __FUNCTION__; // expected-warning{{predefined identifier is only valid inside function}} \
+  // expected-warning{{expansion of predefined identifier '__FUNCTION__' to a string literal is a Microsoft extension}}
+  const char* function_rconcat = __FUNCTION__ ""; // expected-warning{{predefined identifier is only valid inside function}} \
+  // expected-warning{{expansion of predefined identifier '__FUNCTION__' to a string literal is a Microsoft extension}}
+
+  struct S
+  {
+static constexpr const char* function = __FUNCTION__;// expected-warning{{predefined identifier is only valid inside function}}
+static constexpr const char* function_lconcat = "" __FUNCTION__; // expected-warning{{predefined identifier is only valid inside function}} \
+ // expected-warning{{expansion of predefined identifier 

[PATCH] D156175: [clang][ConstExprEmitter] handle NullToPointer ImplicitCastExpr

2023-07-25 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added inline comments.



Comment at: clang/lib/CodeGen/CGExprConstant.cpp:1131-1132
+case CK_NullToPointer: {
+  if (llvm::Constant *C = Visit(subExpr, destType))
+if (C->isNullValue())
+  return CGM.EmitNullConstant(destType);

efriedma wrote:
> nickdesaulniers wrote:
> > efriedma wrote:
> > > nickdesaulniers wrote:
> > > > FWIW, I would have thought these might be unnecessary, but we do trip 2 
> > > > tests without these guards IIRC.
> > > The fact that the Visit can fail doesn't surprise me; you can write 
> > > arbitrary expressions of type nullptr_t (for example, `nullptr_t f(); 
> > > void* g = f();`.  I can't think of any reason you'd need to check 
> > > C->isNullValue(), though; do you have a testcase for that?
> > Failed Tests (2):
> >   Clang :: CodeGenCXX/const-init-cxx11.cpp
> >   Clang :: CodeGenCXX/cxx11-thread-local-instantiated.cpp
> > 
> > Looking at the first:
> > 
> > ```
> > decltype(nullptr) null();
> > int *p = null();
> > ```
> > and the corresponding AST:
> > ```
> > |-FunctionDecl 0x5650ebbb44a8  col:21 used null 
> > 'decltype(nullptr) ()'
> > `-VarDecl 0x5650ebbb45e0  col:8 p 'int *' cinit
> >   `-ImplicitCastExpr 0x5650ebbb4740  'int *' 
> > `-CallExpr 0x5650ebbb4720  
> > 'decltype(nullptr)':'std::nullptr_t'
> >   `-ImplicitCastExpr 0x5650ebbb4708  'decltype(nullptr) (*)()' 
> > 
> > `-DeclRefExpr 0x5650ebbb4690  'decltype(nullptr) ()' lvalue 
> > Function 0x5650ebbb44a8 'null' 'decltype(nullptr) ()'
> > ```
> > 
> > 
> > we change the existing test case from having a `__cxx_global_var_init` 
> > routine, i.e.:
> > ```
> > @p = dso_local global ptr null, align 8
> > @llvm.global_ctors = appending global [1 x { i32, ptr, ptr }] [{ i32, ptr, 
> > ptr } { i32 65535, ptr @_GLOBAL__sub_I_x.cpp, ptr null }]
> > 
> > ; Function Attrs: noinline uwtable
> > define internal void @__cxx_global_var_init() #0 section ".text.startup" {
> > entry:
> >   %call = call ptr @_Z4nullv()
> >   store ptr null, ptr @p, align 8
> >   ret void
> > }
> > 
> > declare ptr @_Z4nullv() #1
> > 
> > ; Function Attrs: noinline uwtable
> > define internal void @_GLOBAL__sub_I_x.cpp() #0 section ".text.startup" {
> > entry:
> >   call void @__cxx_global_var_init()
> >   ret void
> > }
> > ```
> > to simply:
> > ```
> > @p = dso_local global ptr null, align 8
> > ```
> > So it seems nice to skip having the static constructors, but then 
> > `@_Z4nullv` is never invoked.  That seems problematic? (I expect the fast 
> > path to fail once it recurses down to the DeclRefExpr, but that requires 
> > the subexpr of the ImplicitCastExpr be visited).
> > 
> > ---
> > 
> > So I think the code as written is good to go. WDYT?
> I think you need to check that Visit() succeeds (returns a non-null 
> Constant*), but like I said before, I can't see why you need to check 
> `C->isNullValue()`
oh, sorry, my reading comprehension skills are sliding off a cliff.

Yeah, that's not necessary for test cases in tree. Removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156175

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


[PATCH] D156175: [clang][ConstExprEmitter] handle NullToPointer ImplicitCastExpr

2023-07-25 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers updated this revision to Diff 544113.
nickdesaulniers marked 2 inline comments as done.
nickdesaulniers added a comment.

- remove the check for isNullValue as per @efriedma


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156175

Files:
  clang/lib/CodeGen/CGExprConstant.cpp


Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1127,6 +1127,12 @@
 case CK_ConstructorConversion:
   return Visit(subExpr, destType);
 
+case CK_NullToPointer: {
+  if (llvm::Constant *C = Visit(subExpr, destType))
+return CGM.EmitNullConstant(destType);
+  return nullptr;
+}
+
 case CK_IntToOCLSampler:
   llvm_unreachable("global sampler variables are not generated");
 
@@ -1183,7 +1189,6 @@
 case CK_IntegralComplexToFloatingComplex:
 case CK_PointerToIntegral:
 case CK_PointerToBoolean:
-case CK_NullToPointer:
 case CK_IntegralCast:
 case CK_BooleanToSignedIntegral:
 case CK_IntegralToPointer:


Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1127,6 +1127,12 @@
 case CK_ConstructorConversion:
   return Visit(subExpr, destType);
 
+case CK_NullToPointer: {
+  if (llvm::Constant *C = Visit(subExpr, destType))
+return CGM.EmitNullConstant(destType);
+  return nullptr;
+}
+
 case CK_IntToOCLSampler:
   llvm_unreachable("global sampler variables are not generated");
 
@@ -1183,7 +1189,6 @@
 case CK_IntegralComplexToFloatingComplex:
 case CK_PointerToIntegral:
 case CK_PointerToBoolean:
-case CK_NullToPointer:
 case CK_IntegralCast:
 case CK_BooleanToSignedIntegral:
 case CK_IntegralToPointer:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D156189: [-Wunsafe-buffer-usage] Refactor to let local variable fix-its and parameter fix-its share common code

2023-07-25 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 updated this revision to Diff 544111.

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

https://reviews.llvm.org/D156189

Files:
  clang/lib/Analysis/UnsafeBufferUsage.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-local-var-span.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-deref.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-unevaluated-context.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage.cpp

Index: clang/test/SemaCXX/warn-unsafe-buffer-usage.cpp
===
--- clang/test/SemaCXX/warn-unsafe-buffer-usage.cpp
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage.cpp
@@ -80,28 +80,16 @@
   );
 }
 
-void testArraySubscriptsWithAuto(int *p, int **pp) {
+void testArraySubscriptsWithAuto() {
   int a[10];
-  auto ap1 = a;   // expected-warning{{'ap1' is an unsafe pointer used for buffer access}} \
-		 expected-note{{change type of 'ap1' to 'std::span' to preserve bounds information}}
-
+  // We do not fix a declaration if the type is `auto`. Because the actual type may change later.
+  auto ap1 = a;   // expected-warning{{'ap1' is an unsafe pointer used for buffer access}}
   foo(ap1[1]);// expected-note{{used in buffer access here}}
 
-  auto ap2 = p;   // expected-warning{{'ap2' is an unsafe pointer used for buffer access}} \
-  		 expected-note{{change type of 'ap2' to 'std::span' to preserve bounds information}}
-
+  // In case the type is `auto *`, we know it must be a pointer. We can fix it.
+  auto * ap2 = a; // expected-warning{{'ap2' is an unsafe pointer used for buffer access}} \
+ expected-note{{change type of 'ap2' to 'std::span' to preserve bounds information}}
   foo(ap2[1]);// expected-note{{used in buffer access here}}
-
-  auto ap3 = pp;  // expected-warning{{'ap3' is an unsafe pointer used for buffer access}} \
-		 expected-note{{change type of 'ap3' to 'std::span' to preserve bounds information}}
-
-  foo(ap3[1][1]); // expected-note{{used in buffer access here}}
-  // expected-warning@-1{{unsafe buffer access}}
-
-  auto ap4 = *pp; // expected-warning{{'ap4' is an unsafe pointer used for buffer access}} \
-  		 expected-note{{change type of 'ap4' to 'std::span' to preserve bounds information}}
-
-  foo(ap4[1]);// expected-note{{used in buffer access here}}
 }
 
 void testUnevaluatedContext(int * p) {// no-warning
@@ -358,8 +346,9 @@
 }
 
 void testMultiLineDeclStmt(int * p) {
-  auto
+  int
 
+  *
 
   ap1 = p;  // expected-warning{{'ap1' is an unsafe pointer used for buffer access}} \
  	   expected-note{{change type of 'ap1' to 'std::span' to preserve bounds information}}
Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-unevaluated-context.cpp
===
--- clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-unevaluated-context.cpp
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-unevaluated-context.cpp
@@ -15,7 +15,7 @@
 int bar(int *ptr);
 
 void uneval_context_fix_pointer_dereference() {
-  auto p = new int[10];
+  int* p = new int[10];
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:11}:"std::span p"
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-2]]:12-[[@LINE-2]]:12}:"{"
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-3]]:23-[[@LINE-3]]:23}:", 10}"
@@ -30,7 +30,7 @@
 }
 
 void uneval_context_fix_pointer_array_access() {
-  auto p = new int[10];
+  int* p = new int[10];
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:11}:"std::span p"
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-2]]:12-[[@LINE-2]]:12}:"{"
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-3]]:23-[[@LINE-3]]:23}:", 10}"
@@ -41,7 +41,7 @@
 }
 
 void uneval_context_fix_pointer_reference() {
-  auto p = new int[10];
+  int* p = new int[10];
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:11}:"std::span p"
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-2]]:12-[[@LINE-2]]:12}:"{"
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-3]]:23-[[@LINE-3]]:23}:", 10}"
@@ -63,7 +63,7 @@
 
 // FIXME: Emit fixits for each of the below use.
 void uneval_context_fix_pointer_dereference_not_handled() {
-  auto p = new int[10];
+  int* p = new int[10];
   int tmp = p[5];
 
   foo(sizeof(*p), sizeof(decltype(*p)));
Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-deref.cpp
===
--- clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-deref.cpp
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-deref.cpp
@@ -4,7 +4,7 @@
 
 void basic_dereference() {
   int tmp;
-  auto p = new int[10];
+  int* p = new int[10];
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:11}:"std::span p"
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-2]]:12-[[@LINE-2]]:12}:"{"
   // CHECK-DAG: 

[PATCH] D156185: [clang][ConstExprEmitter] handle ArrayToPointerDecay ImplicitCastExpr of StringLiterals

2023-07-25 Thread Eli Friedman via Phabricator via cfe-commits
efriedma accepted this revision.
efriedma added a comment.
This revision is now accepted and ready to land.

I don't have any concern with this specific patch; LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156185

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


[PATCH] D156175: [clang][ConstExprEmitter] handle NullToPointer ImplicitCastExpr

2023-07-25 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: clang/lib/CodeGen/CGExprConstant.cpp:1131-1132
+case CK_NullToPointer: {
+  if (llvm::Constant *C = Visit(subExpr, destType))
+if (C->isNullValue())
+  return CGM.EmitNullConstant(destType);

nickdesaulniers wrote:
> efriedma wrote:
> > nickdesaulniers wrote:
> > > FWIW, I would have thought these might be unnecessary, but we do trip 2 
> > > tests without these guards IIRC.
> > The fact that the Visit can fail doesn't surprise me; you can write 
> > arbitrary expressions of type nullptr_t (for example, `nullptr_t f(); void* 
> > g = f();`.  I can't think of any reason you'd need to check 
> > C->isNullValue(), though; do you have a testcase for that?
> Failed Tests (2):
>   Clang :: CodeGenCXX/const-init-cxx11.cpp
>   Clang :: CodeGenCXX/cxx11-thread-local-instantiated.cpp
> 
> Looking at the first:
> 
> ```
> decltype(nullptr) null();
> int *p = null();
> ```
> and the corresponding AST:
> ```
> |-FunctionDecl 0x5650ebbb44a8  col:21 used null 
> 'decltype(nullptr) ()'
> `-VarDecl 0x5650ebbb45e0  col:8 p 'int *' cinit
>   `-ImplicitCastExpr 0x5650ebbb4740  'int *' 
> `-CallExpr 0x5650ebbb4720  
> 'decltype(nullptr)':'std::nullptr_t'
>   `-ImplicitCastExpr 0x5650ebbb4708  'decltype(nullptr) (*)()' 
> 
> `-DeclRefExpr 0x5650ebbb4690  'decltype(nullptr) ()' lvalue 
> Function 0x5650ebbb44a8 'null' 'decltype(nullptr) ()'
> ```
> 
> 
> we change the existing test case from having a `__cxx_global_var_init` 
> routine, i.e.:
> ```
> @p = dso_local global ptr null, align 8
> @llvm.global_ctors = appending global [1 x { i32, ptr, ptr }] [{ i32, ptr, 
> ptr } { i32 65535, ptr @_GLOBAL__sub_I_x.cpp, ptr null }]
> 
> ; Function Attrs: noinline uwtable
> define internal void @__cxx_global_var_init() #0 section ".text.startup" {
> entry:
>   %call = call ptr @_Z4nullv()
>   store ptr null, ptr @p, align 8
>   ret void
> }
> 
> declare ptr @_Z4nullv() #1
> 
> ; Function Attrs: noinline uwtable
> define internal void @_GLOBAL__sub_I_x.cpp() #0 section ".text.startup" {
> entry:
>   call void @__cxx_global_var_init()
>   ret void
> }
> ```
> to simply:
> ```
> @p = dso_local global ptr null, align 8
> ```
> So it seems nice to skip having the static constructors, but then `@_Z4nullv` 
> is never invoked.  That seems problematic? (I expect the fast path to fail 
> once it recurses down to the DeclRefExpr, but that requires the subexpr of 
> the ImplicitCastExpr be visited).
> 
> ---
> 
> So I think the code as written is good to go. WDYT?
I think you need to check that Visit() succeeds (returns a non-null Constant*), 
but like I said before, I can't see why you need to check `C->isNullValue()`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156175

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


[PATCH] D155997: [Phase Ordering] Don't speculate in SimplifyCFG before PGO annotation

2023-07-25 Thread Teresa Johnson via Phabricator via cfe-commits
tejohnson updated this revision to Diff 544109.
tejohnson added a comment.

Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155997

Files:
  clang/test/CodeGen/pgo-sample-preparation.c
  llvm/lib/Passes/PassBuilderPipelines.cpp
  
llvm/test/Transforms/PhaseOrdering/Inputs/simplifycfg-speculate-blocks.proftext
  
llvm/test/Transforms/PhaseOrdering/Inputs/simplifycfg-speculate-blocks.sampleprof
  llvm/test/Transforms/PhaseOrdering/simplifycfg-speculate-blocks.ll

Index: llvm/test/Transforms/PhaseOrdering/simplifycfg-speculate-blocks.ll
===
--- /dev/null
+++ llvm/test/Transforms/PhaseOrdering/simplifycfg-speculate-blocks.ll
@@ -0,0 +1,99 @@
+;; Check that SimplifyCFG does not attempt speculation until after PGO is
+;; annotated in the IR, and then does not perform it when unprofitable.
+
+;; No PGO: SimplifyCFG should speculate.
+; RUN: opt < %s -passes='default' -S | FileCheck %s --check-prefix=YES
+; RUN: opt < %s -passes='thinlto-pre-link' -S | FileCheck %s --check-prefix=YES
+; RUN: opt < %s -passes='lto-pre-link' -S | FileCheck %s --check-prefix=YES
+
+;; Instrumentation PGO: SimplifyCFG should only attempt speculation after PGO
+;; annotation, and in the below cases should not speculate given the branch
+;; biases.
+; RUN: llvm-profdata merge %S/Inputs/simplifycfg-speculate-blocks.proftext -o %t.profdata
+; RUN: opt < %s -passes='default' -pgo-kind=pgo-instr-use-pipeline -profile-file=%t.profdata -S | FileCheck %s --check-prefixes=NO,INSTR
+; RUN: opt < %s -passes='thinlto-pre-link' -pgo-kind=pgo-instr-use-pipeline -profile-file=%t.profdata -S | FileCheck %s --check-prefixes=NO,INSTR
+; RUN: opt < %s -passes='lto-pre-link' -pgo-kind=pgo-instr-use-pipeline -profile-file=%t.profdata -S | FileCheck %s --check-prefixes=NO,INSTR --implicit-check-not=select
+
+;; Sample PGO: SimplifyCFG should only attempt speculation after PGO
+;; annotation, and in the below cases should not speculate given the branch
+;; biases.
+; RUN: opt < %s -passes='default' -pgo-kind=pgo-sample-use-pipeline -profile-file=%S/Inputs/simplifycfg-speculate-blocks.sampleprof -S | FileCheck %s --check-prefixes=NO,SAMPLE
+; RUN: opt < %s -passes='thinlto-pre-link' -pgo-kind=pgo-sample-use-pipeline -profile-file=%S/Inputs/simplifycfg-speculate-blocks.sampleprof -S | FileCheck %s --check-prefixes=NO,SAMPLE
+; RUN: opt < %s -passes='thinlto-pre-link' -pgo-kind=pgo-sample-use-pipeline -profile-file=%S/Inputs/simplifycfg-speculate-blocks.sampleprof -S | FileCheck %s --check-prefixes=NO,SAMPLE
+
+%structx = type { [23 x i8], [0 x i8], i8 }
+define ptr @fold_two_entry_phi(ptr noundef nonnull align 8 dereferenceable(24) %v0) #0 !dbg !12 {
+; YES-LABEL: define ptr @fold_two_entry_phi
+; NO-LABEL: define ptr @fold_two_entry_phi
+  %1 = getelementptr inbounds %structx, ptr %v0, i64 0, i32 2
+  %2 = load i8, ptr %1, align 1
+  %3 = icmp slt i8 %2, 0
+  br i1 %3, label %truelabel, label %falselabel, !dbg !15
+; YES:select
+; INSTR: br i1 {{.*}} !prof ![[PROF:[0-9]+]]
+; SAMPLE: br i1 {{.*}} !prof ![[PROF1:[0-9]+]]
+truelabel:
+  %4 = load ptr, ptr %v0, align 8, !dbg !16
+  br label %retlabel, !dbg !16
+falselabel:
+  br label %retlabel, !dbg !17
+retlabel:
+  %5 = phi ptr [ %4, %truelabel ], [ %v0, %falselabel ], !dbg !18
+  ret ptr %5, !dbg !18
+}
+
+define void @fold_branch_to_common_dest(i8 %v0, i8 %v1) #0 !dbg !19 {
+; YES-LABEL: define void @fold_branch_to_common_dest
+; NO-LABEL: define void @fold_branch_to_common_dest
+pred:
+  %c0 = icmp eq i8 %v0, 0
+  br i1 %c0, label %dispatch, label %final_right, !dbg !20
+; YES:select
+; INSTR: br i1 %c0, label %dispatch, label %final_right, !dbg {{.*}}, !prof ![[PROF]]
+; SAMPLE: br i1 %c0, label %dispatch, label %final_right, !dbg {{.*}}, !prof ![[PROF2:[0-9]+]]
+dispatch:
+  %c1 = icmp eq i8 %v1, 0, !dbg !21
+  br i1 %c1, label %final_left, label %final_right, !dbg !21
+final_left:
+  call void @sideeffect0(), !dbg !22
+  ret void, !dbg !22
+final_right:
+  call void @sideeffect1(), !dbg !23
+  ret void, !dbg !23
+}
+
+declare void @sideeffect0()
+declare void @sideeffect1()
+
+; INSTR: ![[PROF]] = !{!"branch_weights", i32 0, i32 5000}
+; SAMPLE: ![[PROF1]] = !{!"branch_weights", i32 1, i32 5002}
+; SAMPLE: ![[PROF2]] = !{!"branch_weights", i32 1, i32 5001}
+
+attributes #0 = { "use-sample-profile" }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!2, !3, !4, !5, !6, !7, !8}
+!llvm.ident = !{!11}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus_14, file: !1, producer: "clang version 17.0.0 (g...@github.com:llvm/llvm-project.git 180a8148f95d2d5ed96c670fc322292fa0df876c)", isOptimized: true, runtimeVersion: 0, emissionKind: LineTablesOnly, splitDebugInlining: false, nameTableKind: None)
+!1 = !DIFile(filename: "simplifycfg-speculate-blocks.cc", directory: ".", checksumkind: CSK_MD5, checksum: 

[PATCH] D156185: [clang][ConstExprEmitter] handle ArrayToPointerDecay ImplicitCastExpr of StringLiterals

2023-07-25 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

In D156185#4533083 , @efriedma wrote:

> No, that's taking the address of a string literal lvalue.

ah! sorry, yeah
`const char* foo = "foo";`
vs
`char foo[10] = "x";`

That AST looks like:

  `-VarDecl 0x55eaf6075ba8  col:6 foo 'char[10]' cinit
`-StringLiteral 0x55eaf6075c98  'char[10]' "x"

That case is handled today by the fast path today.  The case //I// refer to 
which is 1000% more common is not, hence this patch. WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156185

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


[PATCH] D154838: [analyzer] Add check for null pointer passed to %p of printf family

2023-07-25 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

> Should I cover non-standard (i.e., non ISO C standard) functions from the 
> `printf_s` family? Should I cover non-standard functions like `dprintf`?

The static analyzer, unlike the compiler proper, isn't required to treat all 
code fairly. It's ok to have different behavior depending solely on the 
function's name. So if you want to support non-standard functions, and you know 
that they have the same portability issues, totally go for it!

> This check is part of the UnixAPIPortability checker, which is already 
> registered. Do you suggest creating a separate checker for this check?

Probably a separate check would be better. The consequences of `malloc(0)` are 
likely to be much more dire than consequences of `printf("%p", 0)`, so people 
may want to enable/disable them separately.

> What is the correct way to update expected plists for test inputs?

The run-lines are mostly self-explanatory. Just run it through the `grep` 
command in the other run-line. It filters out all the non-transferable stuff. 
(You clearly don't want to have paths like `/Users/georgiy.lebedev/Work/...` in 
test files.)

Or, put your test in a separate file with a simpler run-line that doesn't 
additionally verify plist output. We already have enough tests for plist output.

In D154838#4532929 , @MitalAshok 
wrote:

> Instead of checking for hard-coded names, you can check functions with the 
> format(printf, x, y) 
>  attribute:
>
>   if (auto *Format = FD->getAttr())
> CheckPrintfPointerConversionSpecifierNULL(C, CE, Format->getFormatIdx());

Is the behavior necessarily implementation-defined for all such functions? I'm 
pretty sure you can find this attribute on a project-local function that will 
never have more than one implementation.




Comment at: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp:479-480
+const clang::Expr *arg) const {
+  ExplodedNode *N =
+  C.generateNonFatalErrorNode(nullState ? nullState : C.getState());
+  if (!N)

> What is the right way to emit a bug report? I have studied the code base and 
> found several patterns: in some cases, an error node is simply generated, in 
> others a new transition is also added based on the analyzed state. In some 
> cases an expression value is also tracked.

You always need to track the value when reporting things about values, it adds 
notes to the report explaining why do we think the variable has that value 
(eg., it was assigned null or compared to null).

Most checkers need this, though for some checkers it's more important than for 
other checkers.



Whether to generate a non-fatal error node and what state to put into it, this 
is indeed a very case-by-case decision. In your case the behavior is not 
undefined, the program doesn't crash when the bug happens, it continues to run 
normally, so analysis should probably also continue to find more defects. There 
are a few unknowns about the program's behavior (in particular, we don't know 
what it actually printed), but we never promised to figure this out in the 
first place. And even if there are unknowns that matter, well, unknowns are 
part of life and the rest of the static analyzer is already built under the 
assumption that not everything is known.

If it was an actual null pointer dereference, then you'd have to terminate the 
analysis by generating a fatal error node. The user won't be happy to learn 
about a "bug" that only occurs under the assumption that the program has 
already crashed with null dereference. And if it doesn't *only* occur under 
that assumption, then we'll probably find the same bug anyway while exploring a 
different execution path that doesn't crash.

---

A separate question is, do we want to assume that the pointer `x` is non-null 
after its first use in `printf("%p", x)`? We may or may not need to assume this 
regardless of whether we see a path on which it's //definitely// null. Eg., 
consider:
```lang=c
void foo(int *x) {
  // (1) We probably can't want to warn here, because there's no indication 
that 'x' can be null.
  printf("%p\n", x);

  // This is an indication that 'x' can be null.
  //
  // Technically it applies retroactively to the first line, but retroactive 
warnings are hard
  // because multiple different paths could reach this check, and it's not 
necessarily there
  // specifically for our current path.
  if (x == NULL) {
printf("WARNING: null passed to foo()!");
  }

  // (2) Now, do we want to warn here? We probably do.
  //
  // But note that if we reached (2), we've already exhibited the same 
non-portable behavior
  // at (1) where no warning was emitted.
  printf("%p\n", x);

  // (3) Do we want to warn again here?
  printf("%p\n", x);

  // (4) What if it was a plain null dereference?
  printf("%d\n", *x);
}
```

If at (1), (2), (3) instead of `printf("%p, x)` we had a 

[PATCH] D154186: [clang][DeclPrinter] Fix AST print of delegating constructors

2023-07-25 Thread Timo Stripf via Phabricator via cfe-commits
strimo378 added a comment.

I plan around half a dozen patches only for ast-print functionality. I would 
love to land it myself and will asked for commit privileges.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154186

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


[PATCH] D156175: [clang][ConstExprEmitter] handle NullToPointer ImplicitCastExpr

2023-07-25 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added inline comments.



Comment at: clang/lib/CodeGen/CGExprConstant.cpp:1131-1132
+case CK_NullToPointer: {
+  if (llvm::Constant *C = Visit(subExpr, destType))
+if (C->isNullValue())
+  return CGM.EmitNullConstant(destType);

efriedma wrote:
> nickdesaulniers wrote:
> > FWIW, I would have thought these might be unnecessary, but we do trip 2 
> > tests without these guards IIRC.
> The fact that the Visit can fail doesn't surprise me; you can write arbitrary 
> expressions of type nullptr_t (for example, `nullptr_t f(); void* g = f();`.  
> I can't think of any reason you'd need to check C->isNullValue(), though; do 
> you have a testcase for that?
Failed Tests (2):
  Clang :: CodeGenCXX/const-init-cxx11.cpp
  Clang :: CodeGenCXX/cxx11-thread-local-instantiated.cpp

Looking at the first:

```
decltype(nullptr) null();
int *p = null();
```
and the corresponding AST:
```
|-FunctionDecl 0x5650ebbb44a8  col:21 used null 
'decltype(nullptr) ()'
`-VarDecl 0x5650ebbb45e0  col:8 p 'int *' cinit
  `-ImplicitCastExpr 0x5650ebbb4740  'int *' 
`-CallExpr 0x5650ebbb4720  
'decltype(nullptr)':'std::nullptr_t'
  `-ImplicitCastExpr 0x5650ebbb4708  'decltype(nullptr) (*)()' 

`-DeclRefExpr 0x5650ebbb4690  'decltype(nullptr) ()' lvalue 
Function 0x5650ebbb44a8 'null' 'decltype(nullptr) ()'
```


we change the existing test case from having a `__cxx_global_var_init` routine, 
i.e.:
```
@p = dso_local global ptr null, align 8
@llvm.global_ctors = appending global [1 x { i32, ptr, ptr }] [{ i32, ptr, ptr 
} { i32 65535, ptr @_GLOBAL__sub_I_x.cpp, ptr null }]

; Function Attrs: noinline uwtable
define internal void @__cxx_global_var_init() #0 section ".text.startup" {
entry:
  %call = call ptr @_Z4nullv()
  store ptr null, ptr @p, align 8
  ret void
}

declare ptr @_Z4nullv() #1

; Function Attrs: noinline uwtable
define internal void @_GLOBAL__sub_I_x.cpp() #0 section ".text.startup" {
entry:
  call void @__cxx_global_var_init()
  ret void
}
```
to simply:
```
@p = dso_local global ptr null, align 8
```
So it seems nice to skip having the static constructors, but then `@_Z4nullv` 
is never invoked.  That seems problematic? (I expect the fast path to fail once 
it recurses down to the DeclRefExpr, but that requires the subexpr of the 
ImplicitCastExpr be visited).

---

So I think the code as written is good to go. WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156175

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


[clang] b6847ed - For #64088: mark vtable as used if we might emit a reference to it.

2023-07-25 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2023-07-25T14:42:10-07:00
New Revision: b6847edfc235829b37dd6d734ef5bbfa0a58b6fc

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

LOG: For #64088: mark vtable as used if we might emit a reference to it.

Added: 


Modified: 
clang/lib/Sema/SemaCast.cpp
clang/test/CodeGenCXX/dynamic-cast-exact.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaCast.cpp b/clang/lib/Sema/SemaCast.cpp
index d65ecf52c52310..b338d601db7397 100644
--- a/clang/lib/Sema/SemaCast.cpp
+++ b/clang/lib/Sema/SemaCast.cpp
@@ -935,6 +935,14 @@ void CastOperation::CheckDynamicCast() {
   << isClangCL;
   }
 
+  // For a dynamic_cast to a final type, IR generation might emit a reference
+  // to the vtable.
+  if (DestRecord) {
+auto *DestDecl = DestRecord->getAsCXXRecordDecl();
+if (DestDecl->isEffectivelyFinal())
+  Self.MarkVTableUsed(OpRange.getBegin(), DestDecl);
+  }
+
   // Done. Everything else is run-time checks.
   Kind = CK_Dynamic;
 }

diff  --git a/clang/test/CodeGenCXX/dynamic-cast-exact.cpp 
b/clang/test/CodeGenCXX/dynamic-cast-exact.cpp
index 676aa975a72686..bd283e85101b4b 100644
--- a/clang/test/CodeGenCXX/dynamic-cast-exact.cpp
+++ b/clang/test/CodeGenCXX/dynamic-cast-exact.cpp
@@ -76,3 +76,12 @@ H *exact_multi(A *a) {
   // CHECK: phi ptr [ %[[RESULT]], %[[LABEL_NOTNULL]] ], [ null, 
%[[LABEL_FAILED]] ]
   return dynamic_cast(a);
 }
+
+namespace GH64088 {
+  // Ensure we mark the B vtable as used here, because we're going to emit a
+  // reference to it.
+  // CHECK: define {{.*}} @_ZN7GH640881BD0
+  struct A { virtual ~A(); };
+  struct B final : A { virtual ~B() = default; };
+  B *cast(A *p) { return dynamic_cast(p); }
+}



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


[PATCH] D156188: [-Wunsafe-buffer-usage] Refactor and improve for parameter fix-its

2023-07-25 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 updated this revision to Diff 544104.

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

https://reviews.llvm.org/D156188

Files:
  clang/lib/Analysis/UnsafeBufferUsage.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-span.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-unsupported.cpp

Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-unsupported.cpp
===
--- clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-unsupported.cpp
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-unsupported.cpp
@@ -1,34 +1,21 @@
 // RUN: %clang_cc1 -std=c++20 -Wno-all -Wunsafe-buffer-usage -fcxx-exceptions -fsafe-buffer-usage-suggestions -verify %s
 // RUN: %clang_cc1 -std=c++20 -Wunsafe-buffer-usage -fcxx-exceptions -fdiagnostics-parseable-fixits -fsafe-buffer-usage-suggestions %s 2>&1 | FileCheck %s
 
-void const_ptr(int * const x) { // expected-warning{{'x' is an unsafe pointer used for buffer access}} expected-note{{change type of 'x' to 'std::span' to preserve bounds information}}
-  // CHECK: fix-it:{{.*}}:{[[@LINE-1]]:16-[[@LINE-1]]:29}:"std::span const x"
-  int tmp = x[5]; // expected-note{{used in buffer access here}}
-}
-// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:2-[[@LINE-1]]:2}:"\n{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}} void const_ptr(int * const x) {return const_ptr(std::span(x, <# size #>));}\n"
-
-void const_ptr_to_const(const int * const x) {// expected-warning{{'x' is an unsafe pointer used for buffer access}} expected-note{{change type of 'x' to 'std::span' to preserve bounds information}}
-  // CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:25-[[@LINE-1]]:44}:"std::span const x"
-  int tmp = x[5]; // expected-note{{used in buffer access here}}
-}
-// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:2-[[@LINE-1]]:2}:"\n{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}} void const_ptr_to_const(const int * const x) {return const_ptr_to_const(std::span(x, <# size #>));}\n"
+typedef int * TYPEDEF_PTR;
+#define MACRO_PTR int*
 
-typedef struct {int x;} NAMED_UNNAMED_STRUCT; // an unnamed struct type named by a typedef
-typedef struct {int x;} * PTR_TO_ANON;// pointer to an unnamed struct
-typedef NAMED_UNNAMED_STRUCT * PTR_TO_NAMED;  // pointer to a named type
+// We CANNOT fix a pointer whose type is defined in a typedef or a
+// macro. Because if the typedef is changed after the fix, the fix
+// becomes incorrect and may not be noticed.
 
-// We can fix a pointer to a named type
-void namedPointeeType(NAMED_UNNAMED_STRUCT * p) {  // expected-warning{{'p' is an unsafe pointer used for buffer access}}\ expected-note{{change type of 'p' to 'std::span' to preserve bounds information}}
-  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:23-[[@LINE-1]]:47}:"std::span p"
+// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE+1]]
+void typedefPointer(TYPEDEF_PTR p) {  // expected-warning{{'p' is an unsafe pointer used for buffer access}}
   if (++p) {  // expected-note{{used in pointer arithmetic here}}
-// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:7-[[@LINE-1]]:10}:"(p = p.subspan(1)).data()"
   }
 }
-// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:2-[[@LINE-1]]:2}:"\n{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}} void namedPointeeType(NAMED_UNNAMED_STRUCT * p) {return namedPointeeType(std::span(p, <# size #>));}\n"
 
-// We CANNOT fix a pointer to an unnamed type
-// CHECK-NOT: fix-it:
-void unnamedPointeeType(PTR_TO_ANON p) {  // expected-warning{{'p' is an unsafe pointer used for buffer access}}
+// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE+1]]
+void macroPointer(MACRO_PTR p) {  // expected-warning{{'p' is an unsafe pointer used for buffer access}}
   if (++p) {  // expected-note{{used in pointer arithmetic here}}
   }
 }
@@ -148,3 +135,17 @@
   int tmp;
   tmp = x[5]; // expected-note{{used in buffer access here}}
 }
+
+#define MACRO_NAME MyName
+
+// CHECK-NOT: fix-it:{{.*}}:{[[@LINE+1]]
+void macroIdentifier(int * MACRO_NAME) { // The fix-it ends with a macro. It will be discarded due to overlap with macros. \
+	expected-warning{{'MyName' is an unsafe pointer used for buffer access}}
+  if (++MyName){} // expected-note{{used in pointer arithmetic here}}
+}
+
+// CHECK-NOT: fix-it:{{.*}}:{[[@LINE+1]]
+void parmHasNoName(int *p, int *) { // cannot fix the function because there is one parameter has no name. \
+   expected-warning{{'p' is an unsafe pointer used for buffer access}}
+  p[5] = 5; // expected-note{{used in buffer access here}}
+}
Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-span.cpp
===
--- clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-span.cpp
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-span.cpp
@@ -147,18 +147,78 @@
   if (++a){}
 }
 
-// Make sure we do not generate fixes for the following cases:
+// Tests parameters with cv-qualifiers
 
-#define MACRO_NAME MyName
+void 

[PATCH] D156172: [clang][CodeGen] Emit annotations for function declarations.

2023-07-25 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

Slightly messed up my example because I forgot the function was unprototyped.  
The following should show what I mean:

  void foo(void);
  void *xxx = (void*)foo;
  __attribute__((annotate("bar"))) void foo(){}

In terms of where the right place is, I don't recall the exact structure of 
that code off the top of my head, but I think there's somewhere we handle 
redeclarations?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156172

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


[PATCH] D154007: Reland "Try to implement lambdas with inalloca parameters by forwarding without use of inallocas."

2023-07-25 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 544101.
akhuang added a comment.

add TODO


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154007

Files:
  clang/include/clang/CodeGen/CGFunctionInfo.h
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGCall.h
  clang/lib/CodeGen/CGClass.cpp
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CodeGenABITypes.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/CodeGenTypes.h
  clang/lib/CodeGen/Targets/X86.cpp
  clang/test/CodeGenCXX/inalloca-lambda.cpp

Index: clang/test/CodeGenCXX/inalloca-lambda.cpp
===
--- clang/test/CodeGenCXX/inalloca-lambda.cpp
+++ clang/test/CodeGenCXX/inalloca-lambda.cpp
@@ -1,11 +1,63 @@
-// RUN: not %clang_cc1 -triple i686-windows-msvc -emit-llvm -o /dev/null %s  2>&1 | FileCheck %s
+// RUN: %clang_cc1 -triple i686-windows-msvc -emit-llvm -o - %s  2>&1 | FileCheck %s
 
-// PR28299
-// CHECK: error: cannot compile this forwarded non-trivially copyable parameter yet
-
-class A {
+struct A {
+  A();
   A(const A &);
+  int x;
 };
-typedef void (*fptr_t)(A);
-fptr_t fn1() { return [](A) {}; }
+void decayToFp(int (*f)(A));
+void test() {
+  auto ld = [](A a) {
+static int calls = 0;
+++calls;
+return a.x + calls;
+  };
+  decayToFp(ld);
+  ld(A{});
+}
+
+// CHECK: define internal x86_thiscallcc noundef i32
+// CHECK-SAME: @"??R@?0??test@@YAXXZ@QBE?A?@@UA@@@Z"
+// CHECK-SAME: (ptr noundef %this, ptr inalloca(<{ %struct.A }>) %[[ARG:.*]])
+// CHECK: %[[V:.*]] = getelementptr inbounds <{ %struct.A }>, ptr %[[ARG]], i32 0, i32 0
+// CHECK: %call = call x86_thiscallcc noundef i32
+// CHECK-SAME: @"?__impl@@?0??test@@YAXXZ@QBE?A?@@UA@@@Z"
+// CHECK-SAME: (ptr noundef %this, ptr noundef %[[V]])
+
+// CHECK: define internal noundef i32
+// CHECK-SAME: @"?__invoke@@?0??test@@YAXXZ@CA?A?@@UA@@@Z"
+// CHECK-SAME: (ptr inalloca(<{ %struct.A }>) %[[ARG:.*]])
+// CHECK: %unused.capture = alloca %class.anon, align 1
+// CHECK: %[[VAR:.*]] = getelementptr inbounds <{ %struct.A }>, ptr %[[ARG]], i32 0, i32 0
+// CHECK: %call = call x86_thiscallcc noundef i32
+// CHECK-SAME: @"?__impl@@?0??test@@YAXXZ@QBE?A?@@UA@@@Z"
+// CHECK-SAME: (ptr noundef %unused.capture, ptr noundef %[[VAR]])
+// CHECK: ret i32 %call
+
+// CHECK: define internal x86_thiscallcc noundef i32
+// CHECK-SAME: @"?__impl@@?0??test@@YAXXZ@QBE?A?@@UA@@@Z"
+// CHECK-SAME: (ptr noundef %this, ptr noundef %[[ARG:.*]])
+// CHECK: %this.addr = alloca ptr, align 4
+// CHECK: store ptr %this, ptr %this.addr, align 4
+// CHECK: %this1 = load ptr, ptr %this.addr, align 4
+// CHECK: %{{.*}} = load i32, ptr @"?calls@?1???R
+// CHECK: %inc = add nsw i32 %{{.*}}, 1
+// CHECK: store i32 %inc, ptr @"?calls@?1???R
+// CHECK: %{{.*}} = getelementptr inbounds %struct.A, ptr %{{.*}}, i32 0, i32 0
+// CHECK: %{{.*}} = load i32, ptr %{{.*}}, align 4
+// CHECK: %{{.*}} = load i32, ptr @"?calls@?1???R
+// CHECK: %add = add nsw i32 %{{.*}}, %{{.*}}
+// CHECK: ret i32 %add
+
+// Make sure we don't try to copy an uncopyable type.
+struct B {
+  B();
+  B(B &);
+  void operator=(B);
+  long long x;
+} b;
+
+void f() {
+  [](B) {}(b);
+}
 
Index: clang/lib/CodeGen/Targets/X86.cpp
===
--- clang/lib/CodeGen/Targets/X86.cpp
+++ clang/lib/CodeGen/Targets/X86.cpp
@@ -140,7 +140,8 @@
 
   Class classify(QualType Ty) const;
   ABIArgInfo classifyReturnType(QualType RetTy, CCState ) const;
-  ABIArgInfo classifyArgumentType(QualType RetTy, CCState ) const;
+  ABIArgInfo classifyArgumentType(QualType RetTy, CCState ,
+  bool isDelegateCall) const;
 
   /// Updates the number of available free registers, returns
   /// true if any registers were allocated.
@@ -737,8 +738,8 @@
   }
 }
 
-ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
-   CCState ) const {
+ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState ,
+   bool isDelegateCall) const {
   // FIXME: Set alignment on indirect arguments.
   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
@@ -753,6 +754,12 @@
 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
 if (RAA == CGCXXABI::RAA_Indirect) {
   return getIndirectResult(Ty, false, State);
+} else if (isDelegateCall) {
+  // Avoid having different alignments on delegate call args by always
+  // setting the alignment to 4, which is what we do for inallocas.
+  ABIArgInfo Res = getIndirectResult(Ty, false, State);
+  Res.setIndirectAlign(CharUnits::fromQuantity(4));
+  return Res;
 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
   // The field index doesn't matter, we'll fix 

[PATCH] D156182: [clang][CodeGenModule] remove declaration of GetAddrOfConstantString

2023-07-25 Thread Nick Desaulniers via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGef103adf60c6: [clang][CodeGenModule] remove declaration of 
GetAddrOfConstantString (authored by nickdesaulniers).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156182

Files:
  clang/include/clang/CodeGen/ConstantInitBuilder.h
  clang/lib/CodeGen/CodeGenModule.h


Index: clang/lib/CodeGen/CodeGenModule.h
===
--- clang/lib/CodeGen/CodeGenModule.h
+++ clang/lib/CodeGen/CodeGenModule.h
@@ -1019,11 +1019,6 @@
   /// Return a pointer to a constant CFString object for the given string.
   ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
 
-  /// Return a pointer to a constant NSString object for the given string. Or a
-  /// user defined String object as defined via
-  /// -fconstant-string-class=class_name option.
-  ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
-
   /// Return a constant array for the given string.
   llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
 
Index: clang/include/clang/CodeGen/ConstantInitBuilder.h
===
--- clang/include/clang/CodeGen/ConstantInitBuilder.h
+++ clang/include/clang/CodeGen/ConstantInitBuilder.h
@@ -41,7 +41,7 @@
 ///for (auto  : widgets) {
 ///  auto widgetDesc = widgetArray.beginStruct();
 ///  widgetDesc.addInt(CGM.SizeTy, widget.getPower());
-///  widgetDesc.add(CGM.GetAddrOfConstantString(widget.getName()));
+///  
widgetDesc.add(CGM.GetAddrOfConstantStringFromLiteral(widget.getName()));
 ///  widgetDesc.add(CGM.GetAddrOfGlobal(widget.getInitializerDecl()));
 ///  widgetDesc.finishAndAddTo(widgetArray);
 ///}


Index: clang/lib/CodeGen/CodeGenModule.h
===
--- clang/lib/CodeGen/CodeGenModule.h
+++ clang/lib/CodeGen/CodeGenModule.h
@@ -1019,11 +1019,6 @@
   /// Return a pointer to a constant CFString object for the given string.
   ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
 
-  /// Return a pointer to a constant NSString object for the given string. Or a
-  /// user defined String object as defined via
-  /// -fconstant-string-class=class_name option.
-  ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
-
   /// Return a constant array for the given string.
   llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
 
Index: clang/include/clang/CodeGen/ConstantInitBuilder.h
===
--- clang/include/clang/CodeGen/ConstantInitBuilder.h
+++ clang/include/clang/CodeGen/ConstantInitBuilder.h
@@ -41,7 +41,7 @@
 ///for (auto  : widgets) {
 ///  auto widgetDesc = widgetArray.beginStruct();
 ///  widgetDesc.addInt(CGM.SizeTy, widget.getPower());
-///  widgetDesc.add(CGM.GetAddrOfConstantString(widget.getName()));
+///  widgetDesc.add(CGM.GetAddrOfConstantStringFromLiteral(widget.getName()));
 ///  widgetDesc.add(CGM.GetAddrOfGlobal(widget.getInitializerDecl()));
 ///  widgetDesc.finishAndAddTo(widgetArray);
 ///}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ef103ad - [clang][CodeGenModule] remove declaration of GetAddrOfConstantString

2023-07-25 Thread Nick Desaulniers via cfe-commits

Author: Nick Desaulniers
Date: 2023-07-25T14:25:25-07:00
New Revision: ef103adf60c6fccd3cc6d76b362c1c37c41da30f

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

LOG: [clang][CodeGenModule] remove declaration of GetAddrOfConstantString

It looks like the definition was removed in cd21d541397e but the
declaration was not.  Surprisingly (to me), that doesn't seem to produce
any kind of diagnostic.

Reviewed By: efriedma

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

Added: 


Modified: 
clang/include/clang/CodeGen/ConstantInitBuilder.h
clang/lib/CodeGen/CodeGenModule.h

Removed: 




diff  --git a/clang/include/clang/CodeGen/ConstantInitBuilder.h 
b/clang/include/clang/CodeGen/ConstantInitBuilder.h
index 88e357a0c29c06..9e0d0fa0d8e824 100644
--- a/clang/include/clang/CodeGen/ConstantInitBuilder.h
+++ b/clang/include/clang/CodeGen/ConstantInitBuilder.h
@@ -41,7 +41,7 @@ class CodeGenModule;
 ///for (auto  : widgets) {
 ///  auto widgetDesc = widgetArray.beginStruct();
 ///  widgetDesc.addInt(CGM.SizeTy, widget.getPower());
-///  widgetDesc.add(CGM.GetAddrOfConstantString(widget.getName()));
+///  
widgetDesc.add(CGM.GetAddrOfConstantStringFromLiteral(widget.getName()));
 ///  widgetDesc.add(CGM.GetAddrOfGlobal(widget.getInitializerDecl()));
 ///  widgetDesc.finishAndAddTo(widgetArray);
 ///}

diff  --git a/clang/lib/CodeGen/CodeGenModule.h 
b/clang/lib/CodeGen/CodeGenModule.h
index c5de947687ea61..8517b1c93b40f1 100644
--- a/clang/lib/CodeGen/CodeGenModule.h
+++ b/clang/lib/CodeGen/CodeGenModule.h
@@ -1019,11 +1019,6 @@ class CodeGenModule : public CodeGenTypeCache {
   /// Return a pointer to a constant CFString object for the given string.
   ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal);
 
-  /// Return a pointer to a constant NSString object for the given string. Or a
-  /// user defined String object as defined via
-  /// -fconstant-string-class=class_name option.
-  ConstantAddress GetAddrOfConstantString(const StringLiteral *Literal);
-
   /// Return a constant array for the given string.
   llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E);
 



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


[PATCH] D156154: [clang][ConstExprEmitter] handle IntegerLiterals

2023-07-25 Thread Nick Desaulniers via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG15a484bf6990: [clang][ConstExprEmitter] handle 
IntegerLiterals (authored by nickdesaulniers).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156154

Files:
  clang/lib/CodeGen/CGExprConstant.cpp


Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1215,6 +1215,10 @@
 return Visit(E->getSubExpr(), T);
   }
 
+  llvm::Constant *VisitIntegerLiteral(IntegerLiteral *I, QualType T) {
+return llvm::ConstantInt::get(CGM.getLLVMContext(), I->getValue());
+  }
+
   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
 assert(CAT && "can't emit array init for non-constant-bound array");


Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1215,6 +1215,10 @@
 return Visit(E->getSubExpr(), T);
   }
 
+  llvm::Constant *VisitIntegerLiteral(IntegerLiteral *I, QualType T) {
+return llvm::ConstantInt::get(CGM.getLLVMContext(), I->getValue());
+  }
+
   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
 assert(CAT && "can't emit array init for non-constant-bound array");
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 15a484b - [clang][ConstExprEmitter] handle IntegerLiterals

2023-07-25 Thread Nick Desaulniers via cfe-commits

Author: Nick Desaulniers
Date: 2023-07-25T14:12:50-07:00
New Revision: 15a484bf6990c5c3b759f5bbf99055612c20b924

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

LOG: [clang][ConstExprEmitter] handle IntegerLiterals

Improves the ability of ConstExprEmitter to evaluate constants.

Found by adding asserts to ConstantEmitter::tryEmitPrivate to find cases
where ConstExprEmitter::Visit() fails to resolve (obvious) constants.

Reviewed By: efriedma

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

Added: 


Modified: 
clang/lib/CodeGen/CGExprConstant.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGExprConstant.cpp 
b/clang/lib/CodeGen/CGExprConstant.cpp
index 353ee56839f37e..836561a0fb7325 100644
--- a/clang/lib/CodeGen/CGExprConstant.cpp
+++ b/clang/lib/CodeGen/CGExprConstant.cpp
@@ -1215,6 +1215,10 @@ class ConstExprEmitter :
 return Visit(E->getSubExpr(), T);
   }
 
+  llvm::Constant *VisitIntegerLiteral(IntegerLiteral *I, QualType T) {
+return llvm::ConstantInt::get(CGM.getLLVMContext(), I->getValue());
+  }
+
   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
 assert(CAT && "can't emit array init for non-constant-bound array");



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


[PATCH] D156261: [NFC] Cast unchecked return values to void.

2023-07-25 Thread Sindhu Chittireddy via Phabricator via cfe-commits
schittir created this revision.
schittir added reviewers: tahonermann, aaron.ballman.
Herald added a project: All.
schittir 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/D156261

Files:
  clang/lib/Sema/SemaDeclCXX.cpp


Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -2482,7 +2482,7 @@
 << /*Call*/ 1 << /*Function*/ 0 << E->getSourceRange();
   }
   for (auto A : E->arguments()) {
-getDerived().TraverseStmt(A);
+(void)getDerived().TraverseStmt(A);
   }
   return true;
 }
@@ -2516,7 +2516,7 @@
 bool VisitBlockExpr(BlockExpr *T) { return true; }
 
   } Visitor(*this, FD);
-  Visitor.TraverseStmt(FD->getBody());
+  (void)Visitor.TraverseStmt(FD->getBody());
 }
 
 /// Get the class that is directly named by the current context. This is the


Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -2482,7 +2482,7 @@
 << /*Call*/ 1 << /*Function*/ 0 << E->getSourceRange();
   }
   for (auto A : E->arguments()) {
-getDerived().TraverseStmt(A);
+(void)getDerived().TraverseStmt(A);
   }
   return true;
 }
@@ -2516,7 +2516,7 @@
 bool VisitBlockExpr(BlockExpr *T) { return true; }
 
   } Visitor(*this, FD);
-  Visitor.TraverseStmt(FD->getBody());
+  (void)Visitor.TraverseStmt(FD->getBody());
 }
 
 /// Get the class that is directly named by the current context. This is the
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153914: [clang-cl] Enable concatenation of predefined identifiers

2023-07-25 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:1981
+  // parsed yet).
+  assert(getLangOpts().MicrosoftExt);
+

RIscRIpt wrote:
> I think I should remove this assertion so this function would be usable 
> without MS ext, on the other hand it would be a noop without MS ext.
I suggest leaving it in solely because use of the function does impose some 
overhead in the construction of the `std::vector` that is returned. If that 
overhead can be avoided (I guess by passing the container to populate by 
reference as a separate argument and then return either the original `ArrayRef` 
or a new one referencing the populated container), then this could be made a 
no-op and the checks for `MicrosoftExt` at the call sites could be removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153914

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


[PATCH] D156172: [clang][CodeGen] Emit annotations for function declarations.

2023-07-25 Thread Brendan Dahl via Phabricator via cfe-commits
brendandahl added a comment.

That example appears to still work the same with my patch:

  @xxx = global ptr @foo, align 8
  @.str = private unnamed_addr constant [4 x i8] c"bar\00", section 
"llvm.metadata"
  @.str.1 = private unnamed_addr constant [8 x i8] c"main2.c\00", section 
"llvm.metadata"
  @llvm.global.annotations = appending global [1 x { ptr, ptr, ptr, i32, ptr }] 
[{ ptr, ptr, ptr, i32, ptr } { ptr @foo, ptr @.str, ptr @.str.1, i32 3, ptr 
null }], section "llvm.metadata"

I'm not very familiar with the CodeGenModule, so I'm happy to move the call to 
`AddGlobalAnnotations` if there is a better place.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156172

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


[PATCH] D153914: [clang-cl] Enable concatenation of predefined identifiers

2023-07-25 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added a comment.

I think I'm happy with this. I noted two code changes that I think are no 
longer needed and offered some final suggestions on some names.




Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:118-120
+def ext_expand_predef_ms : ExtWarn<
+  "expansion of predefined identifier '%0' to a string literal is a Microsoft 
extension">,
+  InGroup;

For consistency with other names, I'll suggest some alternative names here. I 
think these better reflect the actual diagnostic message.
  - ext_expand_predef_ms -> ext_string_literal_from_predefined
  - MicrosoftConcatPredefined -> MicrosoftStringLiteralFromPredefined



Comment at: clang/include/clang/Basic/TokenKinds.h:22-23
 
+class LangOptions;
+
 namespace tok {

It looks like this change is no longer needed.



Comment at: clang/lib/Basic/TokenKinds.cpp:14-15
 #include "clang/Basic/TokenKinds.h"
+
+#include "clang/Basic/LangOptions.h"
 #include "llvm/Support/ErrorHandling.h"

This change appears to no longer be needed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153914

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


[PATCH] D154007: Reland "Try to implement lambdas with inalloca parameters by forwarding without use of inallocas."

2023-07-25 Thread Reid Kleckner via Phabricator via cfe-commits
rnk accepted this revision.
rnk added a comment.
This revision is now accepted and ready to land.

lgtm




Comment at: clang/lib/CodeGen/CGClass.cpp:3094
+  // reason the name doesn't look as expected then just tack __impl to the
+  // front.
+  StringRef CallOpName = CallOpFn->getName();

Please add a TODO comment, suggestion:
`// TODO: Use the name mangler to produce the right name instead of using 
string replacement.`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154007

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


[PATCH] D155524: [-Wunsafe-buffer-usage] Ignore the FixableGadgets that will not be fixed at an earlier stage

2023-07-25 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.

LGTM, thanks!!




Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:1095-1102
   // Gadgets "claim" variables they're responsible for. Once this loop 
finishes,
   // the tracker will only track DREs that weren't claimed by any gadgets,
   // i.e. not understood by the analysis.
   for (const auto  : CB.FixableGadgets) {
 for (const auto *DRE : G->getClaimedVarUseSites()) {
   CB.Tracker.claimUse(DRE);
 }

ziqingluo-90 wrote:
> NoQ wrote:
> > Let's also skip this part when there are no warning gadgets? Your initial 
> > patch was clearing the `FixableGadgets` list so it was naturally skipped, 
> > but now it's active again.
> Oh, I intentionally chose not to skip it:
>  - 1. To keep the `Tracker` consistent with `CB.FixableGadgets` in case in 
> the future we want to use these two objects even if there is no 
> `WarningGadget`; 
>  - 2. The `findGadgets` function can stay as straightforward as its name 
> suggests.  It doesn't have to know the specific optimization for empty 
> `WarningGadget`s.
> 
> But the two thoughts above probably aren't important enough.  I will change 
> it back to skipping the loop when there is no warnings.
> 
> 
Hmm, I agree that this turns into a confusing contract. Maybe move this loop 
out of the function, to the call site, so that it was more obvious that we skip 
it? This would leave the tracker in a mildly inconsistent state at return, so 
the caller will have to make it consistent by doing the claiming, but that's 
arguably less confusing because we clearly communicate that this is an optional 
step. So the function will do exactly what it says it'll do: find gadgets and 
that's it.

Separately, we can probably consider not searching for fixable gadgets at all 
when no warning gadgets are found. This could be a performance improvement, but 
definitely a story for another time.


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

https://reviews.llvm.org/D155524

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


[PATCH] D154007: Reland "Try to implement lambdas with inalloca parameters by forwarding without use of inallocas."

2023-07-25 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 544090.
akhuang added a comment.

go back to previous __impl naming method


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154007

Files:
  clang/include/clang/CodeGen/CGFunctionInfo.h
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGCall.h
  clang/lib/CodeGen/CGClass.cpp
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CodeGenABITypes.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/CodeGenTypes.h
  clang/lib/CodeGen/Targets/X86.cpp
  clang/test/CodeGenCXX/inalloca-lambda.cpp

Index: clang/test/CodeGenCXX/inalloca-lambda.cpp
===
--- clang/test/CodeGenCXX/inalloca-lambda.cpp
+++ clang/test/CodeGenCXX/inalloca-lambda.cpp
@@ -1,11 +1,63 @@
-// RUN: not %clang_cc1 -triple i686-windows-msvc -emit-llvm -o /dev/null %s  2>&1 | FileCheck %s
+// RUN: %clang_cc1 -triple i686-windows-msvc -emit-llvm -o - %s  2>&1 | FileCheck %s
 
-// PR28299
-// CHECK: error: cannot compile this forwarded non-trivially copyable parameter yet
-
-class A {
+struct A {
+  A();
   A(const A &);
+  int x;
 };
-typedef void (*fptr_t)(A);
-fptr_t fn1() { return [](A) {}; }
+void decayToFp(int (*f)(A));
+void test() {
+  auto ld = [](A a) {
+static int calls = 0;
+++calls;
+return a.x + calls;
+  };
+  decayToFp(ld);
+  ld(A{});
+}
+
+// CHECK: define internal x86_thiscallcc noundef i32
+// CHECK-SAME: @"??R@?0??test@@YAXXZ@QBE?A?@@UA@@@Z"
+// CHECK-SAME: (ptr noundef %this, ptr inalloca(<{ %struct.A }>) %[[ARG:.*]])
+// CHECK: %[[V:.*]] = getelementptr inbounds <{ %struct.A }>, ptr %[[ARG]], i32 0, i32 0
+// CHECK: %call = call x86_thiscallcc noundef i32
+// CHECK-SAME: @"?__impl@@?0??test@@YAXXZ@QBE?A?@@UA@@@Z"
+// CHECK-SAME: (ptr noundef %this, ptr noundef %[[V]])
+
+// CHECK: define internal noundef i32
+// CHECK-SAME: @"?__invoke@@?0??test@@YAXXZ@CA?A?@@UA@@@Z"
+// CHECK-SAME: (ptr inalloca(<{ %struct.A }>) %[[ARG:.*]])
+// CHECK: %unused.capture = alloca %class.anon, align 1
+// CHECK: %[[VAR:.*]] = getelementptr inbounds <{ %struct.A }>, ptr %[[ARG]], i32 0, i32 0
+// CHECK: %call = call x86_thiscallcc noundef i32
+// CHECK-SAME: @"?__impl@@?0??test@@YAXXZ@QBE?A?@@UA@@@Z"
+// CHECK-SAME: (ptr noundef %unused.capture, ptr noundef %[[VAR]])
+// CHECK: ret i32 %call
+
+// CHECK: define internal x86_thiscallcc noundef i32
+// CHECK-SAME: @"?__impl@@?0??test@@YAXXZ@QBE?A?@@UA@@@Z"
+// CHECK-SAME: (ptr noundef %this, ptr noundef %[[ARG:.*]])
+// CHECK: %this.addr = alloca ptr, align 4
+// CHECK: store ptr %this, ptr %this.addr, align 4
+// CHECK: %this1 = load ptr, ptr %this.addr, align 4
+// CHECK: %{{.*}} = load i32, ptr @"?calls@?1???R
+// CHECK: %inc = add nsw i32 %{{.*}}, 1
+// CHECK: store i32 %inc, ptr @"?calls@?1???R
+// CHECK: %{{.*}} = getelementptr inbounds %struct.A, ptr %{{.*}}, i32 0, i32 0
+// CHECK: %{{.*}} = load i32, ptr %{{.*}}, align 4
+// CHECK: %{{.*}} = load i32, ptr @"?calls@?1???R
+// CHECK: %add = add nsw i32 %{{.*}}, %{{.*}}
+// CHECK: ret i32 %add
+
+// Make sure we don't try to copy an uncopyable type.
+struct B {
+  B();
+  B(B &);
+  void operator=(B);
+  long long x;
+} b;
+
+void f() {
+  [](B) {}(b);
+}
 
Index: clang/lib/CodeGen/Targets/X86.cpp
===
--- clang/lib/CodeGen/Targets/X86.cpp
+++ clang/lib/CodeGen/Targets/X86.cpp
@@ -140,7 +140,8 @@
 
   Class classify(QualType Ty) const;
   ABIArgInfo classifyReturnType(QualType RetTy, CCState ) const;
-  ABIArgInfo classifyArgumentType(QualType RetTy, CCState ) const;
+  ABIArgInfo classifyArgumentType(QualType RetTy, CCState ,
+  bool isDelegateCall) const;
 
   /// Updates the number of available free registers, returns
   /// true if any registers were allocated.
@@ -737,8 +738,8 @@
   }
 }
 
-ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
-   CCState ) const {
+ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState ,
+   bool isDelegateCall) const {
   // FIXME: Set alignment on indirect arguments.
   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
@@ -753,6 +754,12 @@
 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
 if (RAA == CGCXXABI::RAA_Indirect) {
   return getIndirectResult(Ty, false, State);
+} else if (isDelegateCall) {
+  // Avoid having different alignments on delegate call args by always
+  // setting the alignment to 4, which is what we do for inallocas.
+  ABIArgInfo Res = getIndirectResult(Ty, false, State);
+  Res.setIndirectAlign(CharUnits::fromQuantity(4));
+  return Res;
 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
   // The field 

[PATCH] D156259: Fix a bug that erroneously placed function arguments on a new line despite all arguments being able to fit on the same line.

2023-07-25 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/lib/Format/ContinuationIndenter.cpp:263
   State.StartOfStringLiteral = 0;
+  State.NoLineBreak = false;
   State.StartOfLineLevel = 0;

Was this uninitialized?



Comment at: clang/lib/Format/ContinuationIndenter.cpp:657
 
+  bool DisallowLineBreaksOnThisLine = ([ = this->Style, ] {
+// Deal with lambda arguments in C++. The aim here is to ensure that we

Can drop outer parens.



Comment at: clang/lib/Format/ContinuationIndenter.cpp:664-666
+if ((Style.Language == FormatStyle::LK_Cpp ||
+ Style.Language == FormatStyle::LK_ObjC) &&
+!Current.is(tok::comment) && PrevNonComment &&

Could move this out of the lambda.



Comment at: clang/lib/Format/ContinuationIndenter.cpp:669
+PrevNonComment->BlockParameterCount > 0 &&
+!Current.isOneOf(tok::l_paren, TT_LambdaLSquare)) {
+  if (PrevNonComment->BlockParameterCount > 1)

This can be merged with `!Current.is(tok::comment)`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156259

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


[PATCH] D153914: [clang-cl] Enable concatenation of predefined identifiers

2023-07-25 Thread Richard Dzenis via Phabricator via cfe-commits
RIscRIpt added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:1981
+  // parsed yet).
+  assert(getLangOpts().MicrosoftExt);
+

I think I should remove this assertion so this function would be usable without 
MS ext, on the other hand it would be a noop without MS ext.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153914

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


[PATCH] D153914: [clang-cl] Enable concatenation of predefined identifiers

2023-07-25 Thread Richard Dzenis via Phabricator via cfe-commits
RIscRIpt updated this revision to Diff 544088.
RIscRIpt added a comment.

Removed irrelevant changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153914

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Lex/LiteralSupport.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Lex/LiteralSupport.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/ms_predefined_expr.cpp
  clang/test/Sema/ms_wide_predefined_expr.cpp

Index: clang/test/Sema/ms_wide_predefined_expr.cpp
===
--- clang/test/Sema/ms_wide_predefined_expr.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-// RUN: %clang_cc1 %s -fsyntax-only -Wno-unused-value -Wmicrosoft -verify -fms-extensions
-// expected-no-diagnostics
-
-// Wide character predefined identifiers
-#define _STR2WSTR(str) L##str
-#define STR2WSTR(str) _STR2WSTR(str)
-void abcdefghi12(void) {
- const wchar_t (*ss)[12] = (__FUNCTION__);
- static int arr[sizeof(STR2WSTR(__FUNCTION__))==12*sizeof(wchar_t) ? 1 : -1];
- const wchar_t (*ss2)[31] = (__FUNCSIG__);
- static int arr2[sizeof(STR2WSTR(__FUNCSIG__))==31*sizeof(wchar_t) ? 1 : -1];
-}
-
-namespace PR13206 {
-void foo(const wchar_t *);
-
-template class A {
-public:
- void method() {
-  foo(L__FUNCTION__);
- }
-};
-
-void bar() {
- A x;
- x.method();
-}
-}
Index: clang/test/Sema/ms_predefined_expr.cpp
===
--- clang/test/Sema/ms_predefined_expr.cpp
+++ clang/test/Sema/ms_predefined_expr.cpp
@@ -1,9 +1,170 @@
 // RUN: %clang_cc1 %s -fsyntax-only -Wmicrosoft -verify -fms-extensions
 
-void f() {
+using size_t = __SIZE_TYPE__;
+
+// Test array initialization
+void array_init() {
  const char a[] = __FUNCTION__; // expected-warning{{initializing an array from a '__FUNCTION__' predefined identifier is a Microsoft extension}}
  const char b[] = __FUNCDNAME__; // expected-warning{{initializing an array from a '__FUNCDNAME__' predefined identifier is a Microsoft extension}}
  const char c[] = __FUNCSIG__; // expected-warning{{initializing an array from a '__FUNCSIG__' predefined identifier is a Microsoft extension}}
  const char d[] = __func__; // expected-warning{{initializing an array from a '__func__' predefined identifier is a Microsoft extension}}
  const char e[] = __PRETTY_FUNCTION__; // expected-warning{{initializing an array from a '__PRETTY_FUNCTION__' predefined identifier is a Microsoft extension}}
+ const wchar_t f[] = L__FUNCTION__; // expected-warning{{initializing an array from a 'L__FUNCTION__' predefined identifier is a Microsoft extension}}
+ const wchar_t g[] = L__FUNCSIG__; // expected-warning{{initializing an array from a 'L__FUNCSIG__' predefined identifier is a Microsoft extension}}
+}
+
+// Test function local identifiers outside of a function
+const char* g_function = __FUNCTION__;// expected-warning{{predefined identifier is only valid inside function}}
+const char* g_function_lconcat = "" __FUNCTION__; // expected-warning{{predefined identifier is only valid inside function}} \
+  // expected-warning{{expansion of predefined identifier '__FUNCTION__' to a string literal is a Microsoft extension}}
+const char* g_function_rconcat = __FUNCTION__ ""; // expected-warning{{predefined identifier is only valid inside function}} \
+  // expected-warning{{expansion of predefined identifier '__FUNCTION__' to a string literal is a Microsoft extension}}
+
+namespace NS
+{
+  const char* function = __FUNCTION__;// expected-warning{{predefined identifier is only valid inside function}}
+  const char* function_lconcat = "" __FUNCTION__; // expected-warning{{predefined identifier is only valid inside function}} \
+  // expected-warning{{expansion of predefined identifier '__FUNCTION__' to a string literal is a Microsoft extension}}
+  const char* function_rconcat = __FUNCTION__ ""; // expected-warning{{predefined identifier is only valid inside function}} \
+  // expected-warning{{expansion of predefined identifier '__FUNCTION__' to a string literal is a Microsoft extension}}
+
+  struct S
+  {
+static constexpr const char* function = __FUNCTION__;// expected-warning{{predefined identifier is only valid inside function}}
+static constexpr const char* function_lconcat = "" __FUNCTION__; // expected-warning{{predefined identifier is only valid inside function}} \
+ // expected-warning{{expansion of predefined identifier '__FUNCTION__' to a string literal is a Microsoft 

[PATCH] D154007: Reland "Try to implement lambdas with inalloca parameters by forwarding without use of inallocas."

2023-07-25 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added inline comments.



Comment at: clang/lib/CodeGen/CGClass.cpp:3095
+  StringRef CallOpName = CallOpFn->getName();
+  std::string ImplName = ("__impl" + CallOpName).str();
+

akhuang wrote:
> rnk wrote:
> > akhuang wrote:
> > > The old code tried to find the "" part of the function name and 
> > > replace the front with "?__impl@", so that the function name was 
> > > consistent with the mangling scheme.  But apparently there are some cases 
> > > where when the function name is too long, it uses a hash instead (?), so 
> > > the attempt to find the  was failing. 
> > > 
> > > I couldn't find a good way to name this function through the actual 
> > > mangling code -- is it fine to just add "__impl" to the front and have it 
> > > not be mangled correctly? 
> > Let me suggest one more thing to try here to convince the mangler to do our 
> > work for us. You can create a CXXMethodDecl AST node here in CodeGen, and 
> > ask the mangler to mangle it for you. If you search CodeGen, you can find 
> > other examples of this, notably, for making implicit `this` variable 
> > declarations:
> > ```
> > $ git grep Decl::Create'(' ../clang/lib/CodeGen/
> > ../clang/lib/CodeGen/CGBuiltin.cpp:  
> > Args.push_back(ImplicitParamDecl::Create(
> > ../clang/lib/CodeGen/CGBuiltin.cpp:
> > Args.push_back(ImplicitParamDecl::Create(
> > ../clang/lib/CodeGen/CGCXXABI.cpp:  auto *ThisDecl = 
> > ImplicitParamDecl::Create(
> > ```
> > 
> > Call `CXXMethodDecl::Create`, and copy in all of the attribute from the 
> > call operator, but replace the DeclarationNameInfo with an IdentifierInfo 
> > of `__impl`.
> > 
> > If that's not working out, let's land this as is and follow up on fixing 
> > the mangling.
> I think `CXXMethodDecl::Create` doesn't work because it needs a non-const 
> CXXRecordDecl to construct? 
> 
> I added some functions to MicrosoftMangler so that we can pass in a custom 
> DeclarationName, does that seem ok? 
I think we should go back to the last approach you had with the string 
substution, and then we can start a new code review where we consider the two 
alternative approaches. I see lots of examples of `const_cast` in the codebase, 
but maybe the custom name approach is better. Hard to say. Either way, it will 
be easier to resolve the question in a smaller code review. Sorry for the back 
and forth.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154007

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


[PATCH] D156192: [-Wunsafe-buffer-usage] Stop generating incorrect fix-its for variable declarations with unsupported specifiers

2023-07-25 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

LGTM!

Yeah I agree that we can eventually support a lot of these incrementally, but 
it's great to establish a safe baseline first.

> If there are other specifiers involved, they may be accidentally removed 
> (e.g., fix `int [[some_type_attribute]] a[]` to `std::span` a is 
> incorrect).

Note that your patch doesn't actually address //type// attributes, only 
//declaration// attributes.

I'd love to learn if we handle type attributes like `int *_Nonnull` and `int 
*_Nonnull *_Nonnull` correctly. How do we even handle that correctly? This is 
no longer about preserving the attribute, it's about the very ability to put 
the same attribute on a `span` itself or on its template parameter. And in case 
of `_Nonnull` it doesn't sound like we have anything like that: there is no 
standard container that acts like `span` but is never null (and even if there 
was, that's not what `_Nonnull` really means), and we probably also can't do 
`span` because that's actually the same type as `span` 
(https://godbolt.org/z/oehTMbvrz).

So it's likely that we have to give up on unsupported type attributes very 
early, even before the fixit stage. Maybe on `hasPointerType()` stage; in such 
cases we aren't even sure that's a pointer, what if it's like an `int 
*__attribute__((vector_size(8)))`? (This actually can't happen; you can't have 
vectors of pointers. But something similar totally could.)

> So both `const static int * x` and `static const int * x` will be fixed to 
> `static std::span x`.

Ugh, `const static int` sounds awful because `const`applies to the //pointee//, 
`static` applies to the //pointer//, then `int` applies to the //pointee// 
again. I hope we'll never see such code, but it's great that it works correctly!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156192

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


[PATCH] D156128: [Clang][AArch64] Fix up immediate range of f64f64 mopa/mops intrinsics

2023-07-25 Thread Bryan Chan via Phabricator via cfe-commits
bryanpkc accepted this revision.
bryanpkc added a comment.
This revision is now accepted and ready to land.

Thanks for the catch!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156128

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


[PATCH] D156185: [clang][ConstExprEmitter] handle ArrayToPointerDecay ImplicitCastExpr of StringLiterals

2023-07-25 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

No, that's taking the address of a string literal lvalue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156185

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


[PATCH] D155526: [-Wunsafe-buffer-usage] Fix a fallthrough case in UPCStandalonePointer getFixits

2023-07-25 Thread Rashmi Mudduluru via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG070358ec9235: [-Wunsafe-buffer-usage] Fix a fallthrough case 
in UPCStandalonePointer getFixits (authored by t-rasmud).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D155526?vs=543700=544087#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155526

Files:
  clang/lib/Analysis/UnsafeBufferUsage.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-test-unreachable.cpp


Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-test-unreachable.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-test-unreachable.cpp
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -std=c++20 -Wunsafe-buffer-usage 
-fsafe-buffer-usage-suggestions -verify %s
+
+// expected-no-diagnostics
+
+typedef unsigned __darwin_size_t;
+typedef __darwin_size_t size_t;
+ #define bzero(s, n) __builtin_bzero(s, n)
+void __nosan_bzero(void *dst, size_t sz) { bzero(dst, sz); }
Index: clang/lib/Analysis/UnsafeBufferUsage.cpp
===
--- clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -1512,8 +1512,8 @@
 FixItHint::CreateInsertion(
 (*EndOfOperand).getLocWithOffset(1), "[0]")}};
 }
+break;
   }
-[[fallthrough]];
   case Strategy::Kind::Iterator:
   case Strategy::Kind::Array:
   case Strategy::Kind::Vector:
@@ -1541,8 +1541,9 @@
   if (EndOfOperand)
 return FixItList{{FixItHint::CreateInsertion(
 *EndOfOperand, ".data()")}};
+  // FIXME: Points inside a macro expansion.
+  break;
 }
-  [[fallthrough]];
 case Strategy::Kind::Wontfix:
 case Strategy::Kind::Iterator:
 case Strategy::Kind::Array:


Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-test-unreachable.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-test-unreachable.cpp
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -std=c++20 -Wunsafe-buffer-usage -fsafe-buffer-usage-suggestions -verify %s
+
+// expected-no-diagnostics
+
+typedef unsigned __darwin_size_t;
+typedef __darwin_size_t size_t;
+ #define bzero(s, n) __builtin_bzero(s, n)
+void __nosan_bzero(void *dst, size_t sz) { bzero(dst, sz); }
Index: clang/lib/Analysis/UnsafeBufferUsage.cpp
===
--- clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -1512,8 +1512,8 @@
 FixItHint::CreateInsertion(
 (*EndOfOperand).getLocWithOffset(1), "[0]")}};
 }
+break;
   }
-[[fallthrough]];
   case Strategy::Kind::Iterator:
   case Strategy::Kind::Array:
   case Strategy::Kind::Vector:
@@ -1541,8 +1541,9 @@
   if (EndOfOperand)
 return FixItList{{FixItHint::CreateInsertion(
 *EndOfOperand, ".data()")}};
+  // FIXME: Points inside a macro expansion.
+  break;
 }
-  [[fallthrough]];
 case Strategy::Kind::Wontfix:
 case Strategy::Kind::Iterator:
 case Strategy::Kind::Array:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 070358e - [-Wunsafe-buffer-usage] Fix a fallthrough case in UPCStandalonePointer getFixits

2023-07-25 Thread Rashmi Mudduluru via cfe-commits

Author: Rashmi Mudduluru
Date: 2023-07-25T13:40:33-07:00
New Revision: 070358ec92350c13b0b6c60fbb03bf35a7a00251

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

LOG: [-Wunsafe-buffer-usage] Fix a fallthrough case in UPCStandalonePointer 
getFixits

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

Added: 
clang/test/SemaCXX/warn-unsafe-buffer-usage-test-unreachable.cpp

Modified: 
clang/lib/Analysis/UnsafeBufferUsage.cpp

Removed: 




diff  --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 5cde60cefdf065..78f180447eef6f 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -1512,8 +1512,8 @@ PointerDereferenceGadget::getFixits(const Strategy ) 
const {
 FixItHint::CreateInsertion(
 (*EndOfOperand).getLocWithOffset(1), "[0]")}};
 }
+break;
   }
-[[fallthrough]];
   case Strategy::Kind::Iterator:
   case Strategy::Kind::Array:
   case Strategy::Kind::Vector:
@@ -1541,8 +1541,9 @@ std::optional 
UPCStandalonePointerGadget::getFixits(const Strategy 
   if (EndOfOperand)
 return FixItList{{FixItHint::CreateInsertion(
 *EndOfOperand, ".data()")}};
+  // FIXME: Points inside a macro expansion.
+  break;
 }
-  [[fallthrough]];
 case Strategy::Kind::Wontfix:
 case Strategy::Kind::Iterator:
 case Strategy::Kind::Array:

diff  --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-test-unreachable.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-test-unreachable.cpp
new file mode 100644
index 00..844311c3a51a58
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-test-unreachable.cpp
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -std=c++20 -Wunsafe-buffer-usage 
-fsafe-buffer-usage-suggestions -verify %s
+
+// expected-no-diagnostics
+
+typedef unsigned __darwin_size_t;
+typedef __darwin_size_t size_t;
+ #define bzero(s, n) __builtin_bzero(s, n)
+void __nosan_bzero(void *dst, size_t sz) { bzero(dst, sz); }



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


[PATCH] D154007: Reland "Try to implement lambdas with inalloca parameters by forwarding without use of inallocas."

2023-07-25 Thread Amy Huang via Phabricator via cfe-commits
akhuang added inline comments.



Comment at: clang/lib/CodeGen/CGClass.cpp:3095
+  StringRef CallOpName = CallOpFn->getName();
+  std::string ImplName = ("__impl" + CallOpName).str();
+

rnk wrote:
> akhuang wrote:
> > The old code tried to find the "" part of the function name and 
> > replace the front with "?__impl@", so that the function name was consistent 
> > with the mangling scheme.  But apparently there are some cases where when 
> > the function name is too long, it uses a hash instead (?), so the attempt 
> > to find the  was failing. 
> > 
> > I couldn't find a good way to name this function through the actual 
> > mangling code -- is it fine to just add "__impl" to the front and have it 
> > not be mangled correctly? 
> Let me suggest one more thing to try here to convince the mangler to do our 
> work for us. You can create a CXXMethodDecl AST node here in CodeGen, and ask 
> the mangler to mangle it for you. If you search CodeGen, you can find other 
> examples of this, notably, for making implicit `this` variable declarations:
> ```
> $ git grep Decl::Create'(' ../clang/lib/CodeGen/
> ../clang/lib/CodeGen/CGBuiltin.cpp:  Args.push_back(ImplicitParamDecl::Create(
> ../clang/lib/CodeGen/CGBuiltin.cpp:
> Args.push_back(ImplicitParamDecl::Create(
> ../clang/lib/CodeGen/CGCXXABI.cpp:  auto *ThisDecl = 
> ImplicitParamDecl::Create(
> ```
> 
> Call `CXXMethodDecl::Create`, and copy in all of the attribute from the call 
> operator, but replace the DeclarationNameInfo with an IdentifierInfo of 
> `__impl`.
> 
> If that's not working out, let's land this as is and follow up on fixing the 
> mangling.
I think `CXXMethodDecl::Create` doesn't work because it needs a non-const 
CXXRecordDecl to construct? 

I added some functions to MicrosoftMangler so that we can pass in a custom 
DeclarationName, does that seem ok? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154007

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


[PATCH] D154007: Reland "Try to implement lambdas with inalloca parameters by forwarding without use of inallocas."

2023-07-25 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 544086.
akhuang added a comment.

Add some functions to MicrosoftMangle so we can pass in a custom function name.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154007

Files:
  clang/include/clang/AST/Mangle.h
  clang/include/clang/CodeGen/CGFunctionInfo.h
  clang/lib/AST/MicrosoftMangle.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGCall.h
  clang/lib/CodeGen/CGClass.cpp
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CodeGenABITypes.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/CodeGenTypes.h
  clang/lib/CodeGen/Targets/X86.cpp
  clang/test/CodeGenCXX/inalloca-lambda.cpp

Index: clang/test/CodeGenCXX/inalloca-lambda.cpp
===
--- clang/test/CodeGenCXX/inalloca-lambda.cpp
+++ clang/test/CodeGenCXX/inalloca-lambda.cpp
@@ -1,11 +1,63 @@
-// RUN: not %clang_cc1 -triple i686-windows-msvc -emit-llvm -o /dev/null %s  2>&1 | FileCheck %s
+// RUN: %clang_cc1 -triple i686-windows-msvc -emit-llvm -o - %s  2>&1 | FileCheck %s
 
-// PR28299
-// CHECK: error: cannot compile this forwarded non-trivially copyable parameter yet
-
-class A {
+struct A {
+  A();
   A(const A &);
+  int x;
 };
-typedef void (*fptr_t)(A);
-fptr_t fn1() { return [](A) {}; }
+void decayToFp(int (*f)(A));
+void test() {
+  auto ld = [](A a) {
+static int calls = 0;
+++calls;
+return a.x + calls;
+  };
+  decayToFp(ld);
+  ld(A{});
+}
+
+// CHECK: define internal x86_thiscallcc noundef i32
+// CHECK-SAME: @"??R@?0??test@@YAXXZ@QBE?A?@@UA@@@Z"
+// CHECK-SAME: (ptr noundef %this, ptr inalloca(<{ %struct.A }>) %[[ARG:.*]])
+// CHECK: %[[V:.*]] = getelementptr inbounds <{ %struct.A }>, ptr %[[ARG]], i32 0, i32 0
+// CHECK: %call = call x86_thiscallcc noundef i32
+// CHECK-SAME: @"?__impl@@?0??test@@YAXXZ@QBE?A?@@UA@@@Z"
+// CHECK-SAME: (ptr noundef %this, ptr noundef %[[V]])
+
+// CHECK: define internal noundef i32
+// CHECK-SAME: @"?__invoke@@?0??test@@YAXXZ@CA?A?@@UA@@@Z"
+// CHECK-SAME: (ptr inalloca(<{ %struct.A }>) %[[ARG:.*]])
+// CHECK: %unused.capture = alloca %class.anon, align 1
+// CHECK: %[[VAR:.*]] = getelementptr inbounds <{ %struct.A }>, ptr %[[ARG]], i32 0, i32 0
+// CHECK: %call = call x86_thiscallcc noundef i32
+// CHECK-SAME: @"?__impl@@?0??test@@YAXXZ@QBE?A?@@UA@@@Z"
+// CHECK-SAME: (ptr noundef %unused.capture, ptr noundef %[[VAR]])
+// CHECK: ret i32 %call
+
+// CHECK: define internal x86_thiscallcc noundef i32
+// CHECK-SAME: @"?__impl@@?0??test@@YAXXZ@QBE?A?@@UA@@@Z"
+// CHECK-SAME: (ptr noundef %this, ptr noundef %[[ARG:.*]])
+// CHECK: %this.addr = alloca ptr, align 4
+// CHECK: store ptr %this, ptr %this.addr, align 4
+// CHECK: %this1 = load ptr, ptr %this.addr, align 4
+// CHECK: %{{.*}} = load i32, ptr @"?calls@?1???R
+// CHECK: %inc = add nsw i32 %{{.*}}, 1
+// CHECK: store i32 %inc, ptr @"?calls@?1???R
+// CHECK: %{{.*}} = getelementptr inbounds %struct.A, ptr %{{.*}}, i32 0, i32 0
+// CHECK: %{{.*}} = load i32, ptr %{{.*}}, align 4
+// CHECK: %{{.*}} = load i32, ptr @"?calls@?1???R
+// CHECK: %add = add nsw i32 %{{.*}}, %{{.*}}
+// CHECK: ret i32 %add
+
+// Make sure we don't try to copy an uncopyable type.
+struct B {
+  B();
+  B(B &);
+  void operator=(B);
+  long long x;
+} b;
+
+void f() {
+  [](B) {}(b);
+}
 
Index: clang/lib/CodeGen/Targets/X86.cpp
===
--- clang/lib/CodeGen/Targets/X86.cpp
+++ clang/lib/CodeGen/Targets/X86.cpp
@@ -140,7 +140,8 @@
 
   Class classify(QualType Ty) const;
   ABIArgInfo classifyReturnType(QualType RetTy, CCState ) const;
-  ABIArgInfo classifyArgumentType(QualType RetTy, CCState ) const;
+  ABIArgInfo classifyArgumentType(QualType RetTy, CCState ,
+  bool isDelegateCall) const;
 
   /// Updates the number of available free registers, returns
   /// true if any registers were allocated.
@@ -737,8 +738,8 @@
   }
 }
 
-ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
-   CCState ) const {
+ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, CCState ,
+   bool isDelegateCall) const {
   // FIXME: Set alignment on indirect arguments.
   bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
   bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
@@ -753,6 +754,12 @@
 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
 if (RAA == CGCXXABI::RAA_Indirect) {
   return getIndirectResult(Ty, false, State);
+} else if (isDelegateCall) {
+  // Avoid having different alignments on delegate call args by always
+  // setting the alignment to 4, which is what we do for inallocas.
+  ABIArgInfo Res = getIndirectResult(Ty, false, State);
+  

[PATCH] D153914: [clang-cl] Enable concatenation of predefined identifiers

2023-07-25 Thread Richard Dzenis via Phabricator via cfe-commits
RIscRIpt added inline comments.



Comment at: clang/include/clang/Basic/TokenKinds.h:87-93
+/// Return true if this token is a predefined macro
+/// unexpandable by MSVC preprocessor.
+inline bool isUnexpandableMsMacro(TokenKind K) {
+  return K == tok::kw___FUNCTION__ || K == tok::kw___FUNCSIG__ ||
+ K == tok::kw_L__FUNCTION__ || K == tok::kw_L__FUNCSIG__ ||
+ K == tok::kw___FUNCDNAME__;
+}

cor3ntin wrote:
> RIscRIpt wrote:
> > tahonermann wrote:
> > > cor3ntin wrote:
> > > > tahonermann wrote:
> > > > > RIscRIpt wrote:
> > > > > > tahonermann wrote:
> > > > > > > 
> > > > > > Thanks, I like the name. But shouldn't we reflect that we are 
> > > > > > referring to only Microsoft (unexpandable) macros? How about 
> > > > > > `isFunctionLocalPredefinedMsMacro`?
> > > > > I don't think the Microsoft association is meaningful. Sure, some of 
> > > > > the predefined macros are only treated differently when compiling in 
> > > > > Microsoft mode, but some of those macros aren't Microsoft specific. 
> > > > > Also, there might be macros provided by other implementations that 
> > > > > we'll want to emulate some day.
> > > > I think it is, there is currently no way to link 
> > > > `isFunctionLocalPredefinedMacro` to the MS feature. "MSPredefinedMacro" 
> > > > is pretty self explanatory, same reason we most often - but not always 
> > > > - use GNU in the name of function related to GNU extensions.
> > > > There are enough similar-sounding features and extensions that we 
> > > > should try to make it clear which feature we are talking about.
> > > Perhaps we still haven't found the right name then. With the name that 
> > > I've been advocating, this function should also return true for 
> > > `tok::kw___PRETTY_FUNCTION__` even though that macro should not expand to 
> > > something that can be concatenated with other string literals (whether 
> > > compiling in Microsoft mode or not).
> > > 
> > > The Microsoft extension is the localized expansion to a string literal 
> > > that can be concatenated with other string literals. We probably should 
> > > isolate the conditions for that behavior to one place and if we do that, 
> > > then I guess naming this function as specific to Microsoft mode is ok; we 
> > > can always rename it later if it gets used for non-Microsoft extensions.
> > > 
> > > Here is my suggestion then:
> > >   // Return true if the token corresponds to a function local predefined
> > >   // macro that, in Microsoft modes, expands to a string literal (that can
> > >   // then be concatenated with other string literals).
> > >   inline bool isMsFunctionLocalStringLiteralMacro(TokenKind K, const 
> > > LangOptions ) {
> > > return langOpts.MicrosoftExt && (
> > > K == tok::kw___FUNCTION__ || K == tok::kw_L__FUNCTION__ ||
> > > K == tok::kw___FUNCSIG__ || K == tok::kw_L__FUNCSIG__ ||
> > > K == tok::kw___FUNCDNAME__);
> > >   }  
> > > 
> > > This will avoid the need for callers to check for `MicrosoftExt`; that is 
> > > what I really want to avoid since it is easy to forget to do that check.
> > 1. By requiring user to pass `LangOptions` I think we can remove MS 
> > association (implying that there could be other non-msft cases in the 
> > future)
> > 2. We would have to include a `LangOptions.h` in `TokenKinds.h`, are we ok 
> > with this? Alternatively while this function is for msft cases only, we 
> > could pass `bool MicrosoftExt`
> > 
> > Personally, I like version with `LangOptions` and removal of `MS`.
> > By requiring user to pass LangOptions I think we can remove MS association
> 
> I don't think there is any motivation to future proof against hypotheticals, 
> we can always refactor later 
> 
> > We would have to include a LangOptions.h in TokenKinds.h
> 
> This makes me uneasy, but i think we can move the function to 
> `LiteralSupport.h` and include that in `ParseExpr.cpp`.
Sounds good to me. Due to other changes I also moved `TokenIsLikeStringLiteral` 
there.

> I don't think there is any motivation to future proof against hypotheticals, 
> we can always refactor later
Yes, not a strong argument, but I'd like to keep current name if you are not 
against.



Comment at: clang/lib/Sema/SemaExpr.cpp:2010-2013
+OS << "R\"EFLPM("
+   << PredefinedExpr::ComputeName(getPredefinedExprKind(Tok.getKind()),
+  currentDecl)
+   << ")EFLPM\"";

tahonermann wrote:
> cor3ntin wrote:
> > tahonermann wrote:
> > > RIscRIpt wrote:
> > > > tahonermann wrote:
> > > > > "EFLPM"? I'm assuming this is an attempt to avoid an accidental clash 
> > > > > with the computed name. Does this suffice to ensure a clash can't 
> > > > > happen? If not, can we do better? Per 
> > > > > http://eel.is/c++draft/lex.string#nt:r-char and 
> > > > > http://eel.is/c++draft/lex.charset#1, we have a lot of flexibility 
> > > > > regarding which characters to use.
> 

  1   2   3   4   >