[PATCH] D147165: [Windows SEH] Fix catch+return crash for Windows -EHa

2023-03-31 Thread Phoebe Wang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0cc66f3c779b: [Windows SEH] Fix catch+return crash for 
Windows -EHa (authored by pengfei).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147165

Files:
  clang/lib/CodeGen/CGCleanup.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGen/windows-seh-EHa-CppCatchReturn.cpp


Index: clang/test/CodeGen/windows-seh-EHa-CppCatchReturn.cpp
===
--- /dev/null
+++ clang/test/CodeGen/windows-seh-EHa-CppCatchReturn.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -triple x86_64-windows -fasync-exceptions -fcxx-exceptions 
-fexceptions -fms-extensions -x c++ -Wno-implicit-function-declaration -S 
-emit-llvm %s -o - | FileCheck %s
+
+// CHECK: define dso_local void @"?foo@@YAXXZ
+// CHECK: invoke void @llvm.seh.try.begin()
+// CHECK-NOT: llvm.seh.scope.begin
+// CHECK-NOT: llvm.seh.scope.end
+
+// FIXME: Do we actually need llvm.seh.scope*?
+void foo() {
+  try {}
+  catch (...) {
+  return;
+  }
+}
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7666,6 +7666,8 @@
 if (types::isCXX(InputType))
   CmdArgs.push_back("-fcxx-exceptions");
 CmdArgs.push_back("-fexceptions");
+if (EH.Asynch)
+  CmdArgs.push_back("-fasync-exceptions");
   }
   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
 CmdArgs.push_back("-fexternc-nounwind");
Index: clang/lib/CodeGen/CGCleanup.cpp
===
--- clang/lib/CodeGen/CGCleanup.cpp
+++ clang/lib/CodeGen/CGCleanup.cpp
@@ -836,7 +836,7 @@
   EmitBlock(NormalEntry);
 
   // intercept normal cleanup to mark SEH scope end
-  if (IsEHa) {
+  if (IsEHa && getInvokeDest()) {
 if (Personality.isMSVCXXPersonality())
   EmitSehCppScopeEnd();
 else


Index: clang/test/CodeGen/windows-seh-EHa-CppCatchReturn.cpp
===
--- /dev/null
+++ clang/test/CodeGen/windows-seh-EHa-CppCatchReturn.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -triple x86_64-windows -fasync-exceptions -fcxx-exceptions -fexceptions -fms-extensions -x c++ -Wno-implicit-function-declaration -S -emit-llvm %s -o - | FileCheck %s
+
+// CHECK: define dso_local void @"?foo@@YAXXZ
+// CHECK: invoke void @llvm.seh.try.begin()
+// CHECK-NOT: llvm.seh.scope.begin
+// CHECK-NOT: llvm.seh.scope.end
+
+// FIXME: Do we actually need llvm.seh.scope*?
+void foo() {
+  try {}
+  catch (...) {
+  return;
+  }
+}
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7666,6 +7666,8 @@
 if (types::isCXX(InputType))
   CmdArgs.push_back("-fcxx-exceptions");
 CmdArgs.push_back("-fexceptions");
+if (EH.Asynch)
+  CmdArgs.push_back("-fasync-exceptions");
   }
   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
 CmdArgs.push_back("-fexternc-nounwind");
Index: clang/lib/CodeGen/CGCleanup.cpp
===
--- clang/lib/CodeGen/CGCleanup.cpp
+++ clang/lib/CodeGen/CGCleanup.cpp
@@ -836,7 +836,7 @@
   EmitBlock(NormalEntry);
 
   // intercept normal cleanup to mark SEH scope end
-  if (IsEHa) {
+  if (IsEHa && getInvokeDest()) {
 if (Personality.isMSVCXXPersonality())
   EmitSehCppScopeEnd();
 else
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 0cc66f3 - [Windows SEH] Fix catch+return crash for Windows -EHa

2023-03-31 Thread Phoebe Wang via cfe-commits

Author: Phoebe Wang
Date: 2023-04-01T14:53:33+08:00
New Revision: 0cc66f3c779b80a199d692fa84f7ed8d29373d1c

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

LOG: [Windows SEH] Fix catch+return crash for Windows -EHa

This change also turns on -fasync-exceptions by default under -EHa
option due to the backend patch merged.

Reviewed By: LuoYuanke

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

Added: 
clang/test/CodeGen/windows-seh-EHa-CppCatchReturn.cpp

Modified: 
clang/lib/CodeGen/CGCleanup.cpp
clang/lib/Driver/ToolChains/Clang.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGCleanup.cpp b/clang/lib/CodeGen/CGCleanup.cpp
index 43758ac27e439..175d91488efd0 100644
--- a/clang/lib/CodeGen/CGCleanup.cpp
+++ b/clang/lib/CodeGen/CGCleanup.cpp
@@ -836,7 +836,7 @@ void CodeGenFunction::PopCleanupBlock(bool 
FallthroughIsBranchThrough) {
   EmitBlock(NormalEntry);
 
   // intercept normal cleanup to mark SEH scope end
-  if (IsEHa) {
+  if (IsEHa && getInvokeDest()) {
 if (Personality.isMSVCXXPersonality())
   EmitSehCppScopeEnd();
 else

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index f5efcebb3bbd9..1984e1393a15c 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -7666,6 +7666,8 @@ void Clang::AddClangCLArgs(const ArgList &Args, types::ID 
InputType,
 if (types::isCXX(InputType))
   CmdArgs.push_back("-fcxx-exceptions");
 CmdArgs.push_back("-fexceptions");
+if (EH.Asynch)
+  CmdArgs.push_back("-fasync-exceptions");
   }
   if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
 CmdArgs.push_back("-fexternc-nounwind");

diff  --git a/clang/test/CodeGen/windows-seh-EHa-CppCatchReturn.cpp 
b/clang/test/CodeGen/windows-seh-EHa-CppCatchReturn.cpp
new file mode 100644
index 0..a65ab39bea3e4
--- /dev/null
+++ b/clang/test/CodeGen/windows-seh-EHa-CppCatchReturn.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -triple x86_64-windows -fasync-exceptions -fcxx-exceptions 
-fexceptions -fms-extensions -x c++ -Wno-implicit-function-declaration -S 
-emit-llvm %s -o - | FileCheck %s
+
+// CHECK: define dso_local void @"?foo@@YAXXZ
+// CHECK: invoke void @llvm.seh.try.begin()
+// CHECK-NOT: llvm.seh.scope.begin
+// CHECK-NOT: llvm.seh.scope.end
+
+// FIXME: Do we actually need llvm.seh.scope*?
+void foo() {
+  try {}
+  catch (...) {
+  return;
+  }
+}



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


[PATCH] D146376: Update static_assert message for redundant cases

2023-03-31 Thread Krishna Narayanan via Phabricator via cfe-commits
Krishna-13-cyber updated this revision to Diff 510186.
Krishna-13-cyber added a comment.

- Updated diff with `git clang-format HEAD~1`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146376

Files:
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/SemaCXX/static-assert.cpp


Index: clang/test/SemaCXX/static-assert.cpp
===
--- clang/test/SemaCXX/static-assert.cpp
+++ clang/test/SemaCXX/static-assert.cpp
@@ -258,8 +258,14 @@
   constexpr bool invert(bool b) {
 return !b;
   }
+
+  static_assert(invert(true) || invert(true), ""); // expected-error {{failed}}
   static_assert(invert(true) == invert(false), ""); // expected-error 
{{failed}} \
 // expected-note 
{{evaluates to 'false == true'}}
+  static_assert(true && false, ""); // expected-error {{failed}}
+  static_assert(invert(true) || invert(true) || false, ""); // expected-error 
{{failed}}
+  static_assert((true && invert(true)) || false, ""); // expected-error 
{{failed}}
+  static_assert(true && invert(false) && invert(true), ""); // expected-error 
{{failed}}
 
   /// No notes here since we compare a bool expression with a bool literal.
   static_assert(invert(true) == true, ""); // expected-error {{failed}}
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -16715,7 +16715,8 @@
 /// Try to print more useful information about a failed static_assert
 /// with expression \E
 void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
-  if (const auto *Op = dyn_cast(E)) {
+  if (const auto *Op = dyn_cast(E);
+  Op && Op->getOpcode() != BO_LOr) {
 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
 


Index: clang/test/SemaCXX/static-assert.cpp
===
--- clang/test/SemaCXX/static-assert.cpp
+++ clang/test/SemaCXX/static-assert.cpp
@@ -258,8 +258,14 @@
   constexpr bool invert(bool b) {
 return !b;
   }
+
+  static_assert(invert(true) || invert(true), ""); // expected-error {{failed}}
   static_assert(invert(true) == invert(false), ""); // expected-error {{failed}} \
 // expected-note {{evaluates to 'false == true'}}
+  static_assert(true && false, ""); // expected-error {{failed}}
+  static_assert(invert(true) || invert(true) || false, ""); // expected-error {{failed}}
+  static_assert((true && invert(true)) || false, ""); // expected-error {{failed}}
+  static_assert(true && invert(false) && invert(true), ""); // expected-error {{failed}}
 
   /// No notes here since we compare a bool expression with a bool literal.
   static_assert(invert(true) == true, ""); // expected-error {{failed}}
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -16715,7 +16715,8 @@
 /// Try to print more useful information about a failed static_assert
 /// with expression \E
 void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
-  if (const auto *Op = dyn_cast(E)) {
+  if (const auto *Op = dyn_cast(E);
+  Op && Op->getOpcode() != BO_LOr) {
 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D147369: [clang][Interp] Support empty initlist initializers for complex types

2023-03-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaron.ballman, erichkeane, tahonermann, shafik.
Herald added a project: All.
tbaeder 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/D147369

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


Index: clang/test/AST/Interp/complex.cpp
===
--- clang/test/AST/Interp/complex.cpp
+++ clang/test/AST/Interp/complex.cpp
@@ -29,5 +29,28 @@
 static_assert(__imag(I1) == 2, "");
 
 
+constexpr _Complex double D1 = {};
+static_assert(__real(D1) == 0, "");
+static_assert(__imag(D1) == 0, "");
+
+constexpr _Complex int I2 = {};
+static_assert(__real(I2) == 0, "");
+static_assert(__imag(I2) == 0, "");
+
+
+#if 0
+/// FIXME: This should work in the new interpreter.
+constexpr _Complex double D2 = {12};
+static_assert(__real(D2) == 12, "");
+static_assert(__imag(D2) == 12, "");
+
+constexpr _Complex int I3 = {15};
+static_assert(__real(I3) == 15, "");
+static_assert(__imag(I3) == 15, "");
+#endif
+
+
+
+
 /// FIXME: This should work in the new interpreter as well.
 // constexpr _Complex _BitInt(8) A = 0;// = {4};
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1563,19 +1563,35 @@
 template 
 bool ByteCodeExprGen::visitComplexInitializer(
 const Expr *Initializer) {
+  assert(Initializer->getType()->isAnyComplexType());
   if (const auto *InitList = dyn_cast(Initializer)) {
-unsigned InitIndex = 0;
-for (const Expr *Init : InitList->inits()) {
-  PrimType InitT = classifyPrim(Init->getType());
-
-  if (!this->visit(Init))
-return false;
+unsigned NumInits = InitList->getNumInits();
+QualType ElemQT =
+InitList->getType()->getAs()->getElementType();
+PrimType ElemT = classifyPrim(ElemQT);
+
+// FIXME: Initlists with one element contain a
+//   FloatingRealToComplex cast, not a single floating type.
+
+if (NumInits == 0) {
+  // Zero-initialize both elements.
+  for (unsigned I = 0; I < 2; ++I) {
+if (!this->visitZeroInitializer(ElemQT, InitList))
+  return false;
+if (!this->emitInitElem(ElemT, I, InitList))
+  return false;
+  }
+} else if (NumInits == 2) {
+  unsigned InitIndex = 0;
+  for (const Expr *Init : InitList->inits()) {
+if (!this->visit(Init))
+  return false;
 
-  if (!this->emitInitElem(InitT, InitIndex, InitList))
-return false;
-  ++InitIndex;
+if (!this->emitInitElem(ElemT, InitIndex, InitList))
+  return false;
+++InitIndex;
+  }
 }
-assert(InitIndex == 2);
 return true;
   } else if (const auto *CE = dyn_cast(Initializer)) {
 if (!this->emitDupPtr(Initializer))


Index: clang/test/AST/Interp/complex.cpp
===
--- clang/test/AST/Interp/complex.cpp
+++ clang/test/AST/Interp/complex.cpp
@@ -29,5 +29,28 @@
 static_assert(__imag(I1) == 2, "");
 
 
+constexpr _Complex double D1 = {};
+static_assert(__real(D1) == 0, "");
+static_assert(__imag(D1) == 0, "");
+
+constexpr _Complex int I2 = {};
+static_assert(__real(I2) == 0, "");
+static_assert(__imag(I2) == 0, "");
+
+
+#if 0
+/// FIXME: This should work in the new interpreter.
+constexpr _Complex double D2 = {12};
+static_assert(__real(D2) == 12, "");
+static_assert(__imag(D2) == 12, "");
+
+constexpr _Complex int I3 = {15};
+static_assert(__real(I3) == 15, "");
+static_assert(__imag(I3) == 15, "");
+#endif
+
+
+
+
 /// FIXME: This should work in the new interpreter as well.
 // constexpr _Complex _BitInt(8) A = 0;// = {4};
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1563,19 +1563,35 @@
 template 
 bool ByteCodeExprGen::visitComplexInitializer(
 const Expr *Initializer) {
+  assert(Initializer->getType()->isAnyComplexType());
   if (const auto *InitList = dyn_cast(Initializer)) {
-unsigned InitIndex = 0;
-for (const Expr *Init : InitList->inits()) {
-  PrimType InitT = classifyPrim(Init->getType());
-
-  if (!this->visit(Init))
-return false;
+unsigned NumInits = InitList->getNumInits();
+QualType ElemQT =
+InitList->getType()->getAs()->getElementType();
+PrimType ElemT = classifyPrim(ElemQT);
+
+// FIXME: Initlists with one element contain a
+//   FloatingRealToComplex cast, not a single floating type.
+
+if (NumInits == 0) {
+  // Zero-initialize both elements.
+  for (unsigned I = 0; I < 2; ++I) {
+if (!this->visitZeroInitializer(ElemQT, In

[PATCH] D141497: [clang][Interp] Record initialization via conditional operator

2023-03-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 510180.
tbaeder added a comment.

Screw it, just use a `llvm::function_ref`.


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

https://reviews.llvm.org/D141497

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/test/AST/Interp/constexpr-nqueens.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
@@ -343,3 +343,14 @@
   constexpr piecewise_construct_t piecewise_construct =
 piecewise_construct_t();
 };
+
+namespace ConditionalInit {
+  struct S { int a; };
+
+  constexpr S getS(bool b) {
+return b ? S{12} : S{13};
+  }
+
+  static_assert(getS(true).a == 12, "");
+  static_assert(getS(false).a == 13, "");
+};
Index: clang/test/AST/Interp/constexpr-nqueens.cpp
===
--- clang/test/AST/Interp/constexpr-nqueens.cpp
+++ clang/test/AST/Interp/constexpr-nqueens.cpp
@@ -17,7 +17,8 @@
   constexpr Board(uint64_t State, bool Failed = false) :
 Failed(Failed) {}
   constexpr Board addQueen(int Row, int Col) const {
-return Board(State | ((uint64_t)Row << (Col * 4))); // ref-note {{read of uninitialized object}}
+return Board(State | ((uint64_t)Row << (Col * 4))); // ref-note {{read of uninitialized object}} \
+// expected-note {{read of object outside its lifetime}}
   }
   constexpr int getQueenRow(int Col) const {
 return (State >> (Col * 4)) & 0xf;
@@ -47,17 +48,22 @@
 constexpr Board buildBoardScan(int N, int Col, int Row, const Board &B) {
   return Row == N ? Board(0, true) :
  B.ok(Row, Col) ?
- tryBoard(buildBoardRecurse(N, Col + 1, B.addQueen(Row, Col)), // ref-note {{in call to '&Board()->addQueen(0, 0)}}
+ tryBoard(buildBoardRecurse(N, Col + 1, B.addQueen(Row, Col)), // ref-note {{in call to '&Board()->addQueen(0, 0)}} \
+   // expected-note {{in call to '&Board()->addQueen(0, 0)}}
   N, Col, Row+1, B) :
  buildBoardScan(N, Col, Row + 1, B);
 }
 constexpr Board buildBoardRecurse(int N, int Col, const Board &B) {
-  return Col == N ? B : buildBoardScan(N, Col, 0, B); // ref-note {{in call to 'buildBoardScan(8, 0, 0, Board())'}}
+  return Col == N ? B : buildBoardScan(N, Col, 0, B); // ref-note {{in call to 'buildBoardScan(8, 0, 0, Board())'}} \
+  // expected-note {{in call to 'buildBoardScan(8, 0, 0, Board())'}}
+
 }
 constexpr Board buildBoard(int N) {
-  return buildBoardRecurse(N, 0, Board()); // ref-note {{in call to 'buildBoardRecurse(8, 0, Board())'}}
+  return buildBoardRecurse(N, 0, Board()); // ref-note {{in call to 'buildBoardRecurse(8, 0, Board())'}} \
+   // expected-note {{in call to 'buildBoardRecurse(8, 0, Board())'}}
 }
 
 constexpr Board q8 = buildBoard(8); // ref-error {{must be initialized by a constant expression}} \
 // ref-note {{in call to 'buildBoard(8)'}} \
-// expected-error {{must be initialized by a constant expression}}
+// expected-error {{must be initialized by a constant expression}} \
+// expected-note {{in call to 'buildBoard(8)'}}
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -181,6 +181,9 @@
 return this->emitPopPtr(I);
   }
 
+  bool visitConditional(const AbstractConditionalOperator *E,
+llvm::function_ref V);
+
   /// Creates a local primitive value.
   unsigned allocateLocalPrimitive(DeclTy &&Decl, PrimType Ty, bool IsMutable,
   bool IsExtended = false);
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -568,32 +568,8 @@
 template 
 bool ByteCodeExprGen::VisitAbstractConditionalOperator(
 const AbstractConditionalOperator *E) {
-  const Expr *Condition = E->getCond();
-  const Expr *TrueExpr = E->getTrueExpr();
-  const Expr *FalseExpr = E->getFalseExpr();
-
-  LabelTy LabelEnd = this->getLabel();   // Label after the operator.
-  LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
-
-  if (!this->visit(Condition))
-return false;
-  if (!this->jumpFalse(LabelFalse))
-return false;
-
-  if (!this->visit(TrueExpr))
-return false;
-  if (!this->jump(LabelEnd))
-return false;
-
-  this->emitLabel(LabelFalse)

[PATCH] D146376: Update static_assert message for redundant cases

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

Does `git clang-format HEAD~1` not work on your system? It should only format 
the changed parts, not everything.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146376

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


[PATCH] D146809: [WIP][clang-repl] Implement Value pretty printing

2023-03-31 Thread Jun Zhang via Phabricator via cfe-commits
junaire updated this revision to Diff 510168.
junaire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146809

Files:
  clang/include/clang/Interpreter/Interpreter.h
  clang/lib/Headers/CMakeLists.txt
  clang/lib/Headers/__clang_interpreter_runtime_printvalue.h
  clang/lib/Interpreter/CMakeLists.txt
  clang/lib/Interpreter/Interpreter.cpp
  clang/lib/Interpreter/Value.cpp
  clang/lib/Interpreter/ValuePrinter.cpp
  clang/test/Interpreter/pretty-print.cpp

Index: clang/test/Interpreter/pretty-print.cpp
===
--- /dev/null
+++ clang/test/Interpreter/pretty-print.cpp
@@ -0,0 +1,44 @@
+// RUN: clang-repl "int i = 10;" 'extern "C" int printf(const char*,...);' \
+// RUN:'auto r1 = printf("i = %d\n", i);' | FileCheck --check-prefix=CHECK-DRIVER %s
+// UNSUPPORTED: system-aix
+// CHECK-DRIVER: i = 10
+// RUN: cat %s | clang-repl | FileCheck %s
+char c = 'a';
+c
+// CHECK: (char) 'a'
+
+int x = 42;
+x
+// CHECK-NEXT: (int) 42
+
+x - 2
+// CHECK-NEXT: (int) 40
+
+float f = 4.2f;
+f
+// CHECK-NEXT: (float) 4.2f
+
+double d = 4.21;
+d
+// CHECK-NEXT: (double) 4.210
+
+struct S{};
+S s;
+s
+// CHECK-NEXT: (S &) [[Addr:@0x.*]]
+
+S{}
+// CHECK-NEXT: (S) [[Addr:@0x.*]]
+
+struct SS { ~SS() {} };
+SS{}
+// CHECK-NEXT: (SS) [[Addr:@0x.*]]
+
+#include 
+
+auto p1 = std::make_shared(42);
+p1
+// CHECK-NEXT: (shared_ptr &) std::shared_ptr -> [[Addr:@0x.*]]
+
+%quit
+
Index: clang/lib/Interpreter/ValuePrinter.cpp
===
--- /dev/null
+++ clang/lib/Interpreter/ValuePrinter.cpp
@@ -0,0 +1,524 @@
+#include "InterpreterUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/PrettyPrinter.h"
+#include "clang/AST/Type.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Interpreter/Interpreter.h"
+#include "clang/Interpreter/Value.h"
+#include "clang/Parse/Parser.h"
+#include "clang/Sema/Lookup.h"
+#include "clang/Sema/Sema.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+#include 
+
+using namespace clang;
+
+static std::string PrintDeclType(const QualType &QT, NamedDecl *D) {
+  std::string Str;
+  llvm::raw_string_ostream SS(Str);
+  if (QT.hasQualifiers())
+SS << QT.getQualifiers().getAsString() << " ";
+  SS << D->getQualifiedNameAsString();
+  return Str;
+}
+
+static std::string PrintQualType(ASTContext &Ctx, QualType QT) {
+  std::string Str;
+  llvm::raw_string_ostream SS(Str);
+  PrintingPolicy Policy(Ctx.getPrintingPolicy());
+  // Print the Allocator in STL containers, for instance.
+  Policy.SuppressDefaultTemplateArgs = false;
+  Policy.SuppressUnwrittenScope = true;
+  // Print 'a >' rather than 'a>'.
+  Policy.SplitTemplateClosers = true;
+
+  class LocalPrintingPolicyRAII {
+  public:
+LocalPrintingPolicyRAII(ASTContext &Ctx, PrintingPolicy &PPol)
+: Context(Ctx), Policy(Ctx.getPrintingPolicy()) {
+  Context.setPrintingPolicy(PPol);
+}
+~LocalPrintingPolicyRAII() { Context.setPrintingPolicy(Policy); }
+
+  private:
+ASTContext &Context;
+PrintingPolicy Policy;
+  } X(Ctx, Policy);
+
+  const QualType NonRefTy = QT.getNonReferenceType();
+
+  if (const auto *TTy = llvm::dyn_cast(NonRefTy))
+SS << PrintDeclType(NonRefTy, TTy->getDecl());
+  else if (const auto *TRy = dyn_cast(NonRefTy))
+SS << PrintDeclType(NonRefTy, TRy->getDecl());
+  else {
+const QualType Canon = NonRefTy.getCanonicalType();
+if (Canon->isBuiltinType() && !NonRefTy->isFunctionPointerType() &&
+!NonRefTy->isMemberPointerType()) {
+  SS << Canon.getAsString(Ctx.getPrintingPolicy());
+} else if (const auto *TDTy = dyn_cast(NonRefTy)) {
+  // FIXME: TemplateSpecializationType & SubstTemplateTypeParmType checks
+  // are predominately to get STL containers to print nicer and might be
+  // better handled in GetFullyQualifiedName.
+  //
+  // std::vector::iterator is a TemplateSpecializationType
+  // std::vector::value_type is a SubstTemplateTypeParmType
+  //
+  QualType SSDesugar = TDTy->getLocallyUnqualifiedSingleStepDesugaredType();
+  if (llvm::isa(SSDesugar))
+SS << GetFullTypeName(Ctx, Canon);
+  else if (llvm::isa(SSDesugar))
+SS << GetFullTypeName(Ctx, NonRefTy);
+  else
+SS << PrintDeclType(NonRefTy, TDTy->getDecl());
+} else
+  SS << GetFullTypeName(Ctx, NonRefTy);
+  }
+
+  if (QT->isReferenceType())
+SS << " &";
+
+  return Str;
+}
+
+static std::string PrintEnum(const Value &V) {
+  std::string Str;
+  llvm::raw_string_ostream SS(Str);
+  ASTContext &Ctx = V.getASTContext();
+
+  QualType DesugaredTy = V.getType().getDesugaredType(Ctx);
+  const EnumType *EnumTy = DesugaredTy.getNonReferenceType()->getAs();
+  assert(EnumTy && "Fail to cast to enum type");
+
+  EnumDecl *ED = EnumTy

[PATCH] D141215: [clang-repl] Introduce Value to capture expression results

2023-03-31 Thread Jun Zhang via Phabricator via cfe-commits
junaire updated this revision to Diff 510167.
junaire added a comment.

Update.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141215

Files:
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Interpreter/Interpreter.h
  clang/include/clang/Interpreter/Value.h
  clang/include/clang/Parse/Parser.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Frontend/PrintPreprocessedOutput.cpp
  clang/lib/Interpreter/CMakeLists.txt
  clang/lib/Interpreter/IncrementalExecutor.cpp
  clang/lib/Interpreter/IncrementalExecutor.h
  clang/lib/Interpreter/IncrementalParser.cpp
  clang/lib/Interpreter/IncrementalParser.h
  clang/lib/Interpreter/Interpreter.cpp
  clang/lib/Interpreter/InterpreterUtils.cpp
  clang/lib/Interpreter/InterpreterUtils.h
  clang/lib/Interpreter/Value.cpp
  clang/lib/Lex/PPLexerChange.cpp
  clang/lib/Parse/ParseCXXInlineMethods.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Parse/Parser.cpp
  clang/tools/clang-repl/CMakeLists.txt
  clang/unittests/Interpreter/CMakeLists.txt
  clang/unittests/Interpreter/InterpreterTest.cpp

Index: clang/unittests/Interpreter/InterpreterTest.cpp
===
--- clang/unittests/Interpreter/InterpreterTest.cpp
+++ clang/unittests/Interpreter/InterpreterTest.cpp
@@ -17,6 +17,7 @@
 #include "clang/AST/Mangle.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/TextDiagnosticPrinter.h"
+#include "clang/Interpreter/Value.h"
 #include "clang/Sema/Lookup.h"
 #include "clang/Sema/Sema.h"
 
@@ -33,6 +34,10 @@
 #define CLANG_INTERPRETER_NO_SUPPORT_EXEC
 #endif
 
+int Global = 42;
+int getGlobal() { return Global; }
+void setGlobal(int val) { Global = val; }
+
 namespace {
 using Args = std::vector;
 static std::unique_ptr
@@ -276,8 +281,7 @@
   std::vector Args = {"-fno-delayed-template-parsing"};
   std::unique_ptr Interp = createInterpreter(Args);
 
-  llvm::cantFail(Interp->Parse("void* operator new(__SIZE_TYPE__, void* __p);"
-   "extern \"C\" int printf(const char*,...);"
+  llvm::cantFail(Interp->Parse("extern \"C\" int printf(const char*,...);"
"class A {};"
"struct B {"
"  template"
@@ -314,4 +318,38 @@
   free(NewA);
 }
 
+TEST(InterpreterTest, Value) {
+  std::unique_ptr Interp = createInterpreter();
+
+  Value V1;
+  llvm::cantFail(Interp->ParseAndExecute("int x = 42;"));
+  llvm::cantFail(Interp->ParseAndExecute("x", &V1));
+  EXPECT_EQ(V1.getInt(), 42);
+  EXPECT_TRUE(V1.getType()->isIntegerType());
+
+  Value V2;
+  llvm::cantFail(Interp->ParseAndExecute("double y = 3.14;"));
+  llvm::cantFail(Interp->ParseAndExecute("y", &V2));
+  EXPECT_EQ(V2.getAs(), 3.14);
+  EXPECT_TRUE(V2.getType()->isFloatingType());
+  EXPECT_EQ(V2.castAs(), 3);
+
+  llvm::cantFail(Interp->ParseAndExecute("int getGlobal();"));
+  llvm::cantFail(Interp->ParseAndExecute("void setGlobal(int);"));
+  Value V3;
+  llvm::cantFail(Interp->ParseAndExecute("getGlobal()", &V3));
+  EXPECT_EQ(V3.getInt(), 42);
+  EXPECT_TRUE(V3.getType()->isIntegerType());
+
+  // Change the global from the compiled code.
+  setGlobal(43);
+  Value V4;
+  llvm::cantFail(Interp->ParseAndExecute("getGlobal()", &V4));
+  EXPECT_EQ(V4.getInt(), 43);
+  EXPECT_TRUE(V4.getType()->isIntegerType());
+
+  // Change the global from the interpreted code.
+  llvm::cantFail(Interp->ParseAndExecute("setGlobal(44);"));
+  EXPECT_EQ(getGlobal(), 44);
+}
 } // end anonymous namespace
Index: clang/unittests/Interpreter/CMakeLists.txt
===
--- clang/unittests/Interpreter/CMakeLists.txt
+++ clang/unittests/Interpreter/CMakeLists.txt
@@ -22,3 +22,5 @@
 if(NOT WIN32)
   add_subdirectory(ExceptionTests)
 endif()
+
+export_executable_symbols(ClangReplInterpreterTests)
Index: clang/tools/clang-repl/CMakeLists.txt
===
--- clang/tools/clang-repl/CMakeLists.txt
+++ clang/tools/clang-repl/CMakeLists.txt
@@ -12,6 +12,7 @@
   )
 
 clang_target_link_libraries(clang-repl PRIVATE
+  clangAST
   clangBasic
   clangFrontend
   clangInterpreter
Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -320,6 +320,7 @@
 case tok::annot_module_begin:
 case tok::annot_module_end:
 case tok::annot_module_include:
+case tok::annot_input_end:
   // Stop before we change submodules. They generally indicate a "good"
   // place to pick up parsing again (except in the special case where
   // we're trying to skip to EOF).
@@ -616,8 +617,8 @@
 
   // Skip over the EOF token, flagging end of previous input for incremental
   // processing
-  if (PP.isIncrementalProcessingEnabled

[PATCH] D144347: [clang-tidy] Add readability-forward-usage check

2023-03-31 Thread Chris Cotter via Phabricator via cfe-commits
ccotter added inline comments.



Comment at: clang-tools-extra/clang-tidy/readability/ForwardUsageCheck.cpp:99
+  unless(isExpansionInSystemHeader()), argumentCountIs(1U),
+  IgnoreDependentExpresions
+  ? expr(unless(isInstantiationDependent()))

I think we might need more tests when `IgnoreDependentExpresions` is true. When 
I was playing around and hardcoded IgnoreDependentExpresions to false on line 
99, the tests still pass.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:126
+
+  Suggests removing or replacing ``std::forward`` with ``std::move`` or
+  ``static_cast`` in cases where the template argument type is invariant and

Would you see use in expanding use of this check to cases that (broadly, 
cppcoreguiideline ES.56) apply `forward` when the argument is not a forwarding 
reference? Or separate check (as the one I proposed in 
https://reviews.llvm.org/D146888)? Specifically, when the template parameter is 
deduced:

```
template  void forwards_incorrectly(T& t) { T other = 
std::forward(t); } // ignored by readability-forward-usage
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144347

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


[PATCH] D147365: [HIPSPV] Remove useIntegratedAs. NFC

2023-03-31 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

I don't know the toolchain, does `HIPSPV` perform as expected if you pass 
`-fno-integrated-as`? The difference is that `useIntegratedAs` forces it to 
always be enabled so the user can't change it AFAIK.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147365

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


[PATCH] D147365: [HIPSPV] Remove useIntegratedAs. NFC

2023-03-31 Thread Brad Smith via Phabricator via cfe-commits
brad created this revision.
brad added reviewers: jhuber6, ronlieb.
brad added a project: clang.
Herald added a subscriber: yaxunl.
Herald added a project: All.
brad requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.

useIntegratedAs() is enabled if IsIntegratedAssemblerDefault() is enabled.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147365

Files:
  clang/lib/Driver/ToolChains/HIPSPV.h


Index: clang/lib/Driver/ToolChains/HIPSPV.h
===
--- clang/lib/Driver/ToolChains/HIPSPV.h
+++ clang/lib/Driver/ToolChains/HIPSPV.h
@@ -81,7 +81,6 @@
const llvm::opt::ArgList &Args) const override;
   bool IsIntegratedAssemblerDefault() const override { return true; }
   bool IsMathErrnoDefault() const override { return false; }
-  bool useIntegratedAs() const override { return true; }
   bool isCrossCompiling() const override { return true; }
   bool isPICDefault() const override { return false; }
   bool isPIEDefault(const llvm::opt::ArgList &Args) const override {


Index: clang/lib/Driver/ToolChains/HIPSPV.h
===
--- clang/lib/Driver/ToolChains/HIPSPV.h
+++ clang/lib/Driver/ToolChains/HIPSPV.h
@@ -81,7 +81,6 @@
const llvm::opt::ArgList &Args) const override;
   bool IsIntegratedAssemblerDefault() const override { return true; }
   bool IsMathErrnoDefault() const override { return false; }
-  bool useIntegratedAs() const override { return true; }
   bool isCrossCompiling() const override { return true; }
   bool isPICDefault() const override { return false; }
   bool isPIEDefault(const llvm::opt::ArgList &Args) const override {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D147328: [clang-format] Handle enum in Verilog

2023-03-31 Thread Owen Pan via Phabricator via cfe-commits
owenpan accepted this revision.
owenpan added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1712
 break;
-  // This only applies for C++.
-  if (!Style.isCpp()) {
+  // This only applies for C++ and Verilog.
+  if (!Style.isCpp() && !Style.isVerilog()) {




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147328

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


[clang] 4d7e516 - [OHOS] Remove redundant IsIntegratedAssemblerDefault. NFC

2023-03-31 Thread Brad Smith via cfe-commits

Author: Brad Smith
Date: 2023-03-31T20:27:29-04:00
New Revision: 4d7e5163d96758516c4838f05bfaa481d63179e1

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

LOG: [OHOS] Remove redundant IsIntegratedAssemblerDefault. NFC

It is already enabled.

Added: 


Modified: 
clang/lib/Driver/ToolChains/OHOS.h

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/OHOS.h 
b/clang/lib/Driver/ToolChains/OHOS.h
index 9ce0d0c4325bf..b648d0ffa67a1 100644
--- a/clang/lib/Driver/ToolChains/OHOS.h
+++ b/clang/lib/Driver/ToolChains/OHOS.h
@@ -23,8 +23,9 @@ class LLVM_LIBRARY_VISIBILITY OHOS : public Generic_ELF {
   const llvm::opt::ArgList &Args);
 
   bool HasNativeLLVMSupport() const override { return true; }
-  bool IsIntegratedAssemblerDefault() const override { return true; }
+
   bool IsMathErrnoDefault() const override { return false; }
+
   RuntimeLibType GetDefaultRuntimeLibType() const override {
 return ToolChain::RLT_CompilerRT;
   }



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


[PATCH] D146101: [clang-format] Add BracedInitializerIndentWidth option.

2023-03-31 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/include/clang/Format/Format.h:949
+  /// If unset, ``ContinuationIndentWidth`` is used.
+  /// \code
+  ///   AlignAfterOpenBracket: AlwaysBreak

HazardyKnusperkeks wrote:
> jp4a50 wrote:
> > MyDeveloperDay wrote:
> > > did you check generating the html from the rst? I can never remember if 
> > > we need a newline before the \code
> > Nope - how do I do that exactly? I would guess a newline is not needed 
> > based on other examples.
> > did you check generating the html from the rst? I can never remember if we 
> > need a newline before the \code
> 
> 
> Nope - how do I do that exactly? I would guess a newline is not needed based 
> on other examples.

See D147327#4236718.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146101

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


[PATCH] D147111: [clang-format] Add MinDigits suboptions to IntegerLiteralSeparator

2023-03-31 Thread Owen Pan via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG253985d58caf: [clang-format] Add MinDigits suboptions to 
IntegerLiteralSeparator (authored by owenpan).

Changed prior to commit:
  https://reviews.llvm.org/D147111?vs=509511&id=510152#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147111

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/IntegerLiteralSeparatorFixer.cpp
  clang/lib/Format/IntegerLiteralSeparatorFixer.h
  clang/unittests/Format/IntegerLiteralSeparatorTest.cpp

Index: clang/unittests/Format/IntegerLiteralSeparatorTest.cpp
===
--- clang/unittests/Format/IntegerLiteralSeparatorTest.cpp
+++ clang/unittests/Format/IntegerLiteralSeparatorTest.cpp
@@ -116,6 +116,41 @@
   verifyFormat("o = 0o43n;", Style);
 }
 
+TEST_F(IntegerLiteralSeparatorTest, MinDigits) {
+  FormatStyle Style = getLLVMStyle();
+  Style.IntegerLiteralSeparator.Binary = 3;
+  Style.IntegerLiteralSeparator.Decimal = 3;
+  Style.IntegerLiteralSeparator.Hex = 2;
+
+  Style.IntegerLiteralSeparator.BinaryMinDigits = 7;
+  verifyFormat("b1 = 0b101101;\n"
+   "b2 = 0b1'101'101;",
+   "b1 = 0b101'101;\n"
+   "b2 = 0b1101101;",
+   Style);
+
+  Style.IntegerLiteralSeparator.DecimalMinDigits = 5;
+  verifyFormat("d1 = 2023;\n"
+   "d2 = 10'000;",
+   "d1 = 2'023;\n"
+   "d2 = 100'00;",
+   Style);
+
+  Style.IntegerLiteralSeparator.DecimalMinDigits = 3;
+  verifyFormat("d1 = 123;\n"
+   "d2 = 1'234;",
+   "d1 = 12'3;\n"
+   "d2 = 12'34;",
+   Style);
+
+  Style.IntegerLiteralSeparator.HexMinDigits = 6;
+  verifyFormat("h1 = 0xABCDE;\n"
+   "h2 = 0xAB'CD'EF;",
+   "h1 = 0xA'BC'DE;\n"
+   "h2 = 0xABC'DEF;",
+   Style);
+}
+
 TEST_F(IntegerLiteralSeparatorTest, FixRanges) {
   FormatStyle Style = getLLVMStyle();
   Style.IntegerLiteralSeparator.Decimal = 3;
Index: clang/lib/Format/IntegerLiteralSeparatorFixer.h
===
--- clang/lib/Format/IntegerLiteralSeparatorFixer.h
+++ clang/lib/Format/IntegerLiteralSeparatorFixer.h
@@ -27,7 +27,8 @@
 
 private:
   bool checkSeparator(const StringRef IntegerLiteral, int DigitsPerGroup) const;
-  std::string format(const StringRef IntegerLiteral, int DigitsPerGroup) const;
+  std::string format(const StringRef IntegerLiteral, int DigitsPerGroup,
+ int DigitCount, bool RemoveSeparator) const;
 
   char Separator;
 };
Index: clang/lib/Format/IntegerLiteralSeparatorFixer.cpp
===
--- clang/lib/Format/IntegerLiteralSeparatorFixer.cpp
+++ clang/lib/Format/IntegerLiteralSeparatorFixer.cpp
@@ -69,6 +69,12 @@
   if (SkipBinary && SkipDecimal && SkipHex)
 return {};
 
+  const auto BinaryMinDigits =
+  std::max((int)Option.BinaryMinDigits, Binary + 1);
+  const auto DecimalMinDigits =
+  std::max((int)Option.DecimalMinDigits, Decimal + 1);
+  const auto HexMinDigits = std::max((int)Option.HexMinDigits, Hex + 1);
+
   const auto &SourceMgr = Env.getSourceManager();
   AffectedRangeManager AffectedRangeMgr(SourceMgr, Env.getCharRanges());
 
@@ -116,11 +122,6 @@
 (IsBase16 && Text.find_last_of(".pP") != StringRef::npos)) {
   continue;
 }
-if (((IsBase2 && Binary < 0) || (IsBase10 && Decimal < 0) ||
- (IsBase16 && Hex < 0)) &&
-Text.find(Separator) == StringRef::npos) {
-  continue;
-}
 const auto Start = Text[0] == '0' ? 2 : 0;
 auto End = Text.find_first_of("uUlLzZn", Start);
 if (End == StringRef::npos)
@@ -130,13 +131,25 @@
   Text = Text.substr(Start, Length);
 }
 auto DigitsPerGroup = Decimal;
-if (IsBase2)
+auto MinDigits = DecimalMinDigits;
+if (IsBase2) {
   DigitsPerGroup = Binary;
-else if (IsBase16)
+  MinDigits = BinaryMinDigits;
+} else if (IsBase16) {
   DigitsPerGroup = Hex;
-if (DigitsPerGroup > 0 && checkSeparator(Text, DigitsPerGroup))
+  MinDigits = HexMinDigits;
+}
+const auto SeparatorCount = Text.count(Separator);
+const int DigitCount = Length - SeparatorCount;
+const bool RemoveSeparator = DigitsPerGroup < 0 || DigitCount < MinDigits;
+if (RemoveSeparator && SeparatorCount == 0)
   continue;
-const auto &Formatted = format(Text, DigitsPerGroup);
+if (!RemoveSeparator && SeparatorCount > 0 &&
+checkSeparator(Text, DigitsPerGroup)) {
+  continue;
+}
+const auto &Form

[clang] 253985d - [clang-format] Add MinDigits suboptions to IntegerLiteralSeparator

2023-03-31 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-03-31T17:14:33-07:00
New Revision: 253985d58caf95db8a84632d5a761b96fb7cd7d6

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

LOG: [clang-format] Add MinDigits suboptions to IntegerLiteralSeparator

Closes #61209.

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/IntegerLiteralSeparatorFixer.cpp
clang/lib/Format/IntegerLiteralSeparatorFixer.h
clang/unittests/Format/IntegerLiteralSeparatorTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index d706a0494f0f5..4078019f82bad 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -3375,6 +3375,10 @@ the configuration (without a prefix: ``Auto``).
   Decimal: 3
   Hex: -1
 
+  You can also specify a minimum number of digits (``BinaryMinDigits``,
+  ``DecimalMinDigits``, and ``HexMinDigits``) the integer literal must
+  have in order for the separators to be inserted.
+
   * ``int8_t Binary`` Format separators in binary literals.
 
 .. code-block:: text
@@ -3384,6 +3388,15 @@ the configuration (without a prefix: ``Auto``).
   /*  3: */ b = 0b100'111'101'101;
   /*  4: */ b = 0b1001'1110'1101;
 
+  * ``int8_t BinaryMinDigits`` Format separators in binary literals with a 
minimum number of digits.
+
+.. code-block:: text
+
+  // Binary: 3
+  // BinaryMinDigits: 7
+  b1 = 0b101101;
+  b2 = 0b1'101'101;
+
   * ``int8_t Decimal`` Format separators in decimal literals.
 
 .. code-block:: text
@@ -3392,6 +3405,15 @@ the configuration (without a prefix: ``Auto``).
   /*  0: */ d = 184467'440737'0'95505'92ull;
   /*  3: */ d = 18'446'744'073'709'550'592ull;
 
+  * ``int8_t DecimalMinDigits`` Format separators in decimal literals with a 
minimum number of digits.
+
+.. code-block:: text
+
+  // Decimal: 3
+  // DecimalMinDigits: 5
+  d1 = 2023;
+  d2 = 10'000;
+
   * ``int8_t Hex`` Format separators in hexadecimal literals.
 
 .. code-block:: text
@@ -3400,6 +3422,16 @@ the configuration (without a prefix: ``Auto``).
   /*  0: */ h = 0xDEAD'BEEF'DE'AD'BEE'Fuz;
   /*  2: */ h = 0xDE'AD'BE'EF'DE'AD'BE'EFuz;
 
+  * ``int8_t HexMinDigits`` Format separators in hexadecimal literals with a 
minimum number of
+digits.
+
+.. code-block:: text
+
+  // Hex: 2
+  // HexMinDigits: 6
+  h1 = 0xABCDE;
+  h2 = 0xAB'CD'EF;
+
 
 .. _JavaImportGroups:
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index cc2b34a20e895..85daa50b5bac8 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2500,6 +2500,10 @@ struct FormatStyle {
   /// Decimal: 3
   /// Hex: -1
   /// \endcode
+  ///
+  /// You can also specify a minimum number of digits (``BinaryMinDigits``,
+  /// ``DecimalMinDigits``, and ``HexMinDigits``) the integer literal must
+  /// have in order for the separators to be inserted.
   struct IntegerLiteralSeparatorStyle {
 /// Format separators in binary literals.
 /// \code{.text}
@@ -2509,6 +2513,14 @@ struct FormatStyle {
 ///   /*  4: */ b = 0b1001'1110'1101;
 /// \endcode
 int8_t Binary;
+/// Format separators in binary literals with a minimum number of digits.
+/// \code{.text}
+///   // Binary: 3
+///   // BinaryMinDigits: 7
+///   b1 = 0b101101;
+///   b2 = 0b1'101'101;
+/// \endcode
+int8_t BinaryMinDigits;
 /// Format separators in decimal literals.
 /// \code{.text}
 ///   /* -1: */ d = 18446744073709550592ull;
@@ -2516,6 +2528,14 @@ struct FormatStyle {
 ///   /*  3: */ d = 18'446'744'073'709'550'592ull;
 /// \endcode
 int8_t Decimal;
+/// Format separators in decimal literals with a minimum number of digits.
+/// \code{.text}
+///   // Decimal: 3
+///   // DecimalMinDigits: 5
+///   d1 = 2023;
+///   d2 = 10'000;
+/// \endcode
+int8_t DecimalMinDigits;
 /// Format separators in hexadecimal literals.
 /// \code{.text}
 ///   /* -1: */ h = 0xDEADBEEFDEADBEEFuz;
@@ -2523,6 +2543,20 @@ struct FormatStyle {
 ///   /*  2: */ h = 0xDE'AD'BE'EF'DE'AD'BE'EFuz;
 /// \endcode
 int8_t Hex;
+/// Format separators in hexadecimal literals with a minimum number of
+/// digits.
+/// \code{.text}
+///   // Hex: 2
+///   // HexMinDigits: 6
+///   h1 = 0xABCDE;
+///   h2 = 0xAB'CD'EF;
+/// \endcode
+int8_t HexMinDigits;
+bool operator==(const IntegerLiteralSeparatorStyle &R) const {
+  retur

[PATCH] D146178: [Clang][Sema] Fix comparison of constraint expressions

2023-03-31 Thread Alexander Shaposhnikov via Phabricator via cfe-commits
alexander-shaposhnikov added a comment.

@rsmith - thanks a lot for the review, is there anything you'd like me to do on 
this diff or we are good to go ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146178

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


[PATCH] D147121: [hwasan] remove requirment for PIE

2023-03-31 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka removed a reviewer: alekseyshl. vitalybuka added 1 blocking 
reviewer(s): eugenis.
vitalybuka accepted this revision.
vitalybuka added a comment.
This revision now requires review to proceed.

I don't know why HWASAN may required pie, but @eugenis seems confident on 
D44745 . Lets give him a chance to take a look.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147121

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


[PATCH] D141389: [DFSAN] Add support for strnlen, strncat, strsep, sscanf and _tolower

2023-03-31 Thread Andrew via Phabricator via cfe-commits
browneee added inline comments.



Comment at: compiler-rt/lib/dfsan/dfsan_custom.cpp:221
+  if (flags().strict_data_dependencies) {
+*ret_label = res ? dfsan_read_label(base, sizeof(base)) : 0;
+  } else {

tkuchta wrote:
> browneee wrote:
> > `base, sizeof(base)` does not make sense - the size does not correspond to 
> > the pointer used.
> > 
> > Either
> > ```
> > dfsan_read_label(base, sizeof(*base))   // first byte pointed to by base
> > dfsan_read_label(base, strlen(base)) // whole string pointed to by base
> > dfsan_read_label(&base, sizeof(base))  // the base pointer
> > ```
> > 
> > In this case I think we want the base pointer.
> > 
> > `dfsan_read_label(&base, sizeof(base))`  // the base pointer
> > should be equivalent to doing
> > `dfsan_label base_label = dfsan_read_label(s, sizeof(*s))`  up at the start 
> > of the function, just after we declare base then use `base_label` here.
> > 
> > Lets go with the second option to avoid taking the address of a variable.
> > 
> > This is semantically equivalent to my first suggestion: 
> > `dfsan_get_label(base) == dfsan_read_label(&base, sizeof(base)) == 
> > base_label`.
> > Sorry I didn't consider the other constraints (no dfsan_get_label in this 
> > file because the pass is not run on this code; avoid taking address of 
> > variable) and suggest this in the first place.
> Thank you for your comments! Just to clarify:
> If we have strict data dependencies we would like *ret_label to be related to 
> the taints of the contents of the string, is that correct? Should we use the 
> base_label there too? My understanding is that base_label represents a taint 
> applied to the pointer, not to the data? 
> 
> In other words, would that be correct to:
> 1) use taints of the string data in the first case (strict dependencies) -> 
> therefore no base_label there as it represents the taint of the pointer
> 2) use the taints of the string data + the taints of the pointer in the 
> second case -> therefore using base_label there
> If we have strict data dependencies we would like *ret_label to be related to 
> the taints of the contents of the string, is that correct?

No, `*ret_label` holds the taint label for the return value, which is a 
pointer. The return value pointer is derived from `*s`, aka `base`. This is the 
pointer to the string contents, not the string contents themselves.

> Should we use the base_label there too?

I think we should only use `base_label` here.

> My understanding is that base_label represents a taint applied to the 
> pointer, not to the data?

Correct.


> In other words, would that be correct to:
> 1. use taints of the string data in the first case (strict dependencies) -> 
> therefore no base_label there as it represents the taint of the pointer

No, other way around. We want the base_label, but not the string data.

> 2. use the taints of the string data + the taints of the pointer in the 
> second case -> therefore using base_label there

Yes, we could have both base_label and the taints of the string data in the 
else case.


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

https://reviews.llvm.org/D141389

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


[PATCH] D147295: [clang-format] Don't misannotate left squares as lambda introducers

2023-03-31 Thread Owen Pan 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 rG2a42a7b4e873: [clang-format] Don't misannotate left 
squares as lambda introducers (authored by owenpan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147295

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -382,6 +382,32 @@
   Tokens = annotate("struct [[deprecated]] [[nodiscard]] C { int i; };");
   EXPECT_EQ(Tokens.size(), 19u) << Tokens;
   EXPECT_TOKEN(Tokens[12], tok::l_brace, TT_StructLBrace);
+
+  Tokens = annotate("template  struct S {};");
+  EXPECT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[10], tok::l_square, TT_ArraySubscriptLSquare);
+  EXPECT_TOKEN(Tokens[13], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_StructLBrace);
+
+  Tokens = annotate("template  struct S {};");
+  EXPECT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[10], tok::l_square, TT_ArraySubscriptLSquare);
+  EXPECT_TOKEN(Tokens[13], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_StructLBrace);
+
+  Tokens = annotate("template  struct S 
{\n"
+"  void f(T const (&a)[n]);\n"
+"};");
+  EXPECT_EQ(Tokens.size(), 35u) << Tokens;
+  EXPECT_TOKEN(Tokens[10], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[13], tok::l_square, TT_ArraySubscriptLSquare);
+  EXPECT_TOKEN(Tokens[16], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[17], tok::l_brace, TT_StructLBrace);
+  EXPECT_TOKEN(Tokens[23], tok::l_paren, TT_FunctionTypeLParen);
+  EXPECT_TOKEN(Tokens[24], tok::amp, TT_UnaryOperator);
+  EXPECT_TOKEN(Tokens[27], tok::l_square, TT_ArraySubscriptLSquare);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUnions) {
@@ -1193,6 +1219,16 @@
   EXPECT_TOKEN(Tokens[9], tok::l_brace, TT_ObjCBlockLBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsObjCMethodExpr) {
+  auto Tokens = annotate("void f() {\n"
+ "  //\n"
+ "  BOOL a = [b.c n] > 1;\n"
+ "}");
+  EXPECT_EQ(Tokens.size(), 20u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::l_square, TT_ObjCMethodExpr);
+  EXPECT_TOKEN(Tokens[15], tok::greater, TT_BinaryOperator);
+}
+
 TEST_F(TokenAnnotatorTest, UnderstandsLambdas) {
   auto Tokens = annotate("[]() constexpr {}");
   ASSERT_EQ(Tokens.size(), 8u) << Tokens;
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2231,11 +2231,11 @@
   const FormatToken *Previous = FormatTok->Previous;
   const FormatToken *LeftSquare = FormatTok;
   nextToken();
-  if (Previous &&
-  (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
- tok::kw_delete, tok::l_square) ||
-   LeftSquare->isCppStructuredBinding(Style) || Previous->closesScope() ||
-   Previous->isSimpleTypeSpecifier())) {
+  if ((Previous && ((Previous->Tok.getIdentifierInfo() &&
+ !Previous->isOneOf(tok::kw_return, tok::kw_co_await,
+tok::kw_co_yield, tok::kw_co_return)) 
||
+Previous->closesScope())) ||
+  LeftSquare->isCppStructuredBinding(Style)) {
 return false;
   }
   if (FormatTok->is(tok::l_square))
@@ -3784,7 +3784,7 @@
   // Don't try parsing a lambda if we had a closing parenthesis before,
   // it was probably a pointer to an array: int (*)[].
   if (!tryToParseLambda())
-break;
+continue;
 } else {
   parseSquare();
   continue;


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -382,6 +382,32 @@
   Tokens = annotate("struct [[deprecated]] [[nodiscard]] C { int i; };");
   EXPECT_EQ(Tokens.size(), 19u) << Tokens;
   EXPECT_TOKEN(Tokens[12], tok::l_brace, TT_StructLBrace);
+
+  Tokens = annotate("template  struct S {};");
+  EXPECT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[10], tok::l_square, TT_ArraySubscriptLSquare);
+  EXPECT_TOKEN(Tokens[13], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_StructLBrace);
+
+  Tokens = ann

[clang] 2a42a7b - [clang-format] Don't misannotate left squares as lambda introducers

2023-03-31 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-03-31T16:13:03-07:00
New Revision: 2a42a7b4e87395ae2a4321292f0fd9dce401b4e1

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

LOG: [clang-format] Don't misannotate left squares as lambda introducers

A left square can start a lambda only if it's not preceded by an
identifier other than return and co-wait/co-yield/co-return.

Fixes #54245.
Fixes #61786.

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 3a661292b2d72..fdf5d85d6b1d2 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2231,11 +2231,11 @@ bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
   const FormatToken *Previous = FormatTok->Previous;
   const FormatToken *LeftSquare = FormatTok;
   nextToken();
-  if (Previous &&
-  (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
- tok::kw_delete, tok::l_square) ||
-   LeftSquare->isCppStructuredBinding(Style) || Previous->closesScope() ||
-   Previous->isSimpleTypeSpecifier())) {
+  if ((Previous && ((Previous->Tok.getIdentifierInfo() &&
+ !Previous->isOneOf(tok::kw_return, tok::kw_co_await,
+tok::kw_co_yield, tok::kw_co_return)) 
||
+Previous->closesScope())) ||
+  LeftSquare->isCppStructuredBinding(Style)) {
 return false;
   }
   if (FormatTok->is(tok::l_square))
@@ -3784,7 +3784,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   // Don't try parsing a lambda if we had a closing parenthesis before,
   // it was probably a pointer to an array: int (*)[].
   if (!tryToParseLambda())
-break;
+continue;
 } else {
   parseSquare();
   continue;

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index b058e62654551..bea85e5bdba2f 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -382,6 +382,32 @@ TEST_F(TokenAnnotatorTest, UnderstandsStructs) {
   Tokens = annotate("struct [[deprecated]] [[nodiscard]] C { int i; };");
   EXPECT_EQ(Tokens.size(), 19u) << Tokens;
   EXPECT_TOKEN(Tokens[12], tok::l_brace, TT_StructLBrace);
+
+  Tokens = annotate("template  struct S {};");
+  EXPECT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[10], tok::l_square, TT_ArraySubscriptLSquare);
+  EXPECT_TOKEN(Tokens[13], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_StructLBrace);
+
+  Tokens = annotate("template  struct S {};");
+  EXPECT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[10], tok::l_square, TT_ArraySubscriptLSquare);
+  EXPECT_TOKEN(Tokens[13], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_StructLBrace);
+
+  Tokens = annotate("template  struct S 
{\n"
+"  void f(T const (&a)[n]);\n"
+"};");
+  EXPECT_EQ(Tokens.size(), 35u) << Tokens;
+  EXPECT_TOKEN(Tokens[10], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[13], tok::l_square, TT_ArraySubscriptLSquare);
+  EXPECT_TOKEN(Tokens[16], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[17], tok::l_brace, TT_StructLBrace);
+  EXPECT_TOKEN(Tokens[23], tok::l_paren, TT_FunctionTypeLParen);
+  EXPECT_TOKEN(Tokens[24], tok::amp, TT_UnaryOperator);
+  EXPECT_TOKEN(Tokens[27], tok::l_square, TT_ArraySubscriptLSquare);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUnions) {
@@ -1193,6 +1219,16 @@ TEST_F(TokenAnnotatorTest, UnderstandsObjCBlock) {
   EXPECT_TOKEN(Tokens[9], tok::l_brace, TT_ObjCBlockLBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsObjCMethodExpr) {
+  auto Tokens = annotate("void f() {\n"
+ "  //\n"
+ "  BOOL a = [b.c n] > 1;\n"
+ "}");
+  EXPECT_EQ(Tokens.size(), 20u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::l_square, TT_ObjCMethodExpr);
+  EXPECT_TOKEN(Tokens[15], tok::greater, TT_BinaryOperator);
+}
+
 TEST_F(TokenAnnotatorTest, UnderstandsLambdas) {
   auto Tokens = annotate("[]() constexpr {}");
   ASSERT_EQ(Tokens.size(), 8u) << Tokens;



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


[PATCH] D147295: [clang-format] Don't misannotate left squares as lambda introducers

2023-03-31 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

In D147295#4235648 , @rymiel wrote:

> This is great!

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147295

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


[PATCH] D139653: [clang] Set ShowInSystemHeader for module-build and module-import remarks

2023-03-31 Thread Dave Lee 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 rGba6e747f9b05: [clang] Set ShowInSystemHeader for 
module-build and module-import remarks (authored by kastiglione).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139653

Files:
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Basic/DiagnosticSerializationKinds.td
  clang/test/Modules/system-Rmodule-build.m


Index: clang/test/Modules/system-Rmodule-build.m
===
--- /dev/null
+++ clang/test/Modules/system-Rmodule-build.m
@@ -0,0 +1,16 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t/sys
+// RUN: echo '#include ' > %t/sys/A.h
+// RUN: echo '' > %t/sys/B.h
+// RUN: echo 'module A { header "A.h" }' > %t/sys/module.modulemap
+// RUN: echo 'module B { header "B.h" }' >> %t/sys/module.modulemap
+
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t 
-fsyntax-only %s \
+// RUN:-isystem %t/sys -Rmodule-build 2>&1 | FileCheck %s
+
+@import A;
+
+// CHECK: building module 'A' as
+// CHECK: building module 'B' as
+// CHECK: finished building module 'B'
+// CHECK: finished building module 'A'
Index: clang/include/clang/Basic/DiagnosticSerializationKinds.td
===
--- clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -75,6 +75,7 @@
 
 def remark_module_import : Remark<
   "importing module '%0'%select{| into '%3'}2 from '%1'">,
+  ShowInSystemHeader,
   InGroup;
 
 def err_imported_module_not_found : Error<
Index: clang/include/clang/Basic/DiagnosticFrontendKinds.td
===
--- clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -241,8 +241,10 @@
 def note_module_def_undef_here : Note<
   "macro was %select{defined|#undef'd}0 here">;
 def remark_module_build : Remark<"building module '%0' as '%1'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_build_done : Remark<"finished building module '%0'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_lock : Remark<"locking '%0' to build module '%1'">,
   InGroup;


Index: clang/test/Modules/system-Rmodule-build.m
===
--- /dev/null
+++ clang/test/Modules/system-Rmodule-build.m
@@ -0,0 +1,16 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t/sys
+// RUN: echo '#include ' > %t/sys/A.h
+// RUN: echo '' > %t/sys/B.h
+// RUN: echo 'module A { header "A.h" }' > %t/sys/module.modulemap
+// RUN: echo 'module B { header "B.h" }' >> %t/sys/module.modulemap
+
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -fsyntax-only %s \
+// RUN:-isystem %t/sys -Rmodule-build 2>&1 | FileCheck %s
+
+@import A;
+
+// CHECK: building module 'A' as
+// CHECK: building module 'B' as
+// CHECK: finished building module 'B'
+// CHECK: finished building module 'A'
Index: clang/include/clang/Basic/DiagnosticSerializationKinds.td
===
--- clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -75,6 +75,7 @@
 
 def remark_module_import : Remark<
   "importing module '%0'%select{| into '%3'}2 from '%1'">,
+  ShowInSystemHeader,
   InGroup;
 
 def err_imported_module_not_found : Error<
Index: clang/include/clang/Basic/DiagnosticFrontendKinds.td
===
--- clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -241,8 +241,10 @@
 def note_module_def_undef_here : Note<
   "macro was %select{defined|#undef'd}0 here">;
 def remark_module_build : Remark<"building module '%0' as '%1'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_build_done : Remark<"finished building module '%0'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_lock : Remark<"locking '%0' to build module '%1'">,
   InGroup;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ba6e747 - [clang] Set ShowInSystemHeader for module-build and module-import remarks

2023-03-31 Thread Dave Lee via cfe-commits

Author: Dave Lee
Date: 2023-03-31T15:56:09-07:00
New Revision: ba6e747f9b05e541e88822e1dbd6bd5424cfe2fb

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

LOG: [clang] Set ShowInSystemHeader for module-build and module-import remarks

Without this change, the use of `-Rmodule-build` and `-Rmodule-import` only
produces diagnostics for modules built or imported by non-system code.

For example, if a project source file requires the Foundation module to be
built, then `-Rmodule-build` will show a single diagnostic for Foundation, but
not in turn for any of Foundation's (direct or indirect) dependencies. This is
because the locations of those transitive module builds are initiated from
system headers, which are ignored by default. When wanting to observe module
building/importing, the system modules can represent a significant amount of
module diagnostics, and I think should be shown by default when
`-Rmodule-build` and `-Rmodule-import` are specified.

I noticed some other remarks use `ShowInSystemHeader`.

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

Added: 
clang/test/Modules/system-Rmodule-build.m

Modified: 
clang/include/clang/Basic/DiagnosticFrontendKinds.td
clang/include/clang/Basic/DiagnosticSerializationKinds.td

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index 9f788380f4337..3a71d67d72792 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -241,8 +241,10 @@ def warn_module_config_macro_undef : Warning<
 def note_module_def_undef_here : Note<
   "macro was %select{defined|#undef'd}0 here">;
 def remark_module_build : Remark<"building module '%0' as '%1'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_build_done : Remark<"finished building module '%0'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_lock : Remark<"locking '%0' to build module '%1'">,
   InGroup;

diff  --git a/clang/include/clang/Basic/DiagnosticSerializationKinds.td 
b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
index 30ee291d0d85e..919472417fe98 100644
--- a/clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -75,6 +75,7 @@ def note_module_file_conflict : Note<
 
 def remark_module_import : Remark<
   "importing module '%0'%select{| into '%3'}2 from '%1'">,
+  ShowInSystemHeader,
   InGroup;
 
 def err_imported_module_not_found : Error<

diff  --git a/clang/test/Modules/system-Rmodule-build.m 
b/clang/test/Modules/system-Rmodule-build.m
new file mode 100644
index 0..f631487befd20
--- /dev/null
+++ b/clang/test/Modules/system-Rmodule-build.m
@@ -0,0 +1,16 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t/sys
+// RUN: echo '#include ' > %t/sys/A.h
+// RUN: echo '' > %t/sys/B.h
+// RUN: echo 'module A { header "A.h" }' > %t/sys/module.modulemap
+// RUN: echo 'module B { header "B.h" }' >> %t/sys/module.modulemap
+
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t 
-fsyntax-only %s \
+// RUN:-isystem %t/sys -Rmodule-build 2>&1 | FileCheck %s
+
+@import A;
+
+// CHECK: building module 'A' as
+// CHECK: building module 'B' as
+// CHECK: finished building module 'B'
+// CHECK: finished building module 'A'



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


[PATCH] D139653: [clang] Set ShowInSystemHeader for module-build and module-import remarks

2023-03-31 Thread Dave Lee via Phabricator via cfe-commits
kastiglione updated this revision to Diff 510141.
kastiglione added a comment.

minor cleanup of test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139653

Files:
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Basic/DiagnosticSerializationKinds.td
  clang/test/Modules/system-Rmodule-build.m


Index: clang/test/Modules/system-Rmodule-build.m
===
--- /dev/null
+++ clang/test/Modules/system-Rmodule-build.m
@@ -0,0 +1,16 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t/sys
+// RUN: echo '#include ' > %t/sys/A.h
+// RUN: echo '' > %t/sys/B.h
+// RUN: echo 'module A { header "A.h" }' > %t/sys/module.modulemap
+// RUN: echo 'module B { header "B.h" }' >> %t/sys/module.modulemap
+
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t 
-fsyntax-only %s \
+// RUN:-isystem %t/sys -Rmodule-build 2>&1 | FileCheck %s
+
+@import A;
+
+// CHECK: building module 'A' as
+// CHECK: building module 'B' as
+// CHECK: finished building module 'B'
+// CHECK: finished building module 'A'
Index: clang/include/clang/Basic/DiagnosticSerializationKinds.td
===
--- clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -75,6 +75,7 @@
 
 def remark_module_import : Remark<
   "importing module '%0'%select{| into '%3'}2 from '%1'">,
+  ShowInSystemHeader,
   InGroup;
 
 def err_imported_module_not_found : Error<
Index: clang/include/clang/Basic/DiagnosticFrontendKinds.td
===
--- clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -241,8 +241,10 @@
 def note_module_def_undef_here : Note<
   "macro was %select{defined|#undef'd}0 here">;
 def remark_module_build : Remark<"building module '%0' as '%1'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_build_done : Remark<"finished building module '%0'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_lock : Remark<"locking '%0' to build module '%1'">,
   InGroup;


Index: clang/test/Modules/system-Rmodule-build.m
===
--- /dev/null
+++ clang/test/Modules/system-Rmodule-build.m
@@ -0,0 +1,16 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t/sys
+// RUN: echo '#include ' > %t/sys/A.h
+// RUN: echo '' > %t/sys/B.h
+// RUN: echo 'module A { header "A.h" }' > %t/sys/module.modulemap
+// RUN: echo 'module B { header "B.h" }' >> %t/sys/module.modulemap
+
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -fsyntax-only %s \
+// RUN:-isystem %t/sys -Rmodule-build 2>&1 | FileCheck %s
+
+@import A;
+
+// CHECK: building module 'A' as
+// CHECK: building module 'B' as
+// CHECK: finished building module 'B'
+// CHECK: finished building module 'A'
Index: clang/include/clang/Basic/DiagnosticSerializationKinds.td
===
--- clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -75,6 +75,7 @@
 
 def remark_module_import : Remark<
   "importing module '%0'%select{| into '%3'}2 from '%1'">,
+  ShowInSystemHeader,
   InGroup;
 
 def err_imported_module_not_found : Error<
Index: clang/include/clang/Basic/DiagnosticFrontendKinds.td
===
--- clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -241,8 +241,10 @@
 def note_module_def_undef_here : Note<
   "macro was %select{defined|#undef'd}0 here">;
 def remark_module_build : Remark<"building module '%0' as '%1'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_build_done : Remark<"finished building module '%0'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_lock : Remark<"locking '%0' to build module '%1'">,
   InGroup;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D147360: [AArch64] Add IR intrinsic for vbsl*

2023-03-31 Thread Pranav Kant via Phabricator via cfe-commits
pranavk created this revision.
Herald added subscribers: hiraditya, kristof.beyls.
Herald added a project: All.
pranavk requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147360

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/aarch64-neon-intrinsics.c
  clang/test/CodeGen/aarch64-poly64.c
  clang/test/CodeGen/aarch64-v8.2a-neon-intrinsics.c
  llvm/include/llvm/IR/IntrinsicsAArch64.td
  llvm/lib/Target/AArch64/AArch64InstrInfo.td
  llvm/test/CodeGen/AArch64/aarch64-vbsl.ll

Index: llvm/test/CodeGen/AArch64/aarch64-vbsl.ll
===
--- /dev/null
+++ llvm/test/CodeGen/AArch64/aarch64-vbsl.ll
@@ -0,0 +1,21 @@
+; RUN: llc -mtriple=aarch64-none-linux-gnu -mattr=+neon < %s -o -| FileCheck %s
+
+define <8 x i8> @vbsl.v8i8(<8 x i8> %v0, <8 x i8> %v1, <8 x i8> %v2) {
+entry:
+; CHECK-LABEL: vbsl.v8i8
+; CHECK: bsl   v0.8b, v1.8b, v2.8b
+  %vbsl.i = tail call <8 x i8> @llvm.aarch64.neon.bsl.v8i8(<8 x i8> %v0, <8 x i8> %v1, <8 x i8> %v2)
+  ret <8 x i8> %vbsl.i
+}
+
+define <16 x i8> @vbslq.v8i8(<16 x i8> %v0, <16 x i8> %v1, <16 x i8> %v2) {
+entry:
+; CHECK-LABEL: vbslq.v8i8
+; CHECK: bsl   v0.16b, v1.16b, v2.16b
+  %vbsl.i = tail call <16 x i8> @llvm.aarch64.neon.bsl.v16i8(<16 x i8> %v0, <16 x i8> %v1, <16 x i8> %v2)
+  ret <16 x i8> %vbsl.i
+}
+
+declare <8 x i8> @llvm.aarch64.neon.bsl.v8i8(<8 x i8>, <8 x i8>, <8 x i8>) #2
+declare <16 x i8> @llvm.aarch64.neon.bsl.v16i8(<16 x i8>, <16 x i8>, <16 x i8>) #2
+
Index: llvm/lib/Target/AArch64/AArch64InstrInfo.td
===
--- llvm/lib/Target/AArch64/AArch64InstrInfo.td
+++ llvm/lib/Target/AArch64/AArch64InstrInfo.td
@@ -4966,7 +4966,7 @@
 // It is expanded into BSL/BIT/BIF after register allocation.
 defm BSP : SIMDLogicalThreeVectorPseudo>;
-defm BSL : SIMDLogicalThreeVectorTied<1, 0b01, "bsl">;
+defm BSL : SIMDLogicalThreeVectorTied<1, 0b01, "bsl", int_aarch64_neon_bsl>;
 defm BIT : SIMDLogicalThreeVectorTied<1, 0b10, "bit", AArch64bit>;
 defm BIF : SIMDLogicalThreeVectorTied<1, 0b11, "bif">;
 
Index: llvm/include/llvm/IR/IntrinsicsAArch64.td
===
--- llvm/include/llvm/IR/IntrinsicsAArch64.td
+++ llvm/include/llvm/IR/IntrinsicsAArch64.td
@@ -492,6 +492,8 @@
   def int_aarch64_neon_frint64x : AdvSIMD_1FloatArg_Intrinsic;
   def int_aarch64_neon_frint64z : AdvSIMD_1FloatArg_Intrinsic;
 
+  def int_aarch64_neon_bsl : AdvSIMD_3VectorArg_Intrinsic;
+
   // Scalar FP->Int conversions
 
   // Vector FP Inexact Narrowing
Index: clang/test/CodeGen/aarch64-v8.2a-neon-intrinsics.c
===
--- clang/test/CodeGen/aarch64-v8.2a-neon-intrinsics.c
+++ clang/test/CodeGen/aarch64-v8.2a-neon-intrinsics.c
@@ -2011,14 +2011,8 @@
 // CHECK-NEXT:[[TMP0:%.*]] = bitcast <4 x i16> [[A]] to <8 x i8>
 // CHECK-NEXT:[[TMP1:%.*]] = bitcast <4 x half> [[B]] to <8 x i8>
 // CHECK-NEXT:[[TMP2:%.*]] = bitcast <4 x half> [[C]] to <8 x i8>
-// CHECK-NEXT:[[VBSL1_I:%.*]] = bitcast <8 x i8> [[TMP1]] to <4 x i16>
-// CHECK-NEXT:[[VBSL2_I:%.*]] = bitcast <8 x i8> [[TMP2]] to <4 x i16>
-// CHECK-NEXT:[[VBSL3_I:%.*]] = and <4 x i16> [[A]], [[VBSL1_I]]
-// CHECK-NEXT:[[TMP3:%.*]] = xor <4 x i16> [[A]], 
-// CHECK-NEXT:[[VBSL4_I:%.*]] = and <4 x i16> [[TMP3]], [[VBSL2_I]]
-// CHECK-NEXT:[[VBSL5_I:%.*]] = or <4 x i16> [[VBSL3_I]], [[VBSL4_I]]
-// CHECK-NEXT:[[TMP4:%.*]] = bitcast <4 x i16> [[VBSL5_I]] to <4 x half>
-// CHECK-NEXT:ret <4 x half> [[TMP4]]
+// CHECK-NEXT:[[VBSL_I:%.*]] = call <8 x i8> @llvm.aarch64.neon.bsl.v8i8(<8 x i8> [[TMP0]], <8 x i8> [[TMP1]], <8 x i8> [[TMP2]])
+// CHECK-NEXT:[[TMP3:%.*]] = bitcast <8 x i8> [[VBSL_I]] to <4 x half>
 //
 float16x4_t test_vbsl_f16(uint16x4_t a, float16x4_t b, float16x4_t c) {
   return vbsl_f16(a, b, c);
@@ -2030,14 +2024,9 @@
 // CHECK-NEXT:[[TMP0:%.*]] = bitcast <8 x i16> [[A]] to <16 x i8>
 // CHECK-NEXT:[[TMP1:%.*]] = bitcast <8 x half> [[B]] to <16 x i8>
 // CHECK-NEXT:[[TMP2:%.*]] = bitcast <8 x half> [[C]] to <16 x i8>
-// CHECK-NEXT:[[VBSL1_I:%.*]] = bitcast <16 x i8> [[TMP1]] to <8 x i16>
-// CHECK-NEXT:[[VBSL2_I:%.*]] = bitcast <16 x i8> [[TMP2]] to <8 x i16>
-// CHECK-NEXT:[[VBSL3_I:%.*]] = and <8 x i16> [[A]], [[VBSL1_I]]
-// CHECK-NEXT:[[TMP3:%.*]] = xor <8 x i16> [[A]], 
-// CHECK-NEXT:[[VBSL4_I:%.*]] = and <8 x i16> [[TMP3]], [[VBSL2_I]]
-// CHECK-NEXT:[[VBSL5_I:%.*]] = or <8 x i16> [[VBSL3_I]], [[VBSL4_I]]
-// CHECK-NEXT:[[TMP4:%.*]] = bitcast <8 x i16> [[VBSL5_I]] to <8 x half>
-// CHECK-NEXT:ret <8 x half> [[TMP4]]
+// CHECK-NEXT:[[VBSL_I:%.*]] = call <16 x i8> @llvm.aarch64.neon.bsl.v16i8(<16 x i8> %0, <16 x i8> %1, <16 x i8> %2)
+// CHECK-NEXT:[[TMP3:%

[PATCH] D139653: [clang] Set ShowInSystemHeader for module-build and module-import remarks

2023-03-31 Thread Dave Lee via Phabricator via cfe-commits
kastiglione updated this revision to Diff 510138.
kastiglione added a comment.

Add a test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139653

Files:
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Basic/DiagnosticSerializationKinds.td
  clang/test/Modules/system-Rmodule-build.m


Index: clang/test/Modules/system-Rmodule-build.m
===
--- /dev/null
+++ clang/test/Modules/system-Rmodule-build.m
@@ -0,0 +1,16 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t/sys
+// RUN: echo '#include  // #1' > %t/sys/A.h
+// RUN: echo '' > %t/sys/B.h
+// RUN: echo 'module A { header "A.h" }' > %t/sys/module.modulemap
+// RUN: echo 'module B { header "B.h" }' >> %t/sys/module.modulemap
+
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t 
-fsyntax-only %s \
+// RUN:-isystem %t/sys -Rmodule-build 2>&1 | FileCheck %s
+
+@import A;
+
+// CHECK: building module 'A' as
+// CHECK: building module 'B' as
+// CHECK: finished building module 'B'
+// CHECK: finished building module 'A'
Index: clang/include/clang/Basic/DiagnosticSerializationKinds.td
===
--- clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -75,6 +75,7 @@
 
 def remark_module_import : Remark<
   "importing module '%0'%select{| into '%3'}2 from '%1'">,
+  ShowInSystemHeader,
   InGroup;
 
 def err_imported_module_not_found : Error<
Index: clang/include/clang/Basic/DiagnosticFrontendKinds.td
===
--- clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -241,8 +241,10 @@
 def note_module_def_undef_here : Note<
   "macro was %select{defined|#undef'd}0 here">;
 def remark_module_build : Remark<"building module '%0' as '%1'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_build_done : Remark<"finished building module '%0'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_lock : Remark<"locking '%0' to build module '%1'">,
   InGroup;


Index: clang/test/Modules/system-Rmodule-build.m
===
--- /dev/null
+++ clang/test/Modules/system-Rmodule-build.m
@@ -0,0 +1,16 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t/sys
+// RUN: echo '#include  // #1' > %t/sys/A.h
+// RUN: echo '' > %t/sys/B.h
+// RUN: echo 'module A { header "A.h" }' > %t/sys/module.modulemap
+// RUN: echo 'module B { header "B.h" }' >> %t/sys/module.modulemap
+
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -fsyntax-only %s \
+// RUN:-isystem %t/sys -Rmodule-build 2>&1 | FileCheck %s
+
+@import A;
+
+// CHECK: building module 'A' as
+// CHECK: building module 'B' as
+// CHECK: finished building module 'B'
+// CHECK: finished building module 'A'
Index: clang/include/clang/Basic/DiagnosticSerializationKinds.td
===
--- clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -75,6 +75,7 @@
 
 def remark_module_import : Remark<
   "importing module '%0'%select{| into '%3'}2 from '%1'">,
+  ShowInSystemHeader,
   InGroup;
 
 def err_imported_module_not_found : Error<
Index: clang/include/clang/Basic/DiagnosticFrontendKinds.td
===
--- clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -241,8 +241,10 @@
 def note_module_def_undef_here : Note<
   "macro was %select{defined|#undef'd}0 here">;
 def remark_module_build : Remark<"building module '%0' as '%1'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_build_done : Remark<"finished building module '%0'">,
+  ShowInSystemHeader,
   InGroup;
 def remark_module_lock : Remark<"locking '%0' to build module '%1'">,
   InGroup;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D147315: [clang-tidy] support unscoped enumerations in readability-static-accessed-through-instance

2023-03-31 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL requested changes to this revision.
PiotrZSL added a comment.
This revision now requires changes to proceed.

Ok, you right.
Fix all open issues, and update commit message to be more detailed.
Except that, LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147315

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


[PATCH] D142907: LangRef: Add "dynamic" option to "denormal-fp-math"

2023-03-31 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

ping


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

https://reviews.llvm.org/D142907

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


[PATCH] D147315: [clang-tidy] support unscoped enumerations in readability-static-accessed-through-instance

2023-03-31 Thread Congcong Cai via Phabricator via cfe-commits
HerrCai0907 added a comment.

In D147315#4236403 , @PiotrZSL wrote:

> Add test with scoped enums, to validate that it works correctly.
> In theory this change should suport them also.

scoped enum not support to visit by member. `EnumName::` is needed for scoped 
enum. And `ins.EnumName` is invalid.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147315

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


[PATCH] D140722: [OpenMP] Prefix outlined and reduction func names with original func's name

2023-03-31 Thread Jan-Patrick Lehr via Phabricator via cfe-commits
jplehr added a comment.

In D140722#4219182 , 
@nextsilicon-itay-bookstein wrote:

> Minor fix to the clang/CodeGen/ppc64le-varargs-f128.c test.
>
> @jdoerfert Does the PR CI run these, or are there build bots that cover the 
> different target-offloading variants? Can I somehow check this prior to 
> merging without having all hardware variants on-hand?

There is a buildbot for AMDGPU and the x86 fallback. Not sure about the status 
of the NVPTX openmp offloading buildbot.
What hardware do you have access to? I could potentially give it a try on 
AMDGPU prior to merging.


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

https://reviews.llvm.org/D140722

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


[PATCH] D144347: [clang-tidy] Add readability-forward-usage check

2023-03-31 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL marked an inline comment as done.
PiotrZSL added a comment.

I will leave this review open for 1 more week, in case someone have some 
comments, and by someone I mean you @carlosgalvezp.




Comment at: clang-tools-extra/clang-tidy/readability/ForwardUsageCheck.cpp:98
+  callExpr(
+  unless(isExpansionInSystemHeader()), argumentCountIs(1U),
+  IgnoreDependentExpresions

ccotter wrote:
> Curious, why have `isExpansionInSystemHeader` here, rather than rely on the 
> `system-headers` command line option. Is that a matter of performance (this 
> tool is not likely to apply for system headers)?
isExpansionInSystemHeader works on check level, when --system-headers on 
diagnostic level. This mean that check will be executed, and warning will be 
excluded during call to diag.
For some checks this can be expensive. 
Read more here: 
https://discourse.llvm.org/t/rfc-exclude-issues-from-system-headers-as-early-as-posible/68483


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144347

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


[PATCH] D141389: [DFSAN] Add support for strnlen, strncat, strsep, sscanf and _tolower

2023-03-31 Thread Tomasz Kuchta via Phabricator via cfe-commits
tkuchta added inline comments.



Comment at: compiler-rt/lib/dfsan/dfsan_custom.cpp:221
+  if (flags().strict_data_dependencies) {
+*ret_label = res ? dfsan_read_label(base, sizeof(base)) : 0;
+  } else {

browneee wrote:
> `base, sizeof(base)` does not make sense - the size does not correspond to 
> the pointer used.
> 
> Either
> ```
> dfsan_read_label(base, sizeof(*base))   // first byte pointed to by base
> dfsan_read_label(base, strlen(base)) // whole string pointed to by base
> dfsan_read_label(&base, sizeof(base))  // the base pointer
> ```
> 
> In this case I think we want the base pointer.
> 
> `dfsan_read_label(&base, sizeof(base))`  // the base pointer
> should be equivalent to doing
> `dfsan_label base_label = dfsan_read_label(s, sizeof(*s))`  up at the start 
> of the function, just after we declare base then use `base_label` here.
> 
> Lets go with the second option to avoid taking the address of a variable.
> 
> This is semantically equivalent to my first suggestion: 
> `dfsan_get_label(base) == dfsan_read_label(&base, sizeof(base)) == 
> base_label`.
> Sorry I didn't consider the other constraints (no dfsan_get_label in this 
> file because the pass is not run on this code; avoid taking address of 
> variable) and suggest this in the first place.
Thank you for your comments! Just to clarify:
If we have strict data dependencies we would like *ret_label to be related to 
the taints of the contents of the string, is that correct? Should we use the 
base_label there too? My understanding is that base_label represents a taint 
applied to the pointer, not to the data? 

In other words, would that be correct to:
1) use taints of the string data in the first case (strict dependencies) -> 
therefore no base_label there as it represents the taint of the pointer
2) use the taints of the string data + the taints of the pointer in the second 
case -> therefore using base_label there


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

https://reviews.llvm.org/D141389

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


[PATCH] D147357: [clang-tidy] Add bugprone-optional-value-conversion check

2023-03-31 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL updated this revision to Diff 510132.
PiotrZSL added a comment.

Fix doc


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147357

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/OptionalValueConversionCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/OptionalValueConversionCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone/optional-value-conversion.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/optional-value-conversion.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/optional-value-conversion.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/optional-value-conversion.cpp
@@ -0,0 +1,52 @@
+// RUN: %check_clang_tidy -std=c++17-or-later %s bugprone-optional-value-conversion %t
+
+namespace std {
+  template
+  struct optional
+  {
+  constexpr optional() noexcept;
+  constexpr optional(T&&) noexcept;
+  constexpr optional(const T&) noexcept;
+  template
+  constexpr optional(U&&) noexcept;
+  const T &operator*() const;
+  const T &value() const;
+  T value_or(T) const;
+  };
+}
+
+void takeOptionalValue(std::optional);
+void takeOptionalRef(const std::optional&);
+void takeOtherOptional(std::optional);
+
+void incorrect(std::optional param)
+{
+  takeOptionalValue(*param);
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: conversion from 'std::optional' into 'int' and back into 'std::optional', remove potentially error-prone optional dereference [bugprone-optional-value-conversion]
+
+  takeOptionalValue(param.value());
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: conversion from 'std::optional' into 'int' and back into 'std::optional', remove potentially error-prone optional dereference [bugprone-optional-value-conversion]
+
+  takeOptionalRef(*param);
+  // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: conversion from 'std::optional' into 'int' and back into 'std::optional', remove potentially error-prone optional dereference [bugprone-optional-value-conversion]
+
+  takeOptionalRef(param.value());
+  // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: conversion from 'std::optional' into 'int' and back into 'std::optional', remove potentially error-prone optional dereference [bugprone-optional-value-conversion]
+  std::optional p = *param;
+  // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: conversion from 'std::optional' into 'int' and back into 'std::optional', remove potentially error-prone optional dereference [bugprone-optional-value-conversion]
+}
+
+void correct(std::optional param)
+{
+  takeOtherOptional(*param);
+
+  takeOtherOptional(param.value());
+
+  takeOtherOptional(param.value_or(5U));
+
+  std::optional p = *param;
+
+  takeOptionalValue(param.value_or(5U));
+
+  takeOptionalRef(param.value_or(5U));
+}
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
@@ -105,6 +105,7 @@
`bugprone-multiple-statement-macro `_,
`bugprone-no-escape `_,
`bugprone-not-null-terminated-result `_, "Yes"
+   `bugprone-optional-value-conversion `_,
`bugprone-parent-virtual-call `_, "Yes"
`bugprone-posix-return `_, "Yes"
`bugprone-redundant-branch-condition `_, "Yes"
Index: clang-tools-extra/docs/clang-tidy/checks/bugprone/optional-value-conversion.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/bugprone/optional-value-conversion.rst
@@ -0,0 +1,49 @@
+.. title:: clang-tidy - bugprone-optional-value-conversion
+
+bugprone-optional-value-conversion
+==
+
+Detects potentially unintentional and redundant conversions where a value is
+extracted from an optional-like type and then used to create a new instance of
+the same optional-like type.
+
+These conversions might be the result of developer oversight, leftovers from
+code refactoring, or other situations that could lead to unintended exceptions
+or cases where the resulting optional is always initialized, which might be
+unexpected behavior.
+
+.. code-block:: c++
+
+#include 
+
+void print(std::optional);
+
+int main()
+{
+  std::optional opt;
+  // ...
+
+  // Unintentional conversion from std::optional to int and back to
+  // std::optional:
+  print(opt.value());
+
+  // ...
+}
+
+Value extraction using ``operator *`` is matched by default.
+Check does not provide auto-fixes.
+
+Options:
+
+
+.. option:: OptionalTypes
+
+Semicolon-separated list of (fully qualified) optional ty

[PATCH] D147357: [clang-tidy] Add bugprone-optional-value-conversion check

2023-03-31 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added a comment.

There are 37 findings in llvm repository:

1. clang-tools-extra/clang-tidy/ClangTidyCheck.cpp:96:12: warning: conversion 
from 'std::optional' into 'bool' and back into 'std::optional', 
remove potentially error-prone optional dereference 
[bugprone-optional-value-conversion]
2. clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp:65:12: warning: 
conversion from 'std::optional>' into 
'std::basic_string' and back into 
'std::optional>', remove potentially error-prone 
optional dereference [bugprone-optional-value-conversion]
3. clang/lib/AST/Interp/Program.cpp:173:12: warning: conversion from 
'std::optional' into 'unsigned int' and back into 
'std::optional', remove potentially error-prone optional 
dereference [bugprone-optional-value-conversion]
4. clang/lib/Analysis/PathDiagnostic.cpp:323:14: warning: conversion from 
'std::optional' into 'bool' and back into 'std::optional', remove 
potentially error-prone optional dereference 
[bugprone-optional-value-conversion]
5. clang/lib/Frontend/Rewrite/InclusionRewriter.cpp:253:7: warning: conversion 
from 'std::optional' into 'llvm::MemoryBufferRef' and 
back into 'std::optional', remove potentially 
error-prone optional dereference [bugprone-optional-value-conversion]
6. clang/lib/Sema/Scope.cpp:190:25: warning: conversion from 
'std::optional' into 'clang::VarDecl *' and back into 
'std::optional', remove potentially error-prone optional 
dereference [bugprone-optional-value-conversion]
7. clang/lib/Sema/TreeTransform.h:13915:9: warning: conversion from 
'std::optional' into 'unsigned int' and back into 
'std::optional', remove potentially error-prone optional 
dereference [bugprone-optional-value-conversion]
8. clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:440:16: warning: 
conversion from 'std::optional' into 'int' and back into 
'std::optional', remove potentially error-prone optional dereference 
[bugprone-optional-value-conversion]
9. clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp:125:10: 
warning: conversion from 'std::optional' into 'bool' and back into 
'std::optional', remove potentially error-prone optional dereference 
[bugprone-optional-value-conversion]
10. clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1573:10: warning: conversion 
from 'std::optional' into 
'clang::ento::nonloc::LazyCompoundVal' and back into 
'std::optional', remove potentially 
error-prone optional dereference [bugprone-optional-value-conversion]
11. clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1784:12: warning: conversion 
from 'std::optional' into 'clang::ento::SVal' and back into 
'std::optional', remove potentially error-prone optional 
dereference [bugprone-optional-value-conversion]
12. clang/lib/Tooling/InterpolatingCompilationDatabase.cpp:189:16: warning: 
conversion from 'std::optional' into 
'clang::driver::types::ID' and back into 
'std::optional', remove potentially error-prone 
optional dereference [bugprone-optional-value-conversion]
13. lldb/source/Breakpoint/BreakpointResolver.cpp:233:33: warning: conversion 
from 'std::optional' into 'unsigned short' and back into 
'std::optional', remove potentially error-prone optional 
dereference [bugprone-optional-value-conversion]
14. lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp:1362:53: 
warning: conversion from 'std::optional' into 'unsigned long' 
and back into 'std::optional', remove potentially error-prone 
optional dereference [bugprone-optional-value-conversion]
15. llvm/lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.cpp:4119:12: warning: 
conversion from 'std::optional' into 
'LiveDebugValues::ValueIDNum' and back into 
'std::optional', remove potentially error-prone 
optional dereference [bugprone-optional-value-conversion]
16. llvm/lib/DWARFLinker/DWARFLinker.cpp:1191:14: warning: conversion from 
'std::optional' into 'unsigned long' and back into 
'std::optional', remove potentially error-prone optional 
dereference [bugprone-optional-value-conversion]
17. llvm/lib/DebugInfo/DWARF/DWARFContext.cpp:1305:31: warning: conversion from 
'std::optional' into 'long' and back into 'std::optional', remove 
potentially error-prone optional dereference 
[bugprone-optional-value-conversion]
18. llvm/lib/DebugInfo/DWARF/DWARFContext.cpp:1322:62: warning: conversion from 
'std::optional' into 'llvm::DWARFFormValue' and back into 
'std::optional', remove potentially error-prone optional 
dereference [bugprone-optional-value-conversion]
19. llvm/lib/DebugInfo/Symbolize/Markup.cpp:67:14: warning: conversion from 
'std::optional' into 'llvm::symbolize::MarkupNode' 
and back into 'std::optional', remove potentially 
error-prone optional dereference [bugprone-optional-value-conversion]
20. llvm/lib/DebugInfo/Symbolize/MarkupFilter.cpp:425:13: warning: conversion 
from 'std::optional' into 
'llvm::raw_ostream::Colors' and back into 
'std::optional', remove potentially error-prone 
optional dereference [bugprone-optional-value-conversion]
21. llvm/lib/Interfa

[PATCH] D147357: [clang-tidy] Add bugprone-optional-value-conversion check

2023-03-31 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone/optional-value-conversion.rst:46
+expressions that match the methods.
+Default value is `"::value$;::get$`.

Unintended quote in value.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147357

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


[PATCH] D144347: [clang-tidy] Add readability-forward-usage check

2023-03-31 Thread Chris Cotter via Phabricator via cfe-commits
ccotter accepted this revision.
ccotter added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clang-tidy/readability/ForwardUsageCheck.cpp:98
+  callExpr(
+  unless(isExpansionInSystemHeader()), argumentCountIs(1U),
+  IgnoreDependentExpresions

Curious, why have `isExpansionInSystemHeader` here, rather than rely on the 
`system-headers` command line option. Is that a matter of performance (this 
tool is not likely to apply for system headers)?



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability/forward-usage.rst:98
+
+.. option:: DisableTypeMismatchSuggestion
+

PiotrZSL wrote:
> ccotter wrote:
> > Curious what others thing but I think the tool should by default not remove 
> > or replace `forward` with static_cast.  When an author has written 
> > `forward`, there is a good chance they intended to forward something (e.g., 
> > they forgot to use `&&` in the parameter declaration). My hypothesis is 
> > that it's more likely the author intended to forward something, rather than 
> > than they were trying to use it as a cast (but had not intention of forward 
> > - why else would they have typed it out?). In this case, I think it merits 
> > manual review by default (so the tool should always warn, but without the 
> > fixits by default).
> No, in this case if they used forward, they used this with different type, 
> not adding & is not sufficient to trigger this case.
> 
> In theory we could, create alias bugprone-std-forward that would redirect to 
> this check, but would set DisableTypeMismatchSuggestion to false, and would 
> set DisableRemoveSuggestion & DisableMoveSuggestion to true.
> 
> In such case we could have readability check that would just suggest remove 
> of std::forward or usage of std::move, and bugprone check that would only 
> warn of casts between different types.
> 
Makes sense to me. Happy to work on that once this is merged.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144347

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


[PATCH] D147357: [clang-tidy] Add bugprone-optional-value-conversion check

2023-03-31 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL created this revision.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a reviewer: njames93.
Herald added a project: All.
PiotrZSL requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Detects potentially unintentional and redundant conversions where a value is
extracted from an optional-like type and then used to create a new instance of
the same optional-like type.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147357

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/OptionalValueConversionCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/OptionalValueConversionCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone/optional-value-conversion.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/optional-value-conversion.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/optional-value-conversion.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/optional-value-conversion.cpp
@@ -0,0 +1,52 @@
+// RUN: %check_clang_tidy -std=c++17-or-later %s bugprone-optional-value-conversion %t
+
+namespace std {
+  template
+  struct optional
+  {
+  constexpr optional() noexcept;
+  constexpr optional(T&&) noexcept;
+  constexpr optional(const T&) noexcept;
+  template
+  constexpr optional(U&&) noexcept;
+  const T &operator*() const;
+  const T &value() const;
+  T value_or(T) const;
+  };
+}
+
+void takeOptionalValue(std::optional);
+void takeOptionalRef(const std::optional&);
+void takeOtherOptional(std::optional);
+
+void incorrect(std::optional param)
+{
+  takeOptionalValue(*param);
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: conversion from 'std::optional' into 'int' and back into 'std::optional', remove potentially error-prone optional dereference [bugprone-optional-value-conversion]
+
+  takeOptionalValue(param.value());
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: conversion from 'std::optional' into 'int' and back into 'std::optional', remove potentially error-prone optional dereference [bugprone-optional-value-conversion]
+
+  takeOptionalRef(*param);
+  // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: conversion from 'std::optional' into 'int' and back into 'std::optional', remove potentially error-prone optional dereference [bugprone-optional-value-conversion]
+
+  takeOptionalRef(param.value());
+  // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: conversion from 'std::optional' into 'int' and back into 'std::optional', remove potentially error-prone optional dereference [bugprone-optional-value-conversion]
+  std::optional p = *param;
+  // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: conversion from 'std::optional' into 'int' and back into 'std::optional', remove potentially error-prone optional dereference [bugprone-optional-value-conversion]
+}
+
+void correct(std::optional param)
+{
+  takeOtherOptional(*param);
+
+  takeOtherOptional(param.value());
+
+  takeOtherOptional(param.value_or(5U));
+
+  std::optional p = *param;
+
+  takeOptionalValue(param.value_or(5U));
+
+  takeOptionalRef(param.value_or(5U));
+}
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
@@ -105,6 +105,7 @@
`bugprone-multiple-statement-macro `_,
`bugprone-no-escape `_,
`bugprone-not-null-terminated-result `_, "Yes"
+   `bugprone-optional-value-conversion `_,
`bugprone-parent-virtual-call `_, "Yes"
`bugprone-posix-return `_, "Yes"
`bugprone-redundant-branch-condition `_, "Yes"
Index: clang-tools-extra/docs/clang-tidy/checks/bugprone/optional-value-conversion.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/bugprone/optional-value-conversion.rst
@@ -0,0 +1,46 @@
+.. title:: clang-tidy - bugprone-optional-value-conversion
+
+bugprone-optional-value-conversion
+==
+
+Detects potentially unintentional and redundant conversions where a value is
+extracted from an optional-like type and then used to create a new instance of
+the same optional-like type.
+
+These conversions might be the result of developer oversight, leftovers from
+code refactoring, or other situations that could lead to unintended exceptions
+or cases where the resulting optional is always initialized, which might be
+unexpected behavior.
+
+.. code-block:: c++
+
+#include 
+
+void print(std::optional);
+
+int main()
+{
+  std::optional opt;
+  // ...
+
+  // Unintentional conversion from std::option

[PATCH] D147288: [clang][NFC] updates cxx_status for P2113R0

2023-03-31 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb abandoned this revision.
cjdb added a comment.

In D147288#4237413 , @royjacobson 
wrote:

> There was some discussion of this last year in this review: 
> https://reviews.llvm.org/D128750
>
> It's such an edge case that I don't think we should lose sleep about it 
> until/unless the committee finds time to clarify the issue.

I'm okay with this conclusion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147288

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


[PATCH] D144269: [Analyzer] Show "taint originated here" note of alpha.security.taint.TaintPropagation checker at the correct place

2023-03-31 Thread Daniel Krupp via Phabricator via cfe-commits
dkrupp updated this revision to Diff 510108.
dkrupp added a comment.

This is a totally rewritten version of the patch which solely relies on the 
existing "interestingness" utility to track back the taint propagation.  (And  
does not introduce a new FlowID in the ProgramState as requested in the 
reviews.)

-The new version also places a Note, when the taintedness is propagated to an 
argument or to a return value. So it should be easier for the user to follow 
how the taint information is spreading. 
-"The taint originated here" is printed correctly at the taint source function, 
which introduces taintedness. (Main goal of this patch.)

Implementation:
-The createTaintPreTag() function places a NoteTag at the taint propagation 
function calls, if taintedness is propagated. Then at report creation, the 
tainted arguments are marked interesting if propagated taintedness is relevant 
for the bug report.

- The isTainted() function is extended to return the actually tainted 
SymbolRef. This is important to be able to consistently mark relevant symbol 
interesting which carries the taintedness in a complex expression.

-createTaintPostTag(..) function places a NoteTag to the taint generating 
function calls to mark them interesting if they are relevant for a taintedness 
report. So if they propagated taintedness to interesting symbol(s).

The tests are passing and the reports on the open source projects are much 
better understandable than before (twin, tmux, curl):

https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=curl_curl-7_66_0_dkrupp_taint_origin_fix_new&run=tmux_2.6_dkrupp_taint_origin_fix_new&run=twin_v0.8.1_dkrupp_taint_origin_fix_new&is-unique=on&diff-type=New&checker-msg=%2auntrusted%2a&checker-msg=Out%20of%20bound%20memory%20access%20%28index%20is%20tainted%29


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

https://reviews.llvm.org/D144269

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Taint.h
  clang/include/clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h
  clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
  clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/Taint.cpp
  clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
  clang/lib/StaticAnalyzer/Core/CommonBugCategories.cpp
  clang/test/Analysis/taint-diagnostic-visitor.c
  clang/test/Analysis/taint-tester.c

Index: clang/test/Analysis/taint-tester.c
===
--- clang/test/Analysis/taint-tester.c
+++ clang/test/Analysis/taint-tester.c
@@ -122,7 +122,7 @@
   fscanf(pp, "%d", &ii);
   int jj = ii;// expected-warning + {{tainted}}
 
-  fscanf(p, "%d", &ii);
+  fscanf(p, "%d", &ii);// expected-warning + {{tainted}}
   int jj2 = ii;// expected-warning + {{tainted}}
 
   ii = 3;
Index: clang/test/Analysis/taint-diagnostic-visitor.c
===
--- clang/test/Analysis/taint-diagnostic-visitor.c
+++ clang/test/Analysis/taint-diagnostic-visitor.c
@@ -2,13 +2,23 @@
 
 // This file is for testing enhanced diagnostics produced by the GenericTaintChecker
 
+typedef unsigned long size_t;
+struct _IO_FILE;
+typedef struct _IO_FILE FILE;
+
 int scanf(const char *restrict format, ...);
 int system(const char *command);
+char* getenv( const char* env_var );
+size_t strlen( const char* str );
+void *malloc(size_t size );
+char *fgets(char *str, int n, FILE *stream);
+FILE *stdin;
 
 void taintDiagnostic(void)
 {
   char buf[128];
   scanf("%s", buf); // expected-note {{Taint originated here}}
+// expected-note@-1 {{Taint propagated to argument 1}}
   system(buf); // expected-warning {{Untrusted data is passed to a system call}} // expected-note {{Untrusted data is passed to a system call (CERT/STR02-C. Sanitize data passed to complex subsystems)}}
 }
 
@@ -16,6 +26,7 @@
   int index;
   int Array[] = {1, 2, 3, 4, 5};
   scanf("%d", &index); // expected-note {{Taint originated here}}
+   // expected-note@-1 {{Taint propagated to argument 1}}
   return Array[index]; // expected-warning {{Out of bound memory access (index is tainted)}}
// expected-note@-1 {{Out of bound memory access (index is tainted)}}
 }
@@ -23,6 +34,7 @@
 int taintDiagnosticDivZero(int operand) {
   scanf("%d", &operand); // expected-note {{Value assigned to 'operand'}}
  // expected-note@-1 {{Taint originated here}}
+ // expected-note@-2 {{Taint propagated to argument 1}}
   return 10 / operand; // expected-warning {{Division by a tainted value, possibly zero}}
// expected-note@-1 {{Division by a tainted value, possibly zero}}
 }
@@ -31,6 +43,50 @@
   int x;
   scanf("%d", &x); // expected-note {{Value assigned to 'x'}}
// expected-note@-1 {{Taint originated her

[PATCH] D147327: [clang-format] Add option for having one port per line in Verilog

2023-03-31 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks requested changes to this revision.
HazardyKnusperkeks added inline comments.
This revision now requires changes to proceed.



Comment at: clang/include/clang/Format/Format.h:4185
+  /// For Verilog, put each port on its own line in module instantiations.
+  /// \code
+  ///ffnand ff1(.q(),

Can you put the true vs. false in the doc, like on other options?



Comment at: clang/include/clang/Format/Format.h:4192
+  /// \version 17
+  bool VerilogBreakBetweenInstancePorts;
+

V after U



Comment at: clang/lib/Format/TokenAnnotator.cpp:1150
+  if (Style.isVerilog()) {
+const FormatToken *Prev = Tok->getPreviousNonComment(), *Prev2;
+// Identify the parameter list and port list in a module instantiation.





Comment at: clang/lib/Format/TokenAnnotator.cpp:1156-1163
+if (Prev && (Prev2 = Prev->getPreviousNonComment()) &&
+((Prev->is(tok::hash) && Keywords.isVerilogIdentifier(*Prev2)) ||
+ (Keywords.isVerilogIdentifier(*Prev) &&
+  (Prev2->is(tok::r_paren) ||
+   Keywords.isVerilogIdentifier(*Prev2) ||
+   (Prev2->endsSequence(tok::comma, tok::r_paren) &&
+(Prev2 = Prev2->getPreviousNonComment()->MatchingParen) &&

I won't read that.

I think you should go with multiple if statements.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147327

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


[PATCH] D146101: [clang-format] Add BracedInitializerIndentWidth option.

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



Comment at: clang/include/clang/Format/Format.h:949
+  /// If unset, ``ContinuationIndentWidth`` is used.
+  /// \code
+  ///   AlignAfterOpenBracket: AlwaysBreak

jp4a50 wrote:
> MyDeveloperDay wrote:
> > did you check generating the html from the rst? I can never remember if we 
> > need a newline before the \code
> Nope - how do I do that exactly? I would guess a newline is not needed based 
> on other examples.
> did you check generating the html from the rst? I can never remember if we 
> need a newline before the \code





Comment at: clang/lib/Format/ContinuationIndenter.cpp:1659
   opensProtoMessageField(Current, Style)) {
+const FormatToken *NextNonComment = Current.getNextNonComment();
 if (Current.opensBlockOrBlockTypeList(Style)) {

Why did you move it?



Comment at: clang/lib/Format/ContinuationIndenter.cpp:1664-1668
+  const auto BracedInitializerIndentWidth =
+  Style.BracedInitializerIndentWidth
+  ? *Style.BracedInitializerIndentWidth
+  : Style.ContinuationIndentWidth;
+  NewIndent = CurrentState.LastSpace + BracedInitializerIndentWidth;

You can keep the local variable if you want, but please use `value_or`, it 
expresses the intent better.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146101

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


[PATCH] D147288: [clang][NFC] updates cxx_status for P2113R0

2023-03-31 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson added a comment.

There was some discussion of this last year in this review: 
https://reviews.llvm.org/D128750

It's such an edge case that I don't think we should lose sleep about it 
until/unless the committee finds time to clarify the issue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147288

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


[PATCH] D143467: [PowerPC] Add target feature requirement to builtins

2023-03-31 Thread Maryam Moghadas via Phabricator via cfe-commits
maryammo added a comment.

It looks good to me, just added a minor question as I was not able to verify 
that.




Comment at: clang/include/clang/Basic/BuiltinsPPC.def:444
+TARGET_BUILTIN(__builtin_altivec_vcmpnew_p, "iiV4iV4i", "", "power9-vector")
+TARGET_BUILTIN(__builtin_altivec_vcmpned_p, "iiV2LLiV2LLi", "", "altivec")
+

amyk wrote:
> Does this need to be `vsx`?
How do we find the appropriate FEATURE for the above 4 builtins?  (first 3 are 
p9 and the 4th one is altivec)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143467

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


[PATCH] D147349: [C2x] Implement support for empty brace initialization (WG14 N2900 and WG14 N3011)

2023-03-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 510099.
aaron.ballman added a comment.

Oops, previous diff missed a change that was only locally staged. Fixed.


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

https://reviews.llvm.org/D147349

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/CodeGen/CGExprAgg.cpp
  clang/lib/Parse/ParseInit.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaInit.cpp
  clang/test/C/C2x/n2900_n3011.c
  clang/test/C/C2x/n2900_n3011_2.c
  clang/test/Sema/complex-init-list.c
  clang/test/Sema/flexible-array-init.c
  clang/test/Sema/gnu-flags.c
  clang/test/Sema/sizeless-1.c
  clang/test/Sema/vla.c
  clang/test/SemaObjC/property.m
  clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
  clang/www/c_status.html

Index: clang/www/c_status.html
===
--- clang/www/c_status.html
+++ clang/www/c_status.html
@@ -1083,11 +1083,11 @@
 

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2900.htm";>N2900
-Unknown
+Clang 17
   

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3011.htm";>N3011
-Unknown
+Clang 17
   
 
   Not-so-magic: typeof
Index: clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
===
--- clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
+++ clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
@@ -28,37 +28,34 @@
   intel_sub_group_avc_sic_result_t result_sic = ss;
   intel_sub_group_avc_ime_result_single_reference_streamout_t sstreamout = v;
   intel_sub_group_avc_ime_result_dual_reference_streamout_t dstreamin_list = {0x0, 0x1};
-  intel_sub_group_avc_ime_dual_reference_streamin_t dstreamin_list2 = {};
   intel_sub_group_avc_ime_single_reference_streamin_t dstreamin_list3 = {c};
   intel_sub_group_avc_ime_dual_reference_streamin_t dstreamin_list4 = {1};
 #ifdef EXT
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_mce_payload_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_payload_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ref_payload_t' with an expression of incompatible type '__private float'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_sic_payload_t' with an expression of incompatible type '__private struct st'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_mce_result_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_result_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ref_result_t' with an expression of incompatible type '__private float'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_sic_result_t' with an expression of incompatible type '__private struct st'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_result_single_reference_streamout_t' with an expression of incompatible type '__private void *__private'}}
-// expected-warning@-14 {{excess elements in struct initializer}}
-// expected-error@-14 {{scalar initializer cannot be empty}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_single_reference_streamin_t' with an expression of incompatible type '__private char'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_dual_reference_streamin_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_mce_payload_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_ime_payload_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_ref_payload_t' with an expression of incompatible type '__private float'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_sic_payload_t' with an expression of incompatible type '__private struct st'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_mce_result_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_ime_result_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_ref_result_t' with an expression of incompatible type '__private float'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_sic_result_t' with an expression of incompatible type '__private struct st'}}
+// expected-error@-13 {{initializing '

[PATCH] D147349: [C2x] Implement support for empty brace initialization (WG14 N2900 and WG14 N3011)

2023-03-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added reviewers: jyknight, efriedma, erichkeane, cor3ntin, 
clang-language-wg.
Herald added a project: All.
aaron.ballman requested review of this revision.
Herald added a project: clang.

This implements support for allowing `{}` to consistently zero initialize 
objects. We already supported most of this work as a GNU extension, but the C2x 
feature goes beyond what the GNU extension allowed.

The changes in this patch are:

- Removed the `-Wgnu-empty-initializer` warning group. The extension is now a 
C2x extension warning instead. Note that use of `-Wno-gnu-empty-initializer` 
seems to be quite low in the wild 
(https://sourcegraph.com/search?q=context%3Aglobal+-file%3A.*test.*+%22-Wno-gnu-empty-initializer%22&patternType=standard&sm=1&groupBy=repo
 which currently only gives 8 hits total), so this is not expected to be an 
overly disruptive change. But I'm adding the clang vendors review group just in 
case this expectation is wrong.
- Reworded the diagnostic wording to be about a C2x extension, added a pre-C2x 
compat warning
- Allow `{}` to zero initialize a VLA

This functionality is exposed as an extension in all older C modes (same as the 
GNU extension was), but does *not* allow the extension for VLA initialization 
in C++ due to concern about handling non-trivially constructible types.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147349

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/CodeGen/CGExprAgg.cpp
  clang/lib/Parse/ParseInit.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaInit.cpp
  clang/test/C/C2x/n2900_n3011.c
  clang/test/C/C2x/n2900_n3011_2.c
  clang/test/Sema/complex-init-list.c
  clang/test/Sema/flexible-array-init.c
  clang/test/Sema/gnu-flags.c
  clang/test/Sema/sizeless-1.c
  clang/test/Sema/vla.c
  clang/test/SemaObjC/property.m
  clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
  clang/www/c_status.html

Index: clang/www/c_status.html
===
--- clang/www/c_status.html
+++ clang/www/c_status.html
@@ -1083,11 +1083,11 @@
 

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2900.htm";>N2900
-Unknown
+Clang 17
   

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3011.htm";>N3011
-Unknown
+Clang 17
   
 
   Not-so-magic: typeof
Index: clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
===
--- clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
+++ clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
@@ -28,37 +28,34 @@
   intel_sub_group_avc_sic_result_t result_sic = ss;
   intel_sub_group_avc_ime_result_single_reference_streamout_t sstreamout = v;
   intel_sub_group_avc_ime_result_dual_reference_streamout_t dstreamin_list = {0x0, 0x1};
-  intel_sub_group_avc_ime_dual_reference_streamin_t dstreamin_list2 = {};
   intel_sub_group_avc_ime_single_reference_streamin_t dstreamin_list3 = {c};
   intel_sub_group_avc_ime_dual_reference_streamin_t dstreamin_list4 = {1};
 #ifdef EXT
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_mce_payload_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_payload_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ref_payload_t' with an expression of incompatible type '__private float'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_sic_payload_t' with an expression of incompatible type '__private struct st'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_mce_result_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_result_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ref_result_t' with an expression of incompatible type '__private float'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_sic_result_t' with an expression of incompatible type '__private struct st'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_result_single_reference_streamout_t' with an expression of incompatible type '__private void *__private'}}
-// expected-warning@-14 {{excess elements in struct initializer}}
-// expected-error@-14 {{scalar initializer cannot be empty}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_single_reference_streamin_t' with an expression of incompatible type '__private char'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_dual_reference_streamin_t' with an exp

[PATCH] D144603: Disable compiler launcher on external projects and multi stage clang

2023-03-31 Thread David Fang via Phabricator via cfe-commits
fangism added a comment.

What's the current status of this changeset?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144603

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


[PATCH] D143467: [PowerPC] Add target feature requirement to builtins

2023-03-31 Thread Amy Kwan via Phabricator via cfe-commits
amyk added a comment.

Overall looks OK to me, as well. I just had two questions that I wanted to ask.




Comment at: clang/include/clang/Basic/BuiltinsPPC.def:444
+TARGET_BUILTIN(__builtin_altivec_vcmpnew_p, "iiV4iV4i", "", "power9-vector")
+TARGET_BUILTIN(__builtin_altivec_vcmpned_p, "iiV2LLiV2LLi", "", "altivec")
+

Does this need to be `vsx`?



Comment at: clang/include/clang/Basic/BuiltinsPPC.def:820
+TARGET_BUILTIN(__builtin_vsx_xvcvspbf16, "V16UcV16Uc", "", "power10-vector")
+TARGET_BUILTIN(__builtin_vsx_xvcvbf16spn, "V16UcV16Uc", "", "vsx")
 

Should this be `power10-vector`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143467

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


[clang] 43825d1 - Revert "[Assignment Tracking] Enable by default"

2023-03-31 Thread Haowei Wu via cfe-commits

Author: Haowei Wu
Date: 2023-03-31T11:27:18-07:00
New Revision: 43825d19318695be48abe6f042369da00fbb808b

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

LOG: Revert "[Assignment Tracking] Enable by default"

This reverts commit aa32490bfe0b957c4f5583e14304f5e34b2b9bce, which
breaks llvm runtimes builds on armv7 linux.

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/test/CodeGen/assignment-tracking/flag.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 11007c99aa691..0cc7052b67105 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5800,7 +5800,7 @@ def experimental_assignment_tracking_EQ : Joined<["-"], 
"fexperimental-assignmen
   Group, CodeGenOpts<"EnableAssignmentTracking">,
   NormalizedValuesScope<"CodeGenOptions::AssignmentTrackingOpts">,
   Values<"disabled,enabled,forced">, 
NormalizedValues<["Disabled","Enabled","Forced"]>,
-  MarshallingInfoEnum, "Enabled">;
+  MarshallingInfoEnum, "Disabled">;
 
 } // let Flags = [CC1Option, NoDriverOption]
 

diff  --git a/clang/test/CodeGen/assignment-tracking/flag.cpp 
b/clang/test/CodeGen/assignment-tracking/flag.cpp
index 3bd974fe07c6c..aa1f054dae4d7 100644
--- a/clang/test/CodeGen/assignment-tracking/flag.cpp
+++ b/clang/test/CodeGen/assignment-tracking/flag.cpp
@@ -8,10 +8,10 @@
 // RUN: -emit-llvm  %s -o - -fexperimental-assignment-tracking=disabled 
-O1\
 // RUN: | FileCheck %s --check-prefixes=DISABLE
 
- Enabled by default:
+ Disabled by default:
 // RUN: %clang_cc1 -triple x86_64-none-linux-gnu -debug-info-kind=standalone   
\
 // RUN: -emit-llvm  %s -o - -O1
\
-// RUN: | FileCheck %s --check-prefixes=ENABLE
+// RUN: | FileCheck %s --check-prefixes=DISABLE
 
  Disabled at O0 unless forced.
 // RUN: %clang_cc1 -triple x86_64-none-linux-gnu -debug-info-kind=standalone   
\



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


[PATCH] D143467: [PowerPC] Add target feature requirement to builtins

2023-03-31 Thread Stefan Pintilie via Phabricator via cfe-commits
stefanp added a comment.

Overall I think that this looks fine to me as well.
I had a couple of minor comments and you may decide that you don't need to do 
either one so if that's the case just mention why in a comment and I will 
approve the patch.




Comment at: clang/include/clang/Basic/BuiltinsPPC.def:987
+
+UNALIASED_CUSTOM_BUILTIN(mma_assemble_acc, "vW512*", false, "mma")
+UNALIASED_CUSTOM_BUILTIN(mma_disassemble_acc, "vv*W512*", false, "mma")

Based on the original implementation in `SemaBuiltinPPCMMACall` all of the 
`mma` builtins also require `paired-vector-memops`. 
Is this something that we still need?



Comment at: clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-test.c:47
 
-int test_test_data_class_f() {
-// CHECK-LABEL:   @test_test_data_class_f
-// CHECK: [[TMP:%.*]] = call i32 
@llvm.ppc.test.data.class.f32(float %0, i32 127)
-// CHECK-NEXT:ret i32 [[TMP]]
-// CHECK-NONPWR9-ERR: error: this builtin is only valid on POWER9 or later CPUs
-// CHECK-NOVSX-ERR: error: this builtin requires VSX to be enabled
-  return __test_data_class(f, 127);
+// CHECK-NOVSX-ERR: error: '__builtin_ppc_compare_exp_uo' needs target feature 
isa-v30-instructions,vsx
+// CHECK-NOVSX-ERR: error: '__builtin_ppc_compare_exp_lt' needs target feature 
isa-v30-instructions,vsx

nit:
Should this be 
```
... needs target feature vsx
```
Instead of listing them both?

Fixing this might be more trouble than it's worth because you would have to 
edit `CodeGenFunction::checkTargetFeatures`. I just thought I would mention it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143467

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


[PATCH] D146595: [clang] Add "transparent_stepping" attribute

2023-03-31 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl added a comment.

I think `debug_trampoline` both captures the semantics and makes it clear that 
this is related to debugging.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146595

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


[PATCH] D145264: [OpenMP][MLIR][Flang][Driver][bbc] Lower and apply Module FlagsAttr

2023-03-31 Thread Andrew Gozillon via Phabricator via cfe-commits
agozillon added a comment.

Fragmented this patch into https://reviews.llvm.org/D147344 (lowering) and 
https://reviews.llvm.org/D147324 (driver/tool changes and application of 
attribute). I will keep this patch open until the others are closed to give a 
big picture for easier reference.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145264

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


[PATCH] D147256: [DebugInfo] Fix file path separator when targeting windows.

2023-03-31 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

In D147256#4237099 , @probinson wrote:

> I think we cannot be 100% sure about source paths in a cross-compile 
> situation. Cross-compiling on platform A targeting platform B does not mean 
> your sources and debugger UI are on platform B. My users keep source and 
> debugger UI on platform A, debugging target B remotely. We need to preserve 
> the host pathnames. It is not clear to me that this patch does so.

I believe the idea is to preserve host pathnames as long as 
`LangOptions.UseTargetPathSeparator` is unset. But I see that might not be the 
case for `CodeViewDebug::emitObjName()` in the current version of the patch. 
Could we make clang handle that path instead depending on the flag?




Comment at: llvm/test/DebugInfo/COFF/build-info.ll:18
+; RUN: cd %t-dir
+; RUN: llc -filetype=obj -mtriple i686-pc-windows-msvc %s -o ../build-info.o
+; RUN: llvm-readobj --codeview ../build-info.o | FileCheck %s 
--check-prefix=OBJ

zequanwu wrote:
> hans wrote:
> > Does this write the .o file into the test directory? I don't think that's 
> > allowed (it may be read-only). But the test could create another 
> > subdirectory under `%t-dir`.
> It writes the .o file into the parent directory of the temporary dir %t-dir. 
> It will just be the directory path of a normal `%t`, not the source test 
> directory. The reason I'm not using `%t-dir/build-info.o` in the parent dir 
> is because it will be translated into an absolute address. That will remain 
> unchanged in ObjectName.
Right, I'm just thinking that we can't be sure that we can (or should) write 
files into the parent of `%t-dir`.

Would it work if you instead create `%t-dir/subdir`, `cd` into that, and then 
do `-o ../build-info.o`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147256

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


[PATCH] D141389: [DFSAN] Add support for strnlen, strncat, strsep, sscanf and _tolower

2023-03-31 Thread Andrew via Phabricator via cfe-commits
browneee added a comment.

We're getting really close!

Yes, that build error looks unrelated. Someone should fix it soon.




Comment at: compiler-rt/lib/dfsan/dfsan_custom.cpp:221
+  if (flags().strict_data_dependencies) {
+*ret_label = res ? dfsan_read_label(base, sizeof(base)) : 0;
+  } else {

`base, sizeof(base)` does not make sense - the size does not correspond to the 
pointer used.

Either
```
dfsan_read_label(base, sizeof(*base))   // first byte pointed to by base
dfsan_read_label(base, strlen(base)) // whole string pointed to by base
dfsan_read_label(&base, sizeof(base))  // the base pointer
```

In this case I think we want the base pointer.

`dfsan_read_label(&base, sizeof(base))`  // the base pointer
should be equivalent to doing
`dfsan_label base_label = dfsan_read_label(s, sizeof(*s))`  up at the start of 
the function, just after we declare base then use `base_label` here.

Lets go with the second option to avoid taking the address of a variable.

This is semantically equivalent to my first suggestion: `dfsan_get_label(base) 
== dfsan_read_label(&base, sizeof(base)) == base_label`.
Sorry I didn't consider the other constraints (no dfsan_get_label in this file 
because the pass is not run on this code; avoid taking address of variable) and 
suggest this in the first place.



Comment at: compiler-rt/lib/dfsan/dfsan_custom.cpp:224
+*ret_label =
+dfsan_union(dfsan_read_label(base, sizeof(base)),
+dfsan_union(dfsan_read_label(delim, strlen(delim) + 1),

Also use `base_label` here.



Comment at: compiler-rt/lib/dfsan/dfsan_custom.cpp:240
+if (res)
+  *ret_origin = dfsan_read_origin_of_first_taint(base, strlen(base));
+  } else {

`dfsan_get_origin(base) == dfsan_read_origin_of_first_taint(&base, 
sizeof(base))`

As noted above `base, strlen(base)` is a meaningfully valid pointer, length - 
but it is not the level of indirection we want here.

I think we want the same solution as above.

`dfsan_origin base_origin = dfsan_read_origin_of_first_taint(s, sizeof(*s))` at 
the start of the function, just after declaring and assigning base.



Comment at: compiler-rt/lib/dfsan/dfsan_custom.cpp:243
+if (*ret_label) {
+  dfsan_origin o = dfsan_read_origin_of_first_taint(base, strlen(base));
+  if (o) {

Also use `base_origin` here.



Comment at: compiler-rt/test/dfsan/custom.cpp:1641
+  // taint delim pointer
+  dfsan_set_label(j_label, &p_delim, sizeof(&p_delim));
+  // taint the string data bytes

remove the &

It still works because `sizeof(pointer_var) == sizeof(&pointer_var)`, but it 
doesn't logically match up like it should.

(Sorry, this one is my fault - I made this mistake giving an example in an 
earlier comment.)



Comment at: compiler-rt/test/dfsan/custom.cpp:1645
+  // taint the string pointer
+  dfsan_set_label(m_label, &p_s, sizeof(&p_s));
+

remove & in sizeof



Comment at: compiler-rt/test/dfsan/custom.cpp:1650
+#ifdef STRICT_DATA_DEPENDENCIES
+  ASSERT_LABEL(rv, k_label);
+  ASSERT_READ_LABEL(rv, strlen(rv), k_label);

The value `rv` has a data flow from the the string pointer, not the string 
bytes.
It should have `m_label` not `k_label`.

This is related to line 221 (using `base` instead of `&base`) in the other file.



Comment at: compiler-rt/test/dfsan/custom.cpp:1654
+  ASSERT_LABEL(rv, dfsan_union(dfsan_union(i_label, j_label), k_label));
+  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, *s);
+#endif

rv is a pointer, and I think it's origin should match the pointer s, not the 
bytes in the string.

I think this should be:

`ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, s);`

This is related to line 240 (`*ret_origin = 
dfsan_read_origin_of_first_taint(base, strlen(base));`) in the other file being 
the wrong level of indirection.


(Side note: the existing ASSERT_INIT_ORIGIN_EQ_ORIGIN macro feels a bit odd in 
that the arguments are at different levels of indirection - but not something 
to fix as part of this change)



Comment at: compiler-rt/test/dfsan/custom.cpp:1660
+  char **pp_s_base = pp_s;
+  dfsan_set_label(n_label, &pp_s, sizeof(&pp_s));
+

remove & in sizeof


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

https://reviews.llvm.org/D141389

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


[PATCH] D147324: [OpenMP][MLIR][Flang][bbc][Driver] Add OpenMP RTL Flags to Flang and generate omp.FlagsAttr from them

2023-03-31 Thread Andrew Gozillon via Phabricator via cfe-commits
agozillon updated this revision to Diff 510080.
agozillon added a comment.

- Add FIR -> LLVM Dialect test here, more fitting than the other patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147324

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/LangOptions.def
  flang/include/flang/Tools/CrossToolHelpers.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/omp-frontend-forwarding.f90
  flang/test/Lower/OpenMP/rtl-flags.f90
  flang/tools/bbc/bbc.cpp

Index: flang/tools/bbc/bbc.cpp
===
--- flang/tools/bbc/bbc.cpp
+++ flang/tools/bbc/bbc.cpp
@@ -129,6 +129,38 @@
llvm::cl::desc("enable openmp device compilation"),
llvm::cl::init(false));
 
+// A simplified subset of the OpenMP RTL Flags from Flang, only the primary
+// positive options are available, no negative options e.g. fopen_assume* vs
+// fno_open_assume*
+static llvm::cl::opt setOpenMPTargetDebug(
+"fopenmp-target-debug",
+llvm::cl::desc("Enable debugging in the OpenMP offloading device RTL"),
+llvm::cl::init(0));
+
+static llvm::cl::opt setOpenMPThreadSubscription(
+"fopenmp-assume-threads-oversubscription",
+llvm::cl::desc("Assume work-shared loops do not have more "
+   "iterations than participating threads."),
+llvm::cl::init(false));
+
+static llvm::cl::opt setOpenMPTeamSubscription(
+"fopenmp-assume-teams-oversubscription",
+llvm::cl::desc("Assume distributed loops do not have more iterations than "
+   "participating teams."),
+llvm::cl::init(false));
+
+static llvm::cl::opt setOpenMPNoThreadState(
+"fopenmp-assume-no-thread-state",
+llvm::cl::desc(
+"Assume that no thread in a parallel region will modify an ICV."),
+llvm::cl::init(false));
+
+static llvm::cl::opt setOpenMPNoNestedParallelism(
+"fopenmp-assume-no-nested-parallelism",
+llvm::cl::desc("Assume that no thread in a parallel region will encounter "
+   "a parallel region."),
+llvm::cl::init(false));
+
 static llvm::cl::opt enableOpenACC("fopenacc",
  llvm::cl::desc("enable openacc"),
  llvm::cl::init(false));
@@ -244,8 +276,13 @@
   kindMap, loweringOptions, {});
   burnside.lower(parseTree, semanticsContext);
   mlir::ModuleOp mlirModule = burnside.getModule();
-  if (enableOpenMP)
-setOffloadModuleInterfaceAttributes(mlirModule, enableOpenMPDevice);
+  if (enableOpenMP) {
+auto offloadModuleOpts =
+OffloadModuleOpts(setOpenMPTargetDebug, setOpenMPTeamSubscription,
+  setOpenMPThreadSubscription, setOpenMPNoThreadState,
+  setOpenMPNoNestedParallelism, enableOpenMPDevice);
+setOffloadModuleInterfaceAttributes(mlirModule, offloadModuleOpts);
+  }
   std::error_code ec;
   std::string outputName = outputFilename;
   if (!outputName.size())
Index: flang/test/Lower/OpenMP/rtl-flags.f90
===
--- /dev/null
+++ flang/test/Lower/OpenMP/rtl-flags.f90
@@ -0,0 +1,64 @@
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-is-device %s -o - | FileCheck %s --check-prefix=DEFAULT-DEVICE-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp %s -o - | FileCheck %s --check-prefix=DEFAULT-HOST-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-target-debug -fopenmp-is-device %s -o - | FileCheck %s --check-prefix=DBG-DEVICE-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-target-debug=111 -fopenmp-is-device %s -o - | FileCheck %s --check-prefix=DBG-EQ-DEVICE-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-assume-teams-oversubscription -fopenmp-is-device %s -o - | FileCheck %s --check-prefix=TEAMS-OSUB-DEVICE-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-assume-threads-oversubscription -fopenmp-is-device %s -o - | FileCheck %s --check-prefix=THREAD-OSUB-DEVICE-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-assume-no-thread-state -fopenmp-is-device %s -o - | FileCheck %s --check-prefix=THREAD-STATE-DEVICE-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-assume-no-nested-parallelism -fopenmp-is-device %s -o - | FileCheck %s --check-prefix=NEST-PAR-DEVICE-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-target-debug -fopenmp-assume-teams-oversubscription -fopenmp-assume-no-nested-parallelism -fopenmp-assume-threads-oversubscription -fopenmp-assume-no-thread-state -fopenmp-is-device %s -o - | FileCheck %s --check-prefix=ALL-DEVICE-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp %s -o - | fir-opt --fir-to-llvm-ir | FileCheck %s  --check-prefix=DEFAULT-HOST-LLVMDIALECT
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-is-device %s -o - | fir-opt -

[PATCH] D146987: [Assignment Tracking] Enable by default

2023-03-31 Thread Haowei Wu via Phabricator via cfe-commits
haowei added a comment.

This patch (which enables assignment tracking) and D147312 
 breaks llvm runtime build for 
`runtimes-armv7-unknown-linux-gnueabihf`

Error message:

  FAILED: libcxx/src/CMakeFiles/cxx_static.dir/charconv.cpp.o 
  /b/s/w/ir/cache/goma/client/gomacc 
/b/s/w/ir/x/w/staging/llvm_build/./bin/clang++ 
--target=armv7-unknown-linux-gnueabihf --sysroot=/b/s/w/ir/x/w/cipd/linux 
-DLIBCXX_BUILDING_LIBCXXABI -D_GLIBCXX_ASSERTIONS -D_LIBCPP_BUILDING_LIBRARY 
-D_LIBCPP_DISABLE_NEW_DELETE_DEFINITIONS -D_LIBCPP_ENABLE_ASSERTIONS 
-D_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER -D_LIBCPP_LINK_PTHREAD_LIB 
-D_LIBCPP_LINK_RT_LIB -D_LIBCPP_REMOVE_TRANSITIVE_INCLUDES 
-D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS 
-I/b/s/w/ir/x/w/llvm-llvm-project/libcxx/src 
-I/b/s/w/ir/x/w/staging/llvm_build/include/c++/v1 
-I/b/s/w/ir/x/w/staging/llvm_build/include/armv7-unknown-linux-gnueabihf/c++/v1 
-I/b/s/w/ir/x/w/llvm-llvm-project/libcxxabi/include 
--target=armv7-unknown-linux-gnueabihf -fvisibility-inlines-hidden 
-Werror=date-time -Werror=unguarded-availability-new -Wall -Wextra 
-Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wmissing-field-initializers 
-Wimplicit-fallthrough -Wcovered-switch-default -Wno-noexcept-type 
-Wnon-virtual-dtor -Wdelete-non-virtual-dtor -Wsuggest-override -Wno-comment 
-Wstring-conversion -Wmisleading-indentation -Wctad-maybe-unsupported 
-fdiagnostics-color -ffunction-sections -fdata-sections 
-ffile-prefix-map=/b/s/w/ir/x/w/staging/llvm_build/runtimes/runtimes-armv7-unknown-linux-gnueabihf-bins=../staging/llvm_build/runtimes/runtimes-armv7-unknown-linux-gnueabihf-bins
 -ffile-prefix-map=/b/s/w/ir/x/w/llvm-llvm-project/= -no-canonical-prefixes -O2 
-g -DNDEBUG -std=c++20 -fPIC -UNDEBUG -faligned-allocation -nostdinc++ 
-fvisibility-inlines-hidden -fvisibility=hidden -Wall -Wextra -Wnewline-eof 
-Wshadow -Wwrite-strings -Wno-unused-parameter -Wno-long-long 
-Werror=return-type -Wextra-semi -Wundef -Wunused-template -Wformat-nonliteral 
-Wno-user-defined-literals -Wno-covered-switch-default -Wno-suggest-override 
-Wno-error -MD -MT libcxx/src/CMakeFiles/cxx_static.dir/charconv.cpp.o -MF 
libcxx/src/CMakeFiles/cxx_static.dir/charconv.cpp.o.d -o 
libcxx/src/CMakeFiles/cxx_static.dir/charconv.cpp.o -c 
/b/s/w/ir/x/w/llvm-llvm-project/libcxx/src/charconv.cpp
  fragment covers entire variable
call void @llvm.dbg.value(metadata i32 %0, metadata !3116, metadata 
!DIExpression(DW_OP_LLVM_fragment, 0, 32)), !dbg !3130
  !3116 = !DILocalVariable(name: "__pred", arg: 3, scope: !3117, file: !3118, 
line: 23, type: !3121)
  fragment covers entire variable
call void @llvm.dbg.value(metadata i64 %0, metadata !3652, metadata 
!DIExpression(DW_OP_LLVM_fragment, 0, 64)), !dbg !3665
  !3652 = !DILocalVariable(name: "__pred", arg: 3, scope: !3653, file: !3118, 
line: 23, type: !3656)
  fragment covers entire variable
call void @llvm.dbg.value(metadata i32 %0, metadata !3116, metadata 
!DIExpression(DW_OP_LLVM_fragment, 0, 32)), !dbg !3130
  !3116 = !DILocalVariable(name: "__pred", arg: 3, scope: !3117, file: !3118, 
line: 23, type: !3121)
  fragment covers entire variable
call void @llvm.dbg.value(metadata i64 %0, metadata !3651, metadata 
!DIExpression(DW_OP_LLVM_fragment, 0, 64)), !dbg !3664
  !3651 = !DILocalVariable(name: "__pred", arg: 3, scope: !3652, file: !3118, 
line: 23, type: !3655)
  fatal error: error in backend: Broken module found, compilation aborted!
  PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ 
and include the crash backtrace, preprocessed source, and associated run script.
  Stack dump:
  0.Program arguments: /b/s/w/ir/x/w/staging/llvm_build/./bin/clang++ 
--target=armv7-unknown-linux-gnueabihf --sysroot=/b/s/w/ir/x/w/cipd/linux 
-DLIBCXX_BUILDING_LIBCXXABI -D_GLIBCXX_ASSERTIONS -D_LIBCPP_BUILDING_LIBRARY 
-D_LIBCPP_DISABLE_NEW_DELETE_DEFINITIONS -D_LIBCPP_ENABLE_ASSERTIONS 
-D_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER -D_LIBCPP_LINK_PTHREAD_LIB 
-D_LIBCPP_LINK_RT_LIB -D_LIBCPP_REMOVE_TRANSITIVE_INCLUDES 
-D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS 
-I/b/s/w/ir/x/w/llvm-llvm-project/libcxx/src 
-I/b/s/w/ir/x/w/staging/llvm_build/include/c++/v1 
-I/b/s/w/ir/x/w/staging/llvm_build/include/armv7-unknown-linux-gnueabihf/c++/v1 
-I/b/s/w/ir/x/w/llvm-llvm-project/libcxxabi/include 
--target=armv7-unknown-linux-gnueabihf -fvisibility-inlines-hidden 
-Werror=date-time -Werror=unguarded-availability-new -Wall -Wextra 
-Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wmissing-field-initializers 
-Wimplicit-fallthrough -Wcovered-switch-default -Wno-noexcept-type 
-Wnon-virtual-dtor -Wdelete-non-virtual-dtor -Wsuggest-override -Wno-comment 
-Wstring-conversion -Wmisleading-indentation -Wctad-maybe-unsupported 
-fdiagnostics-color -ffunction-sections -fdata-sections 
-ffile-prefix-map=/b/s/w/ir/x/w/staging/llvm_build/runtimes/runtimes-armv7-unknown-linux-gnueabihf-bins=

[PATCH] D147326: [clang][dataflow][NFC] Share code between Environment ctor and pushCallInternal().

2023-03-31 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel accepted this revision.
ymandel added a comment.

Thank you!




Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h:465
+  /// referenced in `FuncDecl`. `FuncDecl` must have a body.
+  void initVars(const FunctionDecl *FuncDecl);
 

xazax.hun wrote:
> I wonder if we should rename this to something like `initFieldAndGlobals`.
+1


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147326

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


[PATCH] D147256: [DebugInfo] Fix file path separator when targeting windows.

2023-03-31 Thread Paul Robinson via Phabricator via cfe-commits
probinson added subscribers: debug-info, probinson.
probinson added a comment.

I think we cannot be 100% sure about source paths in a cross-compile situation. 
Cross-compiling on platform A targeting platform B does not mean your sources 
and debugger UI are on platform B. My users keep source and debugger UI on 
platform A, debugging target B remotely. We need to preserve the host 
pathnames. It is not clear to me that this patch does so.




Comment at: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp:787
 
   StringRef PathRef(Asm->TM.Options.ObjectFilenameForDebug);
   llvm::SmallString<256> PathStore(PathRef);

zequanwu wrote:
> hans wrote:
> > This handles codeview. Does anything need to be done for dwarf on windows? 
> > mstorsjo might have input on that.
> It looks like `TM.Options.ObjectFilenameForDebug` is only used for codeview. 
> I guess dwarf doesn't store the object file path.
Right, DWARF only stores the source path.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147256

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


[PATCH] D147282: [clang][deps] Remove -coverage-data-file and -coverage-notes-file from modules

2023-03-31 Thread Ben Langmuir via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG758bca648385: [clang][deps] Remove -coverage-data-file and 
-coverage-notes-file from modules (authored by benlangmuir).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147282

Files:
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/test/ClangScanDeps/Inputs/removed-args/cdb.json.template
  clang/test/ClangScanDeps/removed-args.c


Index: clang/test/ClangScanDeps/removed-args.c
===
--- clang/test/ClangScanDeps/removed-args.c
+++ clang/test/ClangScanDeps/removed-args.c
@@ -23,6 +23,8 @@
 // CHECK-NEXT: "-cc1"
 // CHECK-NOT:  "-fdebug-compilation-dir="
 // CHECK-NOT:  "-fcoverage-compilation-dir="
+// CHECK-NOT:  "-coverage-notes-file
+// CHECK-NOT:  "-coverage-data-file
 // CHECK-NOT:  "-dwarf-debug-flags"
 // CHECK-NOT:  "-main-file-name"
 // CHECK-NOT:  "-include"
@@ -46,6 +48,8 @@
 // CHECK-NEXT: "-cc1"
 // CHECK-NOT:  "-fdebug-compilation-dir=
 // CHECK-NOT:  "-fcoverage-compilation-dir=
+// CHECK-NOT:  "-coverage-notes-file
+// CHECK-NOT:  "-coverage-data-file
 // CHECK-NOT:  "-dwarf-debug-flags"
 // CHECK-NOT:  "-main-file-name"
 // CHECK-NOT:  "-include"
Index: clang/test/ClangScanDeps/Inputs/removed-args/cdb.json.template
===
--- clang/test/ClangScanDeps/Inputs/removed-args/cdb.json.template
+++ clang/test/ClangScanDeps/Inputs/removed-args/cdb.json.template
@@ -1,7 +1,7 @@
 [
   {
 "directory": "DIR",
-"command": "clang -fsyntax-only DIR/tu.c -fmodules -fimplicit-module-maps 
-fmodules-validate-once-per-build-session 
-fbuild-session-file=DIR/build-session -fmodules-prune-interval=123 
-fmodules-prune-after=123 -fmodules-cache-path=DIR/cache -include DIR/header.h 
-grecord-command-line -fdebug-compilation-dir=DIR/debug 
-fcoverage-compilation-dir=DIR/coverage -o DIR/tu.o -serialize-diagnostics 
DIR/tu.diag -MT tu -MD -MF DIR/tu.d",
+"command": "clang -fsyntax-only DIR/tu.c -fmodules -fimplicit-module-maps 
-fmodules-validate-once-per-build-session 
-fbuild-session-file=DIR/build-session -fmodules-prune-interval=123 
-fmodules-prune-after=123 -fmodules-cache-path=DIR/cache -include DIR/header.h 
-grecord-command-line -fdebug-compilation-dir=DIR/debug 
-fcoverage-compilation-dir=DIR/coverage -ftest-coverage -o DIR/tu.o 
-serialize-diagnostics DIR/tu.diag -MT tu -MD -MF DIR/tu.d",
 "file": "DIR/tu.c"
   }
 ]
Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -100,6 +100,8 @@
   if (!CI.getLangOpts()->ModulesCodegen) {
 CI.getCodeGenOpts().DebugCompilationDir.clear();
 CI.getCodeGenOpts().CoverageCompilationDir.clear();
+CI.getCodeGenOpts().CoverageDataFile.clear();
+CI.getCodeGenOpts().CoverageNotesFile.clear();
   }
 
   // Map output paths that affect behaviour to "-" so their existence is in the


Index: clang/test/ClangScanDeps/removed-args.c
===
--- clang/test/ClangScanDeps/removed-args.c
+++ clang/test/ClangScanDeps/removed-args.c
@@ -23,6 +23,8 @@
 // CHECK-NEXT: "-cc1"
 // CHECK-NOT:  "-fdebug-compilation-dir="
 // CHECK-NOT:  "-fcoverage-compilation-dir="
+// CHECK-NOT:  "-coverage-notes-file
+// CHECK-NOT:  "-coverage-data-file
 // CHECK-NOT:  "-dwarf-debug-flags"
 // CHECK-NOT:  "-main-file-name"
 // CHECK-NOT:  "-include"
@@ -46,6 +48,8 @@
 // CHECK-NEXT: "-cc1"
 // CHECK-NOT:  "-fdebug-compilation-dir=
 // CHECK-NOT:  "-fcoverage-compilation-dir=
+// CHECK-NOT:  "-coverage-notes-file
+// CHECK-NOT:  "-coverage-data-file
 // CHECK-NOT:  "-dwarf-debug-flags"
 // CHECK-NOT:  "-main-file-name"
 // CHECK-NOT:  "-include"
Index: clang/test/ClangScanDeps/Inputs/removed-args/cdb.json.template
===
--- clang/test/ClangScanDeps/Inputs/removed-args/cdb.json.template
+++ clang/test/ClangScanDeps/Inputs/removed-args/cdb.json.template
@@ -1,7 +1,7 @@
 [
   {
 "directory": "DIR",
-"command": "clang -fsyntax-only DIR/tu.c -fmodules -fimplicit-module-maps -fmodules-validate-once-per-build-session -fbuild-session-file=DIR/build-session -fmodules-prune-interval=123 -fmodules-prune-after=123 -fmodules-cache-path=DIR/cache -include DIR/header.h -grecord-command-line -fdebug-compilation-dir=DIR/debug -fcoverage-compilation-dir=DIR/coverage -o DIR/tu.o -serialize-di

[clang] 758bca6 - [clang][deps] Remove -coverage-data-file and -coverage-notes-file from modules

2023-03-31 Thread Ben Langmuir via cfe-commits

Author: Ben Langmuir
Date: 2023-03-31T09:43:22-07:00
New Revision: 758bca6483853a743297b68bd88a5dba9d5247f2

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

LOG: [clang][deps] Remove -coverage-data-file and -coverage-notes-file from 
modules

When not performing codegen, we can strip the coverage-data-file and
coverage-notes-file options to improve canonicalization.

rdar://107443796

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

Added: 


Modified: 
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
clang/test/ClangScanDeps/Inputs/removed-args/cdb.json.template
clang/test/ClangScanDeps/removed-args.c

Removed: 




diff  --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp 
b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index 8cac033742a8c..3d41e78dfc7c7 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -100,6 +100,8 @@ 
ModuleDepCollector::makeInvocationForModuleBuildWithoutOutputs(
   if (!CI.getLangOpts()->ModulesCodegen) {
 CI.getCodeGenOpts().DebugCompilationDir.clear();
 CI.getCodeGenOpts().CoverageCompilationDir.clear();
+CI.getCodeGenOpts().CoverageDataFile.clear();
+CI.getCodeGenOpts().CoverageNotesFile.clear();
   }
 
   // Map output paths that affect behaviour to "-" so their existence is in the

diff  --git a/clang/test/ClangScanDeps/Inputs/removed-args/cdb.json.template 
b/clang/test/ClangScanDeps/Inputs/removed-args/cdb.json.template
index 2bdc340a3fccd..7ae3c88aedd8d 100644
--- a/clang/test/ClangScanDeps/Inputs/removed-args/cdb.json.template
+++ b/clang/test/ClangScanDeps/Inputs/removed-args/cdb.json.template
@@ -1,7 +1,7 @@
 [
   {
 "directory": "DIR",
-"command": "clang -fsyntax-only DIR/tu.c -fmodules -fimplicit-module-maps 
-fmodules-validate-once-per-build-session 
-fbuild-session-file=DIR/build-session -fmodules-prune-interval=123 
-fmodules-prune-after=123 -fmodules-cache-path=DIR/cache -include DIR/header.h 
-grecord-command-line -fdebug-compilation-dir=DIR/debug 
-fcoverage-compilation-dir=DIR/coverage -o DIR/tu.o -serialize-diagnostics 
DIR/tu.diag -MT tu -MD -MF DIR/tu.d",
+"command": "clang -fsyntax-only DIR/tu.c -fmodules -fimplicit-module-maps 
-fmodules-validate-once-per-build-session 
-fbuild-session-file=DIR/build-session -fmodules-prune-interval=123 
-fmodules-prune-after=123 -fmodules-cache-path=DIR/cache -include DIR/header.h 
-grecord-command-line -fdebug-compilation-dir=DIR/debug 
-fcoverage-compilation-dir=DIR/coverage -ftest-coverage -o DIR/tu.o 
-serialize-diagnostics DIR/tu.diag -MT tu -MD -MF DIR/tu.d",
 "file": "DIR/tu.c"
   }
 ]

diff  --git a/clang/test/ClangScanDeps/removed-args.c 
b/clang/test/ClangScanDeps/removed-args.c
index 02fbb8cacff2c..9a4ef25838e46 100644
--- a/clang/test/ClangScanDeps/removed-args.c
+++ b/clang/test/ClangScanDeps/removed-args.c
@@ -23,6 +23,8 @@
 // CHECK-NEXT: "-cc1"
 // CHECK-NOT:  "-fdebug-compilation-dir="
 // CHECK-NOT:  "-fcoverage-compilation-dir="
+// CHECK-NOT:  "-coverage-notes-file
+// CHECK-NOT:  "-coverage-data-file
 // CHECK-NOT:  "-dwarf-debug-flags"
 // CHECK-NOT:  "-main-file-name"
 // CHECK-NOT:  "-include"
@@ -46,6 +48,8 @@
 // CHECK-NEXT: "-cc1"
 // CHECK-NOT:  "-fdebug-compilation-dir=
 // CHECK-NOT:  "-fcoverage-compilation-dir=
+// CHECK-NOT:  "-coverage-notes-file
+// CHECK-NOT:  "-coverage-data-file
 // CHECK-NOT:  "-dwarf-debug-flags"
 // CHECK-NOT:  "-main-file-name"
 // CHECK-NOT:  "-include"



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


[PATCH] D144522: [clang-tidy] Add readability-operators-representation check

2023-03-31 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb added a comment.

Thanks so much for seeing this through; I'm unusually looking forward to 
rebuilding LLVM this weekend!




Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability/operators-representation.rst:82
+
+.. option:: OverloadedOperators
+

This is a great solution for ranges pipelines, which I've struggled to work out 
a good automated policy on for years.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144522

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


[PATCH] D147256: [DebugInfo] Fix file path separator when targeting windows.

2023-03-31 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu added a comment.

In D147256#4236522 , @hans wrote:

> Thanks for working on this!
>
> The `-ffile-reproducible` flag name refers to making `#file` directives 
> reproducible, but `LangOptions.UseTargetPathSeparator` sounds a lot broader 
> :) I don't know what others think, but it would be nice to not have to 
> introduce any more flags at least.

Oh, I was already using `LangOptions.UseTargetPathSeparator`. Updated the 
comment on UseTargetPathSeparator.




Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:544
 MainFileDir = std::string(MainFile->getDir().getName());
 if (!llvm::sys::path::is_absolute(MainFileName)) {
   llvm::SmallString<1024> MainFileDirSS(MainFileDir);

hans wrote:
> Do we want to fix absolute filenames too?
> I can see arguments for and against:
> - Using what the user provided makes sense
> - Some build systems might use absolute paths for everything. But on the 
> other hand such builds have larger determinism problems (including the full 
> paths).
> So the current decision probably makes sense.
Yeah. If it's already absolute filename, it will just use that one user 
provided. 



Comment at: clang/test/CodeGen/debug-info-slash.c:5
+
+// WIN:   !DIFile(filename: "{{.*}}clang/test/CodeGen\\debug-info-slash.c"
+// LINUX: !DIFile(filename: "{{.*}}clang/test/CodeGen/debug-info-slash.c"

hans wrote:
> Does the test runner write the 'clang/test/CodeGen' path with forward slashes 
> also on Windows?
No, it uses `clang\\test\\CodeGen`. Removed this part.



Comment at: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp:787
 
   StringRef PathRef(Asm->TM.Options.ObjectFilenameForDebug);
   llvm::SmallString<256> PathStore(PathRef);

hans wrote:
> This handles codeview. Does anything need to be done for dwarf on windows? 
> mstorsjo might have input on that.
It looks like `TM.Options.ObjectFilenameForDebug` is only used for codeview. I 
guess dwarf doesn't store the object file path.



Comment at: llvm/test/DebugInfo/COFF/build-info.ll:18
+; RUN: cd %t-dir
+; RUN: llc -filetype=obj -mtriple i686-pc-windows-msvc %s -o ../build-info.o
+; RUN: llvm-readobj --codeview ../build-info.o | FileCheck %s 
--check-prefix=OBJ

hans wrote:
> Does this write the .o file into the test directory? I don't think that's 
> allowed (it may be read-only). But the test could create another subdirectory 
> under `%t-dir`.
It writes the .o file into the parent directory of the temporary dir %t-dir. It 
will just be the directory path of a normal `%t`, not the source test 
directory. The reason I'm not using `%t-dir/build-info.o` in the parent dir is 
because it will be translated into an absolute address. That will remain 
unchanged in ObjectName.



Comment at: llvm/test/DebugInfo/COFF/build-info.ll:21
+
+; OBJ: ObjectName: ..\build-info.o
+

hans wrote:
> But in the `llc` invocation, the user wrote a relative path with a forward 
> slash. What behavior do we want? What should happen if there are more then 
> one slash - I think remove_dots just works on the first one?
Yeah, the input uses forward slash but we convert it into backslash. When there 
are multiple slashs, they will all be converted into backslashs, which is done 
by `llvm::sys::path::remove_dots(PathStore, /*remove_dot_dot=*/true, 
llvm::sys::path::Style::windows_backslash);`. `remove_dots` not only remove 
redundant dots but also canonicalize path separator based on the style.

I think ideally we want just take what user provided as the ObjectName with the 
redundant dots removed. But `remove_dots` always canonicalizes the path 
separator based on the style. I don't find any function that doesn't 
canonicalize the path. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147256

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


[PATCH] D147256: [DebugInfo] Fix file path separator when targeting windows.

2023-03-31 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu updated this revision to Diff 510057.
zequanwu marked 2 inline comments as done.
zequanwu added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147256

Files:
  clang/include/clang/Basic/LangOptions.h
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/debug-info-slash.c
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/test/DebugInfo/COFF/build-info.ll

Index: llvm/test/DebugInfo/COFF/build-info.ll
===
--- llvm/test/DebugInfo/COFF/build-info.ll
+++ llvm/test/DebugInfo/COFF/build-info.ll
@@ -10,6 +10,16 @@
 
 ; CHECK: {{.*}} | S_BUILDINFO [size = 8] BuildId = `[[INFO_IDX]]`
 
+; Test path is canonicalized to windows backslash style when output object file
+; name is not starting with '/'.
+; RUN: rm -rf %t-dir
+; RUN: mkdir %t-dir
+; RUN: cd %t-dir
+; RUN: llc -filetype=obj -mtriple i686-pc-windows-msvc %s -o ../build-info.o
+; RUN: llvm-readobj --codeview ../build-info.o | FileCheck %s --check-prefix=OBJ
+
+; OBJ: ObjectName: ..\build-info.o
+
 ; ModuleID = 'D:\src\scopes\foo.cpp'
 source_filename = "D:\5Csrc\5Cscopes\5Cfoo.cpp"
 target datalayout = "e-m:x-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32"
Index: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -791,7 +791,11 @@
 // Don't emit the filename if we're writing to stdout or to /dev/null.
 PathRef = {};
   } else {
-llvm::sys::path::remove_dots(PathStore, /*remove_dot_dot=*/true);
+llvm::sys::path::Style Style =
+llvm::sys::path::is_absolute(PathRef, llvm::sys::path::Style::posix)
+? llvm::sys::path::Style::posix
+: llvm::sys::path::Style::windows_backslash;
+llvm::sys::path::remove_dots(PathStore, /*remove_dot_dot=*/true, Style);
 PathRef = PathStore;
   }
 
Index: clang/test/CodeGen/debug-info-slash.c
===
--- /dev/null
+++ clang/test/CodeGen/debug-info-slash.c
@@ -0,0 +1,6 @@
+// RUN: %clang -target x86_64-pc-win32  -ffile-reproducible -emit-llvm -S -g %s -o - | FileCheck --check-prefix=WIN %s
+// RUN: %clang -target x86_64-linux-gnu  -ffile-reproducible -emit-llvm -S -g %s -o - | FileCheck --check-prefix=LINUX %s
+int main() { return 0; }
+
+// WIN:   !DIFile(filename: "{{.*}}\\debug-info-slash.c"
+// LINUX: !DIFile(filename: "{{.*}}/debug-info-slash.c"
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -528,6 +528,7 @@
   // Get absolute path name.
   SourceManager &SM = CGM.getContext().getSourceManager();
   auto &CGO = CGM.getCodeGenOpts();
+  const LangOptions &LO = CGM.getLangOpts();
   std::string MainFileName = CGO.MainFileName;
   if (MainFileName.empty())
 MainFileName = "";
@@ -542,9 +543,15 @@
 MainFileDir = std::string(MainFile->getDir().getName());
 if (!llvm::sys::path::is_absolute(MainFileName)) {
   llvm::SmallString<1024> MainFileDirSS(MainFileDir);
-  llvm::sys::path::append(MainFileDirSS, MainFileName);
-  MainFileName =
-  std::string(llvm::sys::path::remove_leading_dotslash(MainFileDirSS));
+  llvm::sys::path::Style Style =
+  LO.UseTargetPathSeparator
+  ? (CGM.getTarget().getTriple().isOSWindows()
+ ? llvm::sys::path::Style::windows_backslash
+ : llvm::sys::path::Style::posix)
+  : llvm::sys::path::Style::native;
+  llvm::sys::path::append(MainFileDirSS, Style, MainFileName);
+  MainFileName = std::string(
+  llvm::sys::path::remove_leading_dotslash(MainFileDirSS, Style));
 }
 // If the main file name provided is identical to the input file name, and
 // if the input file is a preprocessed source, use the module name for
@@ -560,7 +567,6 @@
   }
 
   llvm::dwarf::SourceLanguage LangTag;
-  const LangOptions &LO = CGM.getLangOpts();
   if (LO.CPlusPlus) {
 if (LO.ObjC)
   LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
Index: clang/include/clang/Basic/LangOptions.h
===
--- clang/include/clang/Basic/LangOptions.h
+++ clang/include/clang/Basic/LangOptions.h
@@ -479,9 +479,9 @@
   /// The seed used by the randomize structure layout feature.
   std::string RandstructSeed;
 
-  /// Indicates whether the __FILE__ macro should use the target's
-  /// platform-specific file separator or whether it should use the build
-  /// environment's platform-specific file separator.
+  /// Indicates whether to use target's platform-specific file separator when
+  /// __FILE__ macro is used and when concatenating filename with dire

[PATCH] D145441: [AMDGPU] Define data layout entries for buffers

2023-03-31 Thread Krzysztof Drewniak via Phabricator via cfe-commits
krzysz00 updated this revision to Diff 510056.
krzysz00 edited the summary of this revision.
krzysz00 added a comment.

Per discussion on the s.buffer.load revision, don't make those changes, and so 
revert this patch back to what it used to be.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145441

Files:
  clang/lib/Basic/Targets/AMDGPU.cpp
  clang/test/CodeGen/target-data.c
  clang/test/CodeGenOpenCL/amdgpu-env-amdgcn.cl
  llvm/docs/AMDGPUUsage.rst
  llvm/lib/IR/AutoUpgrade.cpp
  llvm/lib/Target/AMDGPU/AMDGPU.h
  llvm/lib/Target/AMDGPU/AMDGPUAliasAnalysis.cpp
  llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp
  llvm/lib/Target/AMDGPU/AMDGPUTargetTransformInfo.cpp
  llvm/lib/Target/AMDGPU/SIISelLowering.cpp
  llvm/test/CodeGen/AMDGPU/GlobalISel/buffer-atomic-fadd.f32-no-rtn.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/buffer-atomic-fadd.f32-rtn.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/buffer-atomic-fadd.f64.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/buffer-atomic-fadd.v2f16-no-rtn.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/buffer-atomic-fadd.v2f16-rtn.ll
  
llvm/test/CodeGen/AMDGPU/GlobalISel/irtranslator-non-integral-address-spaces.ll
  
llvm/test/CodeGen/AMDGPU/GlobalISel/legalize-llvm.amdgcn.image.atomic.dim.a16.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/legalize-llvm.amdgcn.image.dim.a16.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/legalize-llvm.amdgcn.image.load.2d.d16.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/legalize-llvm.amdgcn.image.load.2d.ll
  
llvm/test/CodeGen/AMDGPU/GlobalISel/legalize-llvm.amdgcn.image.load.2darraymsaa.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/legalize-llvm.amdgcn.image.load.3d.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/legalize-llvm.amdgcn.image.sample.a16.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/legalize-llvm.amdgcn.image.sample.d.ll
  
llvm/test/CodeGen/AMDGPU/GlobalISel/legalize-llvm.amdgcn.image.sample.g16.a16.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/legalize-llvm.amdgcn.image.sample.g16.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/legalize-llvm.amdgcn.image.store.2d.d16.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.image.atomic.dim.mir
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.buffer.atomic.add.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.buffer.atomic.cmpswap.ll
  
llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.buffer.atomic.fadd-with-ret.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.buffer.atomic.fadd.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.buffer.load.format.f16.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.buffer.load.format.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.buffer.load.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.buffer.store.format.f16.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.buffer.store.format.f32.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.buffer.store.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.tbuffer.load.f16.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.tbuffer.load.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.tbuffer.store.f16.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.tbuffer.store.i8.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.raw.tbuffer.store.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.struct.buffer.atomic.add.ll
  
llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.struct.buffer.atomic.cmpswap.ll
  
llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.struct.buffer.atomic.fadd-with-ret.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.struct.buffer.atomic.fadd.ll
  
llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.struct.buffer.load.format.f16.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.struct.buffer.load.format.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.struct.buffer.load.ll
  
llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.struct.buffer.store.format.f16.ll
  
llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.struct.buffer.store.format.f32.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.struct.buffer.store.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.struct.tbuffer.load.f16.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/llvm.amdgcn.struct.tbuffer.load.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/regbankselect-amdgcn.image.load.1d.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/regbankselect-amdgcn.image.sample.1d.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/regbankselect-amdgcn.raw.buffer.load.ll
  llvm/test/CodeGen/AMDGPU/GlobalISel/regbankselect-amdgcn.struct.buffer.load.ll
  
llvm/test/CodeGen/AMDGPU/GlobalISel/regbankselect-amdgcn.struct.buffer.store.ll
  llvm/test/CodeGen/AMDGPU/addrspacecast-captured.ll
  llvm/test/CodeGen/AMDGPU/annotate-kernel-features-hsa.ll
  llvm/test/CodeGen/AMDGPU/buffer-atomic-fadd.f32-no-rtn.ll
  llvm/test/CodeGen/AMDGPU/buffer-atomic-fadd.f32-rtn.ll
  llvm/test/CodeGen/AMDGPU/buffer-atomic-fadd.f64.ll
  llvm/test/CodeGen/AMDGPU/buffer-atomic-fadd

[PATCH] D107294: [clang-tidy] adds warning to suggest users replace symbols with words

2023-03-31 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL abandoned this revision.
PiotrZSL added a comment.

Obsolete by D144522 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107294

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


[PATCH] D31308: [clang-tidy] new check readability-no-alternative-tokens

2023-03-31 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL abandoned this revision.
PiotrZSL added a comment.

Obsolete by D144522 


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

https://reviews.llvm.org/D31308

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


[clang-tools-extra] a084854 - [clang-tidy] Add readability-operators-representation check

2023-03-31 Thread Piotr Zegar via cfe-commits

Author: Piotr Zegar
Date: 2023-03-31T16:07:16Z
New Revision: a084854266ca60748982228a4c98d036bca5f762

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

LOG: [clang-tidy] Add readability-operators-representation check

Check helps enforce consistent token representation for binary, unary and
overloaded operators in C++ code. The check supports both traditional and
alternative representations of operators.

Reviewed By: carlosgalvezp

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

Added: 
clang-tools-extra/clang-tidy/readability/OperatorsRepresentationCheck.cpp
clang-tools-extra/clang-tidy/readability/OperatorsRepresentationCheck.h

clang-tools-extra/docs/clang-tidy/checks/readability/operators-representation.rst

clang-tools-extra/test/clang-tidy/checkers/readability/operators-representation-to-alternative.cpp

clang-tools-extra/test/clang-tidy/checkers/readability/operators-representation-to-traditional.cpp

Modified: 
clang-tools-extra/clang-tidy/readability/CMakeLists.txt
clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index 2306641ca9215..421698cd615f9 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -29,6 +29,7 @@ add_clang_library(clangTidyReadabilityModule
   NamedParameterCheck.cpp
   NamespaceCommentCheck.cpp
   NonConstParameterCheck.cpp
+  OperatorsRepresentationCheck.cpp
   QualifiedAutoCheck.cpp
   ReadabilityTidyModule.cpp
   RedundantAccessSpecifiersCheck.cpp

diff  --git 
a/clang-tools-extra/clang-tidy/readability/OperatorsRepresentationCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/OperatorsRepresentationCheck.cpp
new file mode 100644
index 0..ab45dab71689a
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/OperatorsRepresentationCheck.cpp
@@ -0,0 +1,335 @@
+//===--- OperatorsRepresentationCheck.cpp - clang-tidy
+//--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "OperatorsRepresentationCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/ADT/STLExtras.h"
+#include 
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+static StringRef getOperatorSpelling(SourceLocation Loc, ASTContext &Context) {
+  if (Loc.isInvalid())
+return {};
+
+  SourceManager &SM = Context.getSourceManager();
+
+  Loc = SM.getSpellingLoc(Loc);
+  if (Loc.isInvalid())
+return {};
+
+  const CharSourceRange TokenRange = CharSourceRange::getTokenRange(Loc);
+  return Lexer::getSourceText(TokenRange, SM, Context.getLangOpts());
+}
+
+namespace {
+
+AST_MATCHER_P2(BinaryOperator, hasInvalidBinaryOperatorRepresentation,
+   BinaryOperatorKind, Kind, llvm::StringRef,
+   ExpectedRepresentation) {
+  if (Node.getOpcode() != Kind || ExpectedRepresentation.empty())
+return false;
+
+  StringRef Spelling =
+  getOperatorSpelling(Node.getOperatorLoc(), Finder->getASTContext());
+  return !Spelling.empty() && Spelling != ExpectedRepresentation;
+}
+
+AST_MATCHER_P2(UnaryOperator, hasInvalidUnaryOperatorRepresentation,
+   UnaryOperatorKind, Kind, llvm::StringRef,
+   ExpectedRepresentation) {
+  if (Node.getOpcode() != Kind || ExpectedRepresentation.empty())
+return false;
+
+  StringRef Spelling =
+  getOperatorSpelling(Node.getOperatorLoc(), Finder->getASTContext());
+  return !Spelling.empty() && Spelling != ExpectedRepresentation;
+}
+
+AST_MATCHER_P2(CXXOperatorCallExpr, hasInvalidOverloadedOperatorRepresentation,
+   OverloadedOperatorKind, Kind, llvm::StringRef,
+   ExpectedRepresentation) {
+  if (Node.getOperator() != Kind || ExpectedRepresentation.empty())
+return false;
+
+  StringRef Spelling =
+  getOperatorSpelling(Node.getOperatorLoc(), Finder->getASTContext());
+  return !Spelling.empty() && Spelling != ExpectedRepresentation;
+}
+
+} // namespace
+
+constexpr std::array, 2U>
+UnaryRepresentation{{{"!", "not"}, {"~", "compl"}}};
+
+constexpr std::array, 9U>
+OperatorsRepresentation{{{"&&", "and"},
+ {"||", "

[PATCH] D144522: [clang-tidy] Add readability-operators-representation check

2023-03-31 Thread Piotr Zegar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa084854266ca: [clang-tidy] Add 
readability-operators-representation check (authored by PiotrZSL).

Changed prior to commit:
  https://reviews.llvm.org/D144522?vs=508310&id=510055#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144522

Files:
  clang-tools-extra/clang-tidy/readability/CMakeLists.txt
  clang-tools-extra/clang-tidy/readability/OperatorsRepresentationCheck.cpp
  clang-tools-extra/clang-tidy/readability/OperatorsRepresentationCheck.h
  clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/docs/clang-tidy/checks/readability/operators-representation.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability/operators-representation-to-alternative.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability/operators-representation-to-traditional.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability/operators-representation-to-traditional.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability/operators-representation-to-traditional.cpp
@@ -0,0 +1,177 @@
+// RUN: %check_clang_tidy %s readability-operators-representation %t -- -config="{CheckOptions: [\
+// RUN: {key: readability-operators-representation.BinaryOperators, value: '&&;&=;&;|;~;!;!=;||;|=;^;^='}, \
+// RUN: {key: readability-operators-representation.OverloadedOperators, value: '&&;&=;&;|;~;!;!=;||;|=;^;^='}]}" --
+
+void testAllTokensToAlternative(int a, int b) {
+  int value = 0;
+
+  value = a or b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: 'or' is an alternative token spelling, consider using a traditional token '||' for consistency [readability-operators-representation]
+  // CHECK-FIXES: {{^  }}value = a || b;{{$}}
+
+  value = a and b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: 'and' is an alternative token spelling, consider using a traditional token '&&' for consistency [readability-operators-representation]
+  // CHECK-FIXES: {{^  }}value = a && b;{{$}}
+
+  value = a bitor b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: 'bitor' is an alternative token spelling, consider using a traditional token '|' for consistency [readability-operators-representation]
+  // CHECK-FIXES: {{^  }}value = a | b;{{$}}
+
+  value = a bitand b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: 'bitand' is an alternative token spelling, consider using a traditional token '&' for consistency [readability-operators-representation]
+  // CHECK-FIXES: {{^  }}value = a & b;{{$}}
+
+  value = not a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: 'not' is an alternative token spelling, consider using a traditional token '!' for consistency [readability-operators-representation]
+  // CHECK-FIXES: {{^  }}value = ! a;{{$}}
+
+  value = a xor b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: 'xor' is an alternative token spelling, consider using a traditional token '^' for consistency [readability-operators-representation]
+  // CHECK-FIXES: {{^  }}value = a ^ b;{{$}}
+
+  value = compl b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: 'compl' is an alternative token spelling, consider using a traditional token '~' for consistency [readability-operators-representation]
+  // CHECK-FIXES: {{^  }}value = ~ b;{{$}}
+
+  value and_eq b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: 'and_eq' is an alternative token spelling, consider using a traditional token '&=' for consistency [readability-operators-representation]
+  // CHECK-FIXES: {{^  }}value &= b;{{$}}
+
+  value or_eq b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: 'or_eq' is an alternative token spelling, consider using a traditional token '|=' for consistency [readability-operators-representation]
+  // CHECK-FIXES: {{^  }}value |= b;{{$}}
+
+  value = a not_eq b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: 'not_eq' is an alternative token spelling, consider using a traditional token '!=' for consistency [readability-operators-representation]
+  // CHECK-FIXES: {{^  }}value = a != b;{{$}}
+
+  value xor_eq a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: 'xor_eq' is an alternative token spelling, consider using a traditional token '^=' for consistency [readability-operators-representation]
+  // CHECK-FIXES: {{^  }}value ^= a;{{$}}
+}
+
+struct Class {
+  bool operator!() const;
+  Class operator~() const;
+  bool operator&&(const Class&) const;
+  Class operator&(const Class&) const;
+  bool operator||(const Class&) const;
+  Class operator|(const Class&) const;
+  Class operator^(const Class&) const;
+  Class& operator&=(const Class&) const;
+  Class& operator|=(const Class&) const;
+  Class& operator^=(const Class&) const;
+  bool operator!=(const Class&) const;
+};
+

[PATCH] D141389: [DFSAN] Add support for strnlen, strncat, strsep, sscanf and _tolower

2023-03-31 Thread Tomasz Kuchta via Phabricator via cfe-commits
tkuchta added a comment.

there is a strange build error which seems unrelated to my change - please let 
me know if that's an issue, I will try to rebase to newest master then


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

https://reviews.llvm.org/D141389

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


[PATCH] D147302: [clang][dataflow] Add `create()` methods to `Environment` and `DataflowAnalysisContext`.

2023-03-31 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added inline comments.
This revision is now accepted and ready to land.



Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:100
+// used `StorageLocation` subclasses and make them use a 
`BumpPtrAllocator`.
+Locs.push_back(std::make_unique(std::forward(args)...));
+return *cast(Locs.back().get());

Would emplace back work? That returns a reference to the just emplaced element 
saving us the call to `back` making the code a bit more concise.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h:328
+  template 
+  std::enable_if_t::value, T &>
+  create(Args &&...args) {

Just curious, what is the reason for repeating the `enable_if` here in addition 
to the one in the called function? Do we get better error messages?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147302

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


[PATCH] D147326: [clang][dataflow][NFC] Share code between Environment ctor and pushCallInternal().

2023-03-31 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h:465
+  /// referenced in `FuncDecl`. `FuncDecl` must have a body.
+  void initVars(const FunctionDecl *FuncDecl);
 

I wonder if we should rename this to something like `initFieldAndGlobals`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147326

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


[PATCH] D141389: [DFSAN] Add support for strnlen, strncat, strsep, sscanf and _tolower

2023-03-31 Thread Tomasz Kuchta via Phabricator via cfe-commits
tkuchta updated this revision to Diff 510047.
tkuchta added a comment.

Updates after the review of strsep.


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

https://reviews.llvm.org/D141389

Files:
  compiler-rt/lib/dfsan/dfsan_custom.cpp
  compiler-rt/lib/dfsan/done_abilist.txt
  compiler-rt/test/dfsan/custom.cpp

Index: compiler-rt/test/dfsan/custom.cpp
===
--- compiler-rt/test/dfsan/custom.cpp
+++ compiler-rt/test/dfsan/custom.cpp
@@ -1627,6 +1627,50 @@
 #endif
 }
 
+void test_strsep() {
+  char *s = strdup("Hello world/");
+  char *delim = strdup(" /");
+
+  char *p_s = s;
+  char *base = s;
+  char *p_delim = delim;
+
+  // taint delim bytes
+  dfsan_set_label(i_label, p_delim, strlen(p_delim));
+  // taint delim pointer
+  dfsan_set_label(j_label, &p_delim, sizeof(&p_delim));
+  // taint the string data bytes
+  dfsan_set_label(k_label, s, 5);
+  // taint the string pointer
+  dfsan_set_label(m_label, &p_s, sizeof(&p_s));
+
+  char *rv = strsep(&p_s, p_delim);
+  assert(rv == &base[0]);
+#ifdef STRICT_DATA_DEPENDENCIES
+  ASSERT_LABEL(rv, k_label);
+  ASSERT_READ_LABEL(rv, strlen(rv), k_label);
+#else
+  ASSERT_LABEL(rv, dfsan_union(dfsan_union(i_label, j_label), k_label));
+  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, *s);
+#endif
+
+  // taint the remaining string's pointer
+  char **pp_s = &p_s;
+  char **pp_s_base = pp_s;
+  dfsan_set_label(n_label, &pp_s, sizeof(&pp_s));
+
+  rv = strsep(pp_s, p_delim);
+
+  assert(rv == &base[6]);
+#ifdef STRICT_DATA_DEPENDENCIES
+  ASSERT_ZERO_LABEL(rv);
+  ASSERT_ZERO_ORIGIN(rv);
+#else
+  ASSERT_LABEL(rv, dfsan_union(i_label, dfsan_union(j_label, n_label)));
+  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, *p_delim);
+#endif
+}
+
 void test_memchr() {
   char str1[] = "str1";
   dfsan_set_label(i_label, &str1[3], 1);
@@ -2041,6 +2085,7 @@
   test_strncmp();
   test_strncpy();
   test_strpbrk();
+  test_strsep();
   test_strrchr();
   test_strstr();
   test_strtod();
Index: compiler-rt/lib/dfsan/done_abilist.txt
===
--- compiler-rt/lib/dfsan/done_abilist.txt
+++ compiler-rt/lib/dfsan/done_abilist.txt
@@ -283,6 +283,7 @@
 fun:strpbrk=custom
 fun:strrchr=custom
 fun:strstr=custom
+fun:strsep=custom
 
 # Functions which take action based on global state, such as running a callback
 # set by a separate function.
Index: compiler-rt/lib/dfsan/dfsan_custom.cpp
===
--- compiler-rt/lib/dfsan/dfsan_custom.cpp
+++ compiler-rt/lib/dfsan/dfsan_custom.cpp
@@ -204,6 +204,55 @@
   return const_cast(ret);
 }
 
+SANITIZER_INTERFACE_ATTRIBUTE char *__dfsw_strsep(char **s, const char *delim,
+  dfsan_label s_label,
+  dfsan_label delim_label,
+  dfsan_label *ret_label) {
+  char *base = *s;
+  char *res = strsep(s, delim);
+  if (res != *s) {
+char *token_start = res;
+int token_length = strlen(res);
+// the delimiter byte has been set to NULL
+dfsan_set_label(0, token_start + token_length, 1);
+  }
+
+  if (flags().strict_data_dependencies) {
+*ret_label = res ? dfsan_read_label(base, sizeof(base)) : 0;
+  } else {
+*ret_label =
+dfsan_union(dfsan_read_label(base, sizeof(base)),
+dfsan_union(dfsan_read_label(delim, strlen(delim) + 1),
+dfsan_union(s_label, delim_label)));
+  }
+
+  return res;
+}
+
+SANITIZER_INTERFACE_ATTRIBUTE char *__dfso_strsep(
+char **s, const char *delim, dfsan_label s_label, dfsan_label delim_label,
+dfsan_label *ret_label, dfsan_origin s_origin, dfsan_origin delim_origin,
+dfsan_origin *ret_origin) {
+  char *base = *s;
+  char *res = __dfsw_strsep(s, delim, s_label, delim_label, ret_label);
+  if (flags().strict_data_dependencies) {
+if (res)
+  *ret_origin = dfsan_read_origin_of_first_taint(base, strlen(base));
+  } else {
+if (*ret_label) {
+  dfsan_origin o = dfsan_read_origin_of_first_taint(base, strlen(base));
+  if (o) {
+*ret_origin = o;
+  } else {
+o = dfsan_read_origin_of_first_taint(delim, strlen(delim) + 1);
+*ret_origin = o ? o : (s_label ? s_origin : delim_origin);
+  }
+}
+  }
+
+  return res;
+}
+
 static int dfsan_memcmp_bcmp(const void *s1, const void *s2, size_t n,
  size_t *bytes_read) {
   const char *cs1 = (const char *) s1, *cs2 = (const char *) s2;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D141389: [DFSAN] Add support for strnlen, strncat, strsep, sscanf and _tolower

2023-03-31 Thread Tomasz Kuchta via Phabricator via cfe-commits
tkuchta updated this revision to Diff 510041.
tkuchta marked an inline comment as done.
tkuchta added a comment.

Hello, I applied the review comments for strsep.


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

https://reviews.llvm.org/D141389

Files:
  compiler-rt/lib/dfsan/dfsan_custom.cpp
  compiler-rt/test/dfsan/custom.cpp

Index: compiler-rt/test/dfsan/custom.cpp
===
--- compiler-rt/test/dfsan/custom.cpp
+++ compiler-rt/test/dfsan/custom.cpp
@@ -1636,80 +1636,38 @@
   char *p_delim = delim;
 
   // taint delim bytes
-  dfsan_set_label(n_label, p_delim, strlen(p_delim));
+  dfsan_set_label(i_label, p_delim, strlen(p_delim));
   // taint delim pointer
-  dfsan_set_label(i_label, &p_delim, sizeof(&p_delim));
+  dfsan_set_label(j_label, &p_delim, sizeof(&p_delim));
+  // taint the string data bytes
+  dfsan_set_label(k_label, s, 5);
+  // taint the string pointer
+  dfsan_set_label(m_label, &p_s, sizeof(&p_s));
 
   char *rv = strsep(&p_s, p_delim);
   assert(rv == &base[0]);
 #ifdef STRICT_DATA_DEPENDENCIES
-  ASSERT_ZERO_LABEL(rv);
-  ASSERT_READ_ZERO_LABEL(rv, strlen(rv));
+  ASSERT_LABEL(rv, k_label);
+  ASSERT_READ_LABEL(rv, strlen(rv), k_label);
 #else
-  ASSERT_LABEL(rv, dfsan_union(i_label, n_label));
-  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, *p_delim);
+  ASSERT_LABEL(rv, dfsan_union(dfsan_union(i_label, j_label), k_label));
+  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, *s);
 #endif
 
-  // taint the remaining string's bytes
-  dfsan_set_label(m_label, p_s, strlen(p_s));
   // taint the remaining string's pointer
   char **pp_s = &p_s;
-  dfsan_set_label(j_label, &pp_s, sizeof(&p_s));
+  char **pp_s_base = pp_s;
+  dfsan_set_label(n_label, &pp_s, sizeof(&pp_s));
 
   rv = strsep(pp_s, p_delim);
 
   assert(rv == &base[6]);
-#ifdef STRICT_DATA_DEPENDENCIES
-  ASSERT_READ_LABEL(rv, strlen(rv), m_label);
-  ASSERT_LABEL(rv, j_label);
-  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, pp_s);
-#else
-  ASSERT_LABEL(
-  rv, dfsan_union(j_label,
-  dfsan_union(i_label, dfsan_union(m_label, n_label;
-  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, base[6]);
-#endif
-
-  free(s);
-  s = strdup("Hello world/");
-  base = s;
-  free(delim);
-  delim = strdup(" /");
-  p_delim = delim;
-
-  dfsan_set_label(j_label, &delim[0], 1);
-
-  rv = strsep(&s, delim);
-  assert(rv == &base[0]);
 #ifdef STRICT_DATA_DEPENDENCIES
   ASSERT_ZERO_LABEL(rv);
+  ASSERT_ZERO_ORIGIN(rv);
 #else
-  ASSERT_LABEL(rv, j_label);
-  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, delim[1]);
-#endif
-
-  char *ps = s;
-  pp_s = &ps;
-  dfsan_set_label(i_label, &pp_s, sizeof(&pp_s));
-  dfsan_set_label(i_label, ps, strlen(ps));
-  dfsan_set_label(dfsan_union(j_label, dfsan_read_label(ps, strlen(ps))), ps,
-  strlen(ps));
-  rv = strsep(pp_s, " /");
-  assert(rv == &base[6]);
-#ifdef STRICT_DATA_DEPENDENCIES
-  ASSERT_LABEL(rv, i_label);
-#else
-  ASSERT_LABEL(rv, i_j_label);
-  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, base[6]);
-#endif
-  rv = strsep(&ps, " /");
-  assert(strlen(rv) == 0);
-#ifdef STRICT_DATA_DEPENDENCIES
-  ASSERT_ZERO_LABEL(ps);
-#else
-  ASSERT_ZERO_LABEL(rv);
-  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, 0);
-
+  ASSERT_LABEL(rv, dfsan_union(i_label, dfsan_union(j_label, n_label)));
+  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, *p_delim);
 #endif
 }
 
Index: compiler-rt/lib/dfsan/dfsan_custom.cpp
===
--- compiler-rt/lib/dfsan/dfsan_custom.cpp
+++ compiler-rt/lib/dfsan/dfsan_custom.cpp
@@ -218,11 +218,10 @@
   }
 
   if (flags().strict_data_dependencies) {
-*ret_label = res ? s_label : 0;
+*ret_label = res ? dfsan_read_label(base, sizeof(base)) : 0;
   } else {
-size_t s_bytes_read = (res ? strlen(res) : strlen(base)) + 1;
 *ret_label =
-dfsan_union(dfsan_read_label(base, s_bytes_read),
+dfsan_union(dfsan_read_label(base, sizeof(base)),
 dfsan_union(dfsan_read_label(delim, strlen(delim) + 1),
 dfsan_union(s_label, delim_label)));
   }
@@ -238,11 +237,10 @@
   char *res = __dfsw_strsep(s, delim, s_label, delim_label, ret_label);
   if (flags().strict_data_dependencies) {
 if (res)
-  *ret_origin = s_origin;
+  *ret_origin = dfsan_read_origin_of_first_taint(base, strlen(base));
   } else {
 if (*ret_label) {
-  size_t s_bytes_read = (res ? strlen(res) : strlen(base)) + 1;
-  dfsan_origin o = dfsan_read_origin_of_first_taint(base, s_bytes_read);
+  dfsan_origin o = dfsan_read_origin_of_first_taint(base, strlen(base));
   if (o) {
 *ret_origin = o;
   } else {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D147044: [clangd] Implement cross reference request for #include lines.

2023-03-31 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 510042.
VitaNuo added a comment.

Simplify.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147044

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

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -43,6 +43,10 @@
 using ::testing::UnorderedElementsAreArray;
 using ::testing::UnorderedPointwise;
 
+std::string guard(llvm::StringRef Code) {
+  return "#pragma once\n" + Code.str();
+}
+
 MATCHER_P2(FileRange, File, Range, "") {
   return Location{URIForFile::canonicalize(File, testRoot()), Range} == arg;
 }
@@ -2293,6 +2297,50 @@
 checkFindRefs(Test);
 }
 
+TEST(FindReferences, UsedSymbolsFromInclude) {
+  const char *Tests[] = {
+  R"cpp([[#include ^"bar.h"]]
+#include 
+int fstBar = [[bar1]]();
+int sndBar = [[bar2]]();
+[[Bar]] bar;
+int macroBar = [[BAR]];
+std::vector vec;
+  )cpp",
+
+  R"cpp([[#in^clude ]]
+std::[[vector]] vec;
+  )cpp"};
+  for (const char *Test : Tests) {
+Annotations T(Test);
+auto TU = TestTU::withCode(T.code());
+TU.ExtraArgs.push_back("-std=c++20");
+TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+  #define BAR 5
+  int bar1();
+  int bar2();
+  class Bar {};
+)cpp");
+TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+  namespace std {
+template
+class vector{};
+  }
+)cpp");
+TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+auto AST = TU.build();
+std::vector> ExpectedLocations;
+for (const auto &R : T.ranges())
+  ExpectedLocations.push_back(AllOf(rangeIs(R), attrsAre(0u)));
+for (const auto &P : T.points()) 
+  EXPECT_THAT(findReferences(AST, P, 0).References,
+  UnorderedElementsAreArray(ExpectedLocations))
+  << "Failed for Refs at " << P << "\n"
+  << Test;
+  }
+}
+
 TEST(FindReferences, NeedsIndexForSymbols) {
   const char *Header = "int foo();";
   Annotations Main("int main() { [[f^oo]](); }");
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -10,12 +10,15 @@
 #include "FindSymbols.h"
 #include "FindTarget.h"
 #include "HeuristicResolver.h"
+#include "IncludeCleaner.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "Quality.h"
 #include "Selection.h"
 #include "SourceCode.h"
 #include "URI.h"
+#include "clang-include-cleaner/Analysis.h"
+#include "clang-include-cleaner/Types.h"
 #include "index/Index.h"
 #include "index/Merge.h"
 #include "index/Relation.h"
@@ -48,6 +51,7 @@
 #include "clang/Index/IndexingAction.h"
 #include "clang/Index/IndexingOptions.h"
 #include "clang/Index/USRGeneration.h"
+#include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
@@ -61,6 +65,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
+#include 
 #include 
 
 namespace clang {
@@ -1312,6 +1317,59 @@
 }
 } // namespace
 
+ReferencesResult maybeFindIncludeReferences(ParsedAST &AST, Position Pos,
+URIForFile URIMainFile) {
+  ReferencesResult Results;
+  const SourceManager &SM = AST.getSourceManager();
+  auto Includes = AST.getIncludeStructure().MainFileIncludes;
+  auto ConvertedMainFileIncludes = convertIncludes(SM, Includes);
+  for (auto &Inc : Includes) {
+if (Inc.HashLine != Pos.line)
+  continue;
+
+auto ReferencedInclude = convertIncludes(SM, Inc);
+include_cleaner::walkUsed(
+AST.getLocalTopLevelDecls(), collectMacroReferences(AST),
+AST.getPragmaIncludes(), SM,
+[&](const include_cleaner::SymbolReference &Ref,
+llvm::ArrayRef Providers) {
+  if (Ref.RT != include_cleaner::RefType::Explicit)
+return;
+
+  auto Provider =
+  firstMatchedProvider(ConvertedMainFileIncludes, Providers);
+  if (!Provider || ReferencedInclude.match(*Provider).empty())
+return;
+
+  auto Loc = SM.getFileLoc(Ref.RefLocation);
+  // File locations can be outside of the main file if macro is
+  // expanded through an #include.
+  while (SM.getFileID(Loc) != SM.getMainFileID())
+Loc = SM.getIncludeLoc(SM.getFileID(Loc));
+
+  ReferencesResult::Reference Result;
+  const auto *Token = AST.getTokens().spelledTokenAt(Loc);
+  Result

[PATCH] D147315: [clang-tidy] support unscoped enumerations in readability-static-accessed-through-instance

2023-03-31 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:264
 
+- Improved :doc:`readability-static-accessed-through-instance
+  ` check to 

Please keep alphabetical order (by check name) in this section.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147315

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


[PATCH] D147044: [clangd] Implement cross reference request for #include lines.

2023-03-31 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo added a comment.

Thanks for the comments!




Comment at: clang-tools-extra/clangd/XRefs.cpp:1348
+  auto Loc = SM.getFileLoc(Ref.RefLocation);
+  for (const auto &H : Providers) {
+auto MatchingIncludes = ConvertedMainFileIncludes.match(H);

kadircet wrote:
> we're implementing and testing this logic twice now, once in here and once in 
> hover. can we instead have a helper in `IncludeCleaner.h` that looks like:
> ```
> std::optional firstSatisfiedProvider(const 
> include_cleaner::Includes& Includes, llvm::ArrayRef 
> Providers);
> // I'd actually return the matching `std::vector` (the 
> highest ranked provider that matched some includes in main file), and check 
> if the include of interest is part of that set for rest of the operations.
> // Since it represents both the provider and the include in the main file. 
> whereas the provider on it's own doesn't say anything about which include in 
> main file triggered satisfaction.
> ```
> and turn these call sites into
> ```
> auto Provider = firstSatisfiedProvider(ConvertedMainFileIncludes, Providers);
> if(!Provider || ReferencedInclude.match(Provider).empty())
>   return;
> // Include in question provides the symbol, do magic.
> ```
Is the comment under the code in the first snippet a mistake/outdated content? 
It confused me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147044

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


[PATCH] D144190: [AIX][clang] Storage Locations for Constant Pointers

2023-03-31 Thread Qiongsi Wu via Phabricator via cfe-commits
qiongsiwu1 added inline comments.



Comment at: clang/test/Driver/ppc-roptr.c:37
+// LINK: "-bforceimprw"
+// LTO_ROPTR: "-bplugin_opt:-mxcoff-roptr"
+// NO_ROPTR-NOT: "-mxcoff-roptr"

qiongsiwu1 wrote:
> hubert.reinterpretcast wrote:
> > This needs the backend option also renamed. Has a commit for that landed 
> > yet?
> No the commit has not landed. The patch is up 
> https://reviews.llvm.org/D147161. 
> This needs the backend option also renamed. Has a commit for that landed yet?

Thanks so much for the fast review Hubert! The commit has now landed. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144190

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


[PATCH] D147044: [clangd] Implement cross reference request for #include lines.

2023-03-31 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 510039.
VitaNuo added a comment.

Rename function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147044

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

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -43,6 +43,10 @@
 using ::testing::UnorderedElementsAreArray;
 using ::testing::UnorderedPointwise;
 
+std::string guard(llvm::StringRef Code) {
+  return "#pragma once\n" + Code.str();
+}
+
 MATCHER_P2(FileRange, File, Range, "") {
   return Location{URIForFile::canonicalize(File, testRoot()), Range} == arg;
 }
@@ -2293,6 +2297,50 @@
 checkFindRefs(Test);
 }
 
+TEST(FindReferences, UsedSymbolsFromInclude) {
+  const char *Tests[] = {
+  R"cpp([[#include ^"bar.h"]]
+#include 
+int fstBar = [[bar1]]();
+int sndBar = [[bar2]]();
+[[Bar]] bar;
+int macroBar = [[BAR]];
+std::vector vec;
+  )cpp",
+
+  R"cpp([[#in^clude ]]
+std::[[vector]] vec;
+  )cpp"};
+  for (const char *Test : Tests) {
+Annotations T(Test);
+auto TU = TestTU::withCode(T.code());
+TU.ExtraArgs.push_back("-std=c++20");
+TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+  #define BAR 5
+  int bar1();
+  int bar2();
+  class Bar {};
+)cpp");
+TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+  namespace std {
+template
+class vector{};
+  }
+)cpp");
+TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+auto AST = TU.build();
+std::vector> ExpectedLocations;
+for (const auto &R : T.ranges())
+  ExpectedLocations.push_back(AllOf(rangeIs(R), attrsAre(0u)));
+for (const auto &P : T.points()) 
+  EXPECT_THAT(findReferences(AST, P, 0).References,
+  UnorderedElementsAreArray(ExpectedLocations))
+  << "Failed for Refs at " << P << "\n"
+  << Test;
+  }
+}
+
 TEST(FindReferences, NeedsIndexForSymbols) {
   const char *Header = "int foo();";
   Annotations Main("int main() { [[f^oo]](); }");
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -10,12 +10,15 @@
 #include "FindSymbols.h"
 #include "FindTarget.h"
 #include "HeuristicResolver.h"
+#include "IncludeCleaner.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "Quality.h"
 #include "Selection.h"
 #include "SourceCode.h"
 #include "URI.h"
+#include "clang-include-cleaner/Analysis.h"
+#include "clang-include-cleaner/Types.h"
 #include "index/Index.h"
 #include "index/Merge.h"
 #include "index/Relation.h"
@@ -48,6 +51,7 @@
 #include "clang/Index/IndexingAction.h"
 #include "clang/Index/IndexingOptions.h"
 #include "clang/Index/USRGeneration.h"
+#include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
@@ -61,6 +65,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
+#include 
 #include 
 
 namespace clang {
@@ -1312,6 +1317,63 @@
 }
 } // namespace
 
+ReferencesResult maybeFindIncludeReferences(ParsedAST &AST, Position Pos,
+URIForFile URIMainFile) {
+  ReferencesResult Results;
+  const SourceManager &SM = AST.getSourceManager();
+  auto Includes = AST.getIncludeStructure().MainFileIncludes;
+  auto ConvertedMainFileIncludes = convertIncludes(SM, Includes);
+  for (auto &Inc : Includes) {
+if (Inc.HashLine != Pos.line)
+  continue;
+
+auto ReferencedInclude = convertIncludes(SM, Inc);
+include_cleaner::walkUsed(
+AST.getLocalTopLevelDecls(), collectMacroReferences(AST),
+AST.getPragmaIncludes(), SM,
+[&](const include_cleaner::SymbolReference &Ref,
+llvm::ArrayRef Providers) {
+  if (Ref.RT != include_cleaner::RefType::Explicit)
+return;
+
+  auto Provider =
+  firstMatchedProvider(ConvertedMainFileIncludes, Providers);
+  if (!Provider)
+return;
+
+  // Check if the referenced include matches this provider.
+  if (ReferencedInclude.match(*Provider).empty())
+return;
+
+  auto Loc = SM.getFileLoc(Ref.RefLocation);
+  // File locations can be outside of the main file if macro is
+  // expanded through an #include.
+  while (SM.getFileID(Loc) != SM.getMainFileID())
+Loc = SM.getIncludeLoc(SM.getFileID(Loc));
+
+  Reference

[PATCH] D147327: [clang-format] Add option for having one port per line in Verilog

2023-03-31 Thread sstwcw via Phabricator via cfe-commits
sstwcw updated this revision to Diff 510038.
sstwcw added a comment.

Generate doc


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147327

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/ConfigParseTest.cpp
  clang/unittests/Format/FormatTestVerilog.cpp

Index: clang/unittests/Format/FormatTestVerilog.cpp
===
--- clang/unittests/Format/FormatTestVerilog.cpp
+++ clang/unittests/Format/FormatTestVerilog.cpp
@@ -659,6 +659,77 @@
"  x = x;");
 }
 
+TEST_F(FormatTestVerilog, Instantiation) {
+  // Without ports.
+  verifyFormat("ffnand ff1;");
+  // With named ports.
+  verifyFormat("ffnand ff1(.qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2));");
+  // With wildcard.
+  verifyFormat("ffnand ff1(.qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2),\n"
+   "   .*);");
+  verifyFormat("ffnand ff1(.*,\n"
+   "   .qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2));");
+  // With unconnected ports.
+  verifyFormat("ffnand ff1(.q(),\n"
+   "   .qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2));");
+  verifyFormat("ffnand ff1(.q(),\n"
+   "   .qbar(),\n"
+   "   .clear(),\n"
+   "   .preset());");
+  verifyFormat("ffnand ff1(,\n"
+   "   .qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2));");
+  // With positional ports.
+  verifyFormat("ffnand ff1(out1,\n"
+   "   in1,\n"
+   "   in2);");
+  verifyFormat("ffnand ff1(,\n"
+   "   out1,\n"
+   "   in1,\n"
+   "   in2);");
+  // Multiple instantiations.
+  verifyFormat("ffnand ff1(.q(),\n"
+   "   .qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2)),\n"
+   "   ff1(.q(),\n"
+   "   .qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2));");
+  verifyFormat("ffnand //\n"
+   "ff1(.q(),\n"
+   ".qbar(out1),\n"
+   ".clear(in1),\n"
+   ".preset(in2)),\n"
+   "ff1(.q(),\n"
+   ".qbar(out1),\n"
+   ".clear(in1),\n"
+   ".preset(in2));");
+  // With breaking between instance ports disabled.
+  auto Style = getDefaultStyle();
+  Style.VerilogBreakBetweenInstancePorts = false;
+  verifyFormat("ffnand ff1;", Style);
+  verifyFormat("ffnand ff1(.qbar(out1), .clear(in1), .preset(in2), .*);",
+   Style);
+  verifyFormat("ffnand ff1(out1, in1, in2);", Style);
+  verifyFormat("ffnand ff1(.q(), .qbar(out1), .clear(in1), .preset(in2)),\n"
+   "   ff1(.q(), .qbar(out1), .clear(in1), .preset(in2));",
+   Style);
+  verifyFormat("ffnand //\n"
+   "ff1(.q(), .qbar(out1), .clear(in1), .preset(in2)),\n"
+   "ff1(.q(), .qbar(out1), .clear(in1), .preset(in2));",
+   Style);
+}
+
 TEST_F(FormatTestVerilog, Operators) {
   // Test that unary operators are not followed by space.
   verifyFormat("x = +x;");
Index: clang/unittests/Format/ConfigParseTest.cpp
===
--- clang/unittests/Format/ConfigParseTest.cpp
+++ clang/unittests/Format/ConfigParseTest.cpp
@@ -192,6 +192,7 @@
   CHECK_PARSE_BOOL(SpaceBeforeJsonColon);
   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
+  CHECK_PARSE_BOOL(VerilogBreakBetweenInstancePorts);
 
   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -311,6 +311,9 @@
   bool OperatorCalledAsMemberFunction =
   Prev->Previous && Prev->Previous->isOneOf(tok::period, tok::arrow);
   Contexts.back().IsExpression = OperatorCalledAsMemberFunction;
+} else if (OpeningParen.is(TT_VerilogInstancePortLParen)) {
+  Contexts.back().IsExpression = true;
+  Contexts.back().ContextType = Context::VerilogInstancePortList;
 } else if (Style.isJavaScript() &&
(Line.startsWith(Keywords.kw_type, tok

[PATCH] D147044: [clangd] Implement cross reference request for #include lines.

2023-03-31 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 510036.
VitaNuo added a comment.

Remove extra formatting changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147044

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

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -43,6 +43,10 @@
 using ::testing::UnorderedElementsAreArray;
 using ::testing::UnorderedPointwise;
 
+std::string guard(llvm::StringRef Code) {
+  return "#pragma once\n" + Code.str();
+}
+
 MATCHER_P2(FileRange, File, Range, "") {
   return Location{URIForFile::canonicalize(File, testRoot()), Range} == arg;
 }
@@ -2293,6 +2297,51 @@
 checkFindRefs(Test);
 }
 
+TEST(FindReferences, UsedSymbolsFromInclude) {
+  const char *Tests[] = {
+  R"cpp([[#include ^"bar.h"]]
+#include 
+int fstBar = [[bar1]]();
+int sndBar = [[bar2]]();
+[[Bar]] bar;
+int macroBar = [[BAR]];
+std::vector vec;
+  )cpp",
+
+  R"cpp([[#in^clude ]]
+std::[[vector]] vec;
+  )cpp"};
+  for (const char *Test : Tests) {
+Annotations T(Test);
+auto TU = TestTU::withCode(T.code());
+TU.ExtraArgs.push_back("-std=c++20");
+TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+  #define BAR 5
+  int bar1();
+  int bar2();
+  class Bar {};
+)cpp");
+TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+  namespace std {
+template
+class vector{};
+  }
+)cpp");
+TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+auto AST = TU.build();
+std::vector> ExpectedLocations;
+for (const auto &R : T.ranges())
+  ExpectedLocations.push_back(AllOf(rangeIs(R), attrsAre(0u)));
+for (const auto &P : T.points()) {
+  EXPECT_THAT(findReferences(AST, P, 0).References,
+  UnorderedElementsAreArray(ExpectedLocations))
+  << "Failed for Refs at " << P << "\n"
+  << Test;
+}
+  }
+}
+
 TEST(FindReferences, NeedsIndexForSymbols) {
   const char *Header = "int foo();";
   Annotations Main("int main() { [[f^oo]](); }");
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -10,12 +10,15 @@
 #include "FindSymbols.h"
 #include "FindTarget.h"
 #include "HeuristicResolver.h"
+#include "IncludeCleaner.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "Quality.h"
 #include "Selection.h"
 #include "SourceCode.h"
 #include "URI.h"
+#include "clang-include-cleaner/Analysis.h"
+#include "clang-include-cleaner/Types.h"
 #include "index/Index.h"
 #include "index/Merge.h"
 #include "index/Relation.h"
@@ -48,6 +51,7 @@
 #include "clang/Index/IndexingAction.h"
 #include "clang/Index/IndexingOptions.h"
 #include "clang/Index/USRGeneration.h"
+#include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
@@ -61,6 +65,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
+#include 
 #include 
 
 namespace clang {
@@ -1312,6 +1317,63 @@
 }
 } // namespace
 
+ReferencesResult maybeFindIncludeReferences(ParsedAST &AST, Position Pos,
+URIForFile URIMainFile) {
+  ReferencesResult Results;
+  const SourceManager &SM = AST.getSourceManager();
+  auto Includes = AST.getIncludeStructure().MainFileIncludes;
+  auto ConvertedMainFileIncludes = convertIncludes(SM, Includes);
+  for (auto &Inc : Includes) {
+if (Inc.HashLine != Pos.line)
+  continue;
+
+auto ReferencedInclude = convertIncludes(SM, Inc);
+include_cleaner::walkUsed(
+AST.getLocalTopLevelDecls(), collectMacroReferences(AST),
+AST.getPragmaIncludes(), SM,
+[&](const include_cleaner::SymbolReference &Ref,
+llvm::ArrayRef Providers) {
+  if (Ref.RT != include_cleaner::RefType::Explicit)
+return;
+
+  auto Provider =
+  firstSatisfiedProvider(ConvertedMainFileIncludes, Providers);
+  if (!Provider)
+return;
+
+  // Check if the referenced include matches this provider.
+  if (ReferencedInclude.match(*Provider).empty())
+return;
+
+  auto Loc = SM.getFileLoc(Ref.RefLocation);
+  // File locations can be outside of the main file if macro is
+  // expanded through an #include.
+  while (SM.getFileID(Loc) != SM.getMainFileID())
+Loc = SM.getIncludeLoc(SM.getFileID(Loc

[PATCH] D146042: [clang-format] Fix numerous issues with "LambdaBodyIndentation: OuterScope" option

2023-03-31 Thread Jon Phillips via Phabricator via cfe-commits
jp4a50 added a comment.

Could I get a re-review on this one please?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146042

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


[PATCH] D147329: [clang-format] Handle Verilog struct literals

2023-03-31 Thread sstwcw via Phabricator via cfe-commits
sstwcw created this revision.
Herald added subscribers: cfe-commits, ctetreau.
Herald added projects: All, clang, clang-format.
Herald added reviewers: rymiel, HazardyKnusperkeks, owenpan, MyDeveloperDay.
sstwcw requested review of this revision.

Previously `isVerilogIdentifier` was mistaking the apostrophe used in
struct literals as an identifier.  It is fixed.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147329

Files:
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/unittests/Format/FormatTestVerilog.cpp


Index: clang/unittests/Format/FormatTestVerilog.cpp
===
--- clang/unittests/Format/FormatTestVerilog.cpp
+++ clang/unittests/Format/FormatTestVerilog.cpp
@@ -902,6 +902,25 @@
   verifyFormat("{

[PATCH] D147044: [clangd] Implement cross reference request for #include lines.

2023-03-31 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 510032.
VitaNuo added a comment.

Simplify.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147044

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

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -43,6 +43,10 @@
 using ::testing::UnorderedElementsAreArray;
 using ::testing::UnorderedPointwise;
 
+std::string guard(llvm::StringRef Code) {
+  return "#pragma once\n" + Code.str();
+}
+
 MATCHER_P2(FileRange, File, Range, "") {
   return Location{URIForFile::canonicalize(File, testRoot()), Range} == arg;
 }
@@ -2293,6 +2297,51 @@
 checkFindRefs(Test);
 }
 
+TEST(FindReferences, UsedSymbolsFromInclude) {
+  const char *Tests[] = {
+  R"cpp([[#include ^"bar.h"]]
+#include 
+int fstBar = [[bar1]]();
+int sndBar = [[bar2]]();
+[[Bar]] bar;
+int macroBar = [[BAR]];
+std::vector vec;
+  )cpp",
+
+  R"cpp([[#in^clude ]]
+std::[[vector]] vec;
+  )cpp"};
+  for (const char *Test : Tests) {
+Annotations T(Test);
+auto TU = TestTU::withCode(T.code());
+TU.ExtraArgs.push_back("-std=c++20");
+TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+  #define BAR 5
+  int bar1();
+  int bar2();
+  class Bar {};
+)cpp");
+TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+  namespace std {
+template
+class vector{};
+  }
+)cpp");
+TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+auto AST = TU.build();
+std::vector> ExpectedLocations;
+for (const auto &R : T.ranges())
+  ExpectedLocations.push_back(AllOf(rangeIs(R), attrsAre(0u)));
+for (const auto &P : T.points()) {
+  EXPECT_THAT(findReferences(AST, P, 0).References,
+  UnorderedElementsAreArray(ExpectedLocations))
+  << "Failed for Refs at " << P << "\n"
+  << Test;
+}
+  }
+}
+
 TEST(FindReferences, NeedsIndexForSymbols) {
   const char *Header = "int foo();";
   Annotations Main("int main() { [[f^oo]](); }");
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -10,12 +10,15 @@
 #include "FindSymbols.h"
 #include "FindTarget.h"
 #include "HeuristicResolver.h"
+#include "IncludeCleaner.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "Quality.h"
 #include "Selection.h"
 #include "SourceCode.h"
 #include "URI.h"
+#include "clang-include-cleaner/Analysis.h"
+#include "clang-include-cleaner/Types.h"
 #include "index/Index.h"
 #include "index/Merge.h"
 #include "index/Relation.h"
@@ -48,6 +51,7 @@
 #include "clang/Index/IndexingAction.h"
 #include "clang/Index/IndexingOptions.h"
 #include "clang/Index/USRGeneration.h"
+#include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
@@ -61,6 +65,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
+#include 
 #include 
 
 namespace clang {
@@ -1312,6 +1317,63 @@
 }
 } // namespace
 
+ReferencesResult maybeFindIncludeReferences(ParsedAST &AST, Position Pos,
+URIForFile URIMainFile) {
+  ReferencesResult Results;
+  const SourceManager &SM = AST.getSourceManager();
+  auto Includes = AST.getIncludeStructure().MainFileIncludes;
+  auto ConvertedMainFileIncludes = convertIncludes(SM, Includes);
+  for (auto &Inc : Includes) {
+if (Inc.HashLine != Pos.line)
+  continue;
+
+auto ReferencedInclude = convertIncludes(SM, Inc);
+include_cleaner::walkUsed(
+AST.getLocalTopLevelDecls(), collectMacroReferences(AST),
+AST.getPragmaIncludes(), SM,
+[&](const include_cleaner::SymbolReference &Ref,
+llvm::ArrayRef Providers) {
+  if (Ref.RT != include_cleaner::RefType::Explicit)
+return;
+
+  auto Provider =
+  firstSatisfiedProvider(ConvertedMainFileIncludes, Providers);
+  if (!Provider)
+return;
+
+  // Check if the referenced include matches this provider.
+  if (ReferencedInclude.match(*Provider).empty())
+return;
+
+  auto Loc = SM.getFileLoc(Ref.RefLocation);
+  // File locations can be outside of the main file if macro is
+  // expanded through an #include.
+  while (SM.getFileID(Loc) != SM.getMainFileID())
+Loc = SM.getIncludeLoc(SM.getFileID(Loc));
+
+  Refere

[PATCH] D147328: [clang-format] Handle enum in Verilog

2023-03-31 Thread sstwcw via Phabricator via cfe-commits
sstwcw created this revision.
Herald added projects: All, clang, clang-format.
Herald added a subscriber: cfe-commits.
Herald added reviewers: rymiel, HazardyKnusperkeks, owenpan, MyDeveloperDay.
sstwcw requested review of this revision.

Verilog has enum just like C.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147328

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTestVerilog.cpp


Index: clang/unittests/Format/FormatTestVerilog.cpp
===
--- clang/unittests/Format/FormatTestVerilog.cpp
+++ clang/unittests/Format/FormatTestVerilog.cpp
@@ -338,6 +338,20 @@
 "x = x;");
 }
 
+TEST_F(FormatTestVerilog, Enum) {
+  verifyFormat("enum { x } x;");
+  verifyFormat("typedef enum { x } x;");
+  verifyFormat("enum { red, yellow, green } x;");
+  verifyFormat("typedef enum { red, yellow, green } x;");
+  verifyFormat("enum integer { x } x;");
+  verifyFormat("typedef enum { x = 0 } x;");
+  verifyFormat("typedef enum { red = 0, yellow = 1, green = 2 } x;");
+  verifyFormat("typedef enum integer { x } x;");
+  verifyFormat("typedef enum bit [0 : 1] { x } x;");
+  verifyFormat("typedef enum { add = 10, sub[5], jmp[6 : 8] } E1;");
+  verifyFormat("typedef enum { add = 10, sub[5] = 0, jmp[6 : 8] = 1 } E1;");
+}
+
 TEST_F(FormatTestVerilog, Headers) {
   // Test headers with multiple ports.
   verifyFormat("module mh1\n"
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1709,8 +1709,8 @@
   // enum definition can start a structural element.
   if (!parseEnum())
 break;
-  // This only applies for C++.
-  if (!Style.isCpp()) {
+  // This only applies for C++ and Verilog.
+  if (!Style.isCpp() && !Style.isVerilog()) {
 addUnwrappedLine();
 return;
   }
@@ -3541,7 +3541,15 @@
  FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
 tok::greater, tok::comma, tok::question,
 tok::l_square, tok::r_square)) {
-nextToken();
+if (Style.isVerilog()) {
+  FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
+  nextToken();
+  // In Verilog the base type can have dimensions.
+  while (FormatTok->is(tok::l_square))
+parseSquare();
+} else {
+  nextToken();
+}
 // We can have macros or attributes in between 'enum' and the enum name.
 if (FormatTok->is(tok::l_paren))
   parseParens();


Index: clang/unittests/Format/FormatTestVerilog.cpp
===
--- clang/unittests/Format/FormatTestVerilog.cpp
+++ clang/unittests/Format/FormatTestVerilog.cpp
@@ -338,6 +338,20 @@
 "x = x;");
 }
 
+TEST_F(FormatTestVerilog, Enum) {
+  verifyFormat("enum { x } x;");
+  verifyFormat("typedef enum { x } x;");
+  verifyFormat("enum { red, yellow, green } x;");
+  verifyFormat("typedef enum { red, yellow, green } x;");
+  verifyFormat("enum integer { x } x;");
+  verifyFormat("typedef enum { x = 0 } x;");
+  verifyFormat("typedef enum { red = 0, yellow = 1, green = 2 } x;");
+  verifyFormat("typedef enum integer { x } x;");
+  verifyFormat("typedef enum bit [0 : 1] { x } x;");
+  verifyFormat("typedef enum { add = 10, sub[5], jmp[6 : 8] } E1;");
+  verifyFormat("typedef enum { add = 10, sub[5] = 0, jmp[6 : 8] = 1 } E1;");
+}
+
 TEST_F(FormatTestVerilog, Headers) {
   // Test headers with multiple ports.
   verifyFormat("module mh1\n"
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1709,8 +1709,8 @@
   // enum definition can start a structural element.
   if (!parseEnum())
 break;
-  // This only applies for C++.
-  if (!Style.isCpp()) {
+  // This only applies for C++ and Verilog.
+  if (!Style.isCpp() && !Style.isVerilog()) {
 addUnwrappedLine();
 return;
   }
@@ -3541,7 +3541,15 @@
  FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
 tok::greater, tok::comma, tok::question,
 tok::l_square, tok::r_square)) {
-nextToken();
+if (Style.isVerilog()) {
+  FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
+  nextToken();
+  // In Verilog the base type can have dimensions.
+  while (FormatTok->is(tok::l_square))
+parseSquare();
+} else {
+  nextToken();
+}
 // We can have macros or attributes in between 'enum' and the enum name.
 if (FormatTok->is(tok::l_paren))
   parseParens();
___
cfe-commits mailing list
c

[PATCH] D147327: [clang-format] Add option for having one port on a line in Verilog

2023-03-31 Thread sstwcw via Phabricator via cfe-commits
sstwcw created this revision.
Herald added projects: All, clang, clang-format.
Herald added a subscriber: cfe-commits.
Herald added reviewers: rymiel, HazardyKnusperkeks, owenpan, MyDeveloperDay.
sstwcw requested review of this revision.
Herald added a comment.

NOTE: Clang-Format Team Automated Review Comment

Your review contains a change to clang/include/clang/Format/Format.h but does 
not contain an update to ClangFormatStyleOptions.rst

ClangFormatStyleOptions.rst is generated via 
clang/docs/tools/dump_format_style.py,  please run this to regenerate the .rst

You can validate that the rst is valid by running.

  ./docs/tools/dump_format_style.py
  mkdir -p html
  /usr/bin/sphinx-build -n ./docs ./html


We added the option `VerilogBreakBetweenInstancePorts` to put ports on
separate lines in module instantiations.  We made it default to true
because style guides mostly recommend it that way for example:

https://github.com/lowRISC/style-guides/blob/master/VerilogCodingStyle.md#module-instantiation


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147327

Files:
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/ConfigParseTest.cpp
  clang/unittests/Format/FormatTestVerilog.cpp

Index: clang/unittests/Format/FormatTestVerilog.cpp
===
--- clang/unittests/Format/FormatTestVerilog.cpp
+++ clang/unittests/Format/FormatTestVerilog.cpp
@@ -659,6 +659,77 @@
"  x = x;");
 }
 
+TEST_F(FormatTestVerilog, Instantiation) {
+  // Without ports.
+  verifyFormat("ffnand ff1;");
+  // With named ports.
+  verifyFormat("ffnand ff1(.qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2));");
+  // With wildcard.
+  verifyFormat("ffnand ff1(.qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2),\n"
+   "   .*);");
+  verifyFormat("ffnand ff1(.*,\n"
+   "   .qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2));");
+  // With unconnected ports.
+  verifyFormat("ffnand ff1(.q(),\n"
+   "   .qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2));");
+  verifyFormat("ffnand ff1(.q(),\n"
+   "   .qbar(),\n"
+   "   .clear(),\n"
+   "   .preset());");
+  verifyFormat("ffnand ff1(,\n"
+   "   .qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2));");
+  // With positional ports.
+  verifyFormat("ffnand ff1(out1,\n"
+   "   in1,\n"
+   "   in2);");
+  verifyFormat("ffnand ff1(,\n"
+   "   out1,\n"
+   "   in1,\n"
+   "   in2);");
+  // Multiple instantiations.
+  verifyFormat("ffnand ff1(.q(),\n"
+   "   .qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2)),\n"
+   "   ff1(.q(),\n"
+   "   .qbar(out1),\n"
+   "   .clear(in1),\n"
+   "   .preset(in2));");
+  verifyFormat("ffnand //\n"
+   "ff1(.q(),\n"
+   ".qbar(out1),\n"
+   ".clear(in1),\n"
+   ".preset(in2)),\n"
+   "ff1(.q(),\n"
+   ".qbar(out1),\n"
+   ".clear(in1),\n"
+   ".preset(in2));");
+  // With breaking between instance ports disabled.
+  auto Style = getDefaultStyle();
+  Style.VerilogBreakBetweenInstancePorts = false;
+  verifyFormat("ffnand ff1;", Style);
+  verifyFormat("ffnand ff1(.qbar(out1), .clear(in1), .preset(in2), .*);",
+   Style);
+  verifyFormat("ffnand ff1(out1, in1, in2);", Style);
+  verifyFormat("ffnand ff1(.q(), .qbar(out1), .clear(in1), .preset(in2)),\n"
+   "   ff1(.q(), .qbar(out1), .clear(in1), .preset(in2));",
+   Style);
+  verifyFormat("ffnand //\n"
+   "ff1(.q(), .qbar(out1), .clear(in1), .preset(in2)),\n"
+   "ff1(.q(), .qbar(out1), .clear(in1), .preset(in2));",
+   Style);
+}
+
 TEST_F(FormatTestVerilog, Operators) {
   // Test that unary operators are not followed by space.
   verifyFormat("x = +x;");
Index: clang/unittests/Format/ConfigParseTest.cpp
===
--- clang/unittests/Format/ConfigParseTest.cpp
+++ clang/unittests/Format/ConfigParseTest.cpp
@@ -192,6 +192,7 @@
   CHECK_PARSE_BOOL(SpaceBeforeJsonColon);
   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
+  CHECK_PARSE_BOOL(Ver

[PATCH] D147326: [clang][dataflow][NFC] Share code between Environment ctor and pushCallInternal().

2023-03-31 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The deduplicated code is moved into initVars().

As an added bonus, pushCallInternal() now also gets the "Add all fields
mentioned in default member initializers" behavior, which apparently had been
added to the Environment ctor but not pushCallInternal().


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147326

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp

Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -203,7 +203,33 @@
 
 // FIXME: Add support for resetting globals after function calls to enable
 // the implementation of sound analyses.
-void Environment::initVars(llvm::DenseSet Vars) {
+void Environment::initVars(const FunctionDecl *FuncDecl) {
+  assert(FuncDecl->getBody() != nullptr);
+
+  llvm::DenseSet Fields;
+  llvm::DenseSet Vars;
+
+  // Look for global variable and field references in the
+  // constructor-initializers.
+  if (const auto *CtorDecl = dyn_cast(FuncDecl)) {
+for (const auto *Init : CtorDecl->inits()) {
+  if (const auto *M = Init->getAnyMember())
+  Fields.insert(M);
+  const Expr *E = Init->getInit();
+  assert(E != nullptr);
+  getFieldsAndGlobalVars(*E, Fields, Vars);
+}
+// Add all fields mentioned in default member initializers.
+for (const FieldDecl *F : CtorDecl->getParent()->fields())
+  if (const auto *I = F->getInClassInitializer())
+  getFieldsAndGlobalVars(*I, Fields, Vars);
+  }
+  getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
+
+  // These have to be added before the lines that follow to ensure that
+  // `create*` work correctly for structs.
+  DACtx->addModeledFields(Fields);
+
   for (const VarDecl *D : Vars) {
 if (getStorageLocation(*D, SkipPast::None) != nullptr)
   continue;
@@ -239,31 +265,7 @@
   if (const auto *FuncDecl = dyn_cast(&DeclCtx)) {
 assert(FuncDecl->getBody() != nullptr);
 
-llvm::DenseSet Fields;
-llvm::DenseSet Vars;
-
-// Look for global variable and field references in the
-// constructor-initializers.
-if (const auto *CtorDecl = dyn_cast(&DeclCtx)) {
-  for (const auto *Init : CtorDecl->inits()) {
-if (const auto *M = Init->getAnyMember())
-  Fields.insert(M);
-const Expr *E = Init->getInit();
-assert(E != nullptr);
-getFieldsAndGlobalVars(*E, Fields, Vars);
-  }
-  // Add all fields mentioned in default member initializers.
-  for (const FieldDecl *F  : CtorDecl->getParent()->fields())
-if (const auto *I = F->getInClassInitializer())
-  getFieldsAndGlobalVars(*I, Fields, Vars);
-}
-getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
-
-// These have to be added before the lines that follow to ensure that
-// `create*` work correctly for structs.
-DACtx.addModeledFields(Fields);
-
-initVars(Vars);
+initVars(FuncDecl);
 
 for (const auto *ParamDecl : FuncDecl->parameters()) {
   assert(ParamDecl != nullptr);
@@ -337,26 +339,7 @@
ArrayRef Args) {
   CallStack.push_back(FuncDecl);
 
-  // FIXME: Share this code with the constructor, rather than duplicating it.
-  llvm::DenseSet Fields;
-  llvm::DenseSet Vars;
-  // Look for global variable references in the constructor-initializers.
-  if (const auto *CtorDecl = dyn_cast(FuncDecl)) {
-for (const auto *Init : CtorDecl->inits()) {
-  if (const auto *M = Init->getAnyMember())
-Fields.insert(M);
-  const Expr *E = Init->getInit();
-  assert(E != nullptr);
-  getFieldsAndGlobalVars(*E, Fields, Vars);
-}
-  }
-  getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
-
-  // These have to be added before the lines that follow to ensure that
-  // `create*` work correctly for structs.
-  DACtx->addModeledFields(Fields);
-
-  initVars(Vars);
+  initVars(FuncDecl);
 
   const auto *ParamIt = FuncDecl->param_begin();
 
Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -460,8 +460,9 @@
   void pushCallInternal(const FunctionDecl *FuncDecl,
 ArrayRef Args);
 
-  /// Assigns storage locations and values to all variables in `Vars`.
-  void initVars(llvm::DenseSet Vars);
+  /// Assigns storage locations and values to all 

[PATCH] D147325: Implement cross reference request for #include lines.

2023-03-31 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo abandoned this revision.
VitaNuo added a comment.

Erroneously created patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147325

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


[PATCH] D147044: [clangd] Implement cross reference request for #include lines.

2023-03-31 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 510027.
VitaNuo marked 10 inline comments as done.
VitaNuo added a comment.

Address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147044

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

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -43,6 +43,10 @@
 using ::testing::UnorderedElementsAreArray;
 using ::testing::UnorderedPointwise;
 
+std::string guard(llvm::StringRef Code) {
+  return "#pragma once\n" + Code.str();
+}
+
 MATCHER_P2(FileRange, File, Range, "") {
   return Location{URIForFile::canonicalize(File, testRoot()), Range} == arg;
 }
@@ -2293,6 +2297,51 @@
 checkFindRefs(Test);
 }
 
+TEST(FindReferences, UsedSymbolsFromInclude) {
+  const char *Tests[] = {
+  R"cpp([[#include ^"bar.h"]]
+#include 
+int fstBar = [[bar1]]();
+int sndBar = [[bar2]]();
+[[Bar]] bar;
+int macroBar = [[BAR]];
+std::vector vec;
+  )cpp",
+
+  R"cpp([[#in^clude ]]
+std::[[vector]] vec;
+  )cpp"};
+  for (const char *Test : Tests) {
+Annotations T(Test);
+auto TU = TestTU::withCode(T.code());
+TU.ExtraArgs.push_back("-std=c++20");
+TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+  #define BAR 5
+  int bar1();
+  int bar2();
+  class Bar {};
+)cpp");
+TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+  namespace std {
+template
+class vector{};
+  }
+)cpp");
+TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+auto AST = TU.build();
+std::vector> ExpectedLocations;
+for (const auto &R : T.ranges())
+  ExpectedLocations.push_back(AllOf(rangeIs(R), attrsAre(0u)));
+for (const auto &P : T.points()) {
+  EXPECT_THAT(findReferences(AST, P, 0).References,
+  UnorderedElementsAreArray(ExpectedLocations))
+  << "Failed for Refs at " << P << "\n"
+  << Test;
+}
+  }
+}
+
 TEST(FindReferences, NeedsIndexForSymbols) {
   const char *Header = "int foo();";
   Annotations Main("int main() { [[f^oo]](); }");
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -10,12 +10,15 @@
 #include "FindSymbols.h"
 #include "FindTarget.h"
 #include "HeuristicResolver.h"
+#include "IncludeCleaner.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "Quality.h"
 #include "Selection.h"
 #include "SourceCode.h"
 #include "URI.h"
+#include "clang-include-cleaner/Analysis.h"
+#include "clang-include-cleaner/Types.h"
 #include "index/Index.h"
 #include "index/Merge.h"
 #include "index/Relation.h"
@@ -48,6 +51,7 @@
 #include "clang/Index/IndexingAction.h"
 #include "clang/Index/IndexingOptions.h"
 #include "clang/Index/USRGeneration.h"
+#include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
@@ -61,6 +65,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
+#include 
 #include 
 
 namespace clang {
@@ -1312,6 +1317,63 @@
 }
 } // namespace
 
+ReferencesResult maybeFindIncludeReferences(ParsedAST &AST, Position Pos,
+URIForFile URIMainFile) {
+  ReferencesResult Results;
+  const SourceManager &SM = AST.getSourceManager();
+  auto Includes = AST.getIncludeStructure().MainFileIncludes;
+  auto ConvertedMainFileIncludes = convertIncludes(SM, Includes);
+  for (auto &Inc : Includes) {
+if (Inc.HashLine != Pos.line)
+  continue;
+
+auto ReferencedInclude = convertIncludes(SM, Inc);
+include_cleaner::walkUsed(
+AST.getLocalTopLevelDecls(), collectMacroReferences(AST),
+AST.getPragmaIncludes(), SM,
+[&](const include_cleaner::SymbolReference &Ref,
+llvm::ArrayRef Providers) {
+  if (Ref.RT != include_cleaner::RefType::Explicit)
+return;
+
+  auto Provider =
+  firstSatisfiedProvider(ConvertedMainFileIncludes, Providers);
+  if (!Provider)
+return;
+
+  // Check if the referenced include matches this provider.
+  if (ReferencedInclude.match(*Provider).empty())
+return;
+
+  auto Loc = SM.getFileLoc(Ref.RefLocation);
+  // File locations can be outside of the main file if macro is
+  // expanded through an #include.
+  while (SM.getFileID(Loc) != SM.getMainFileID())
+Loc 

[PATCH] D147325: Implement cross reference request for #include lines.

2023-03-31 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo created this revision.
Herald added subscribers: kadircet, arphaman.
Herald added a project: All.
VitaNuo requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147325

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

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -43,6 +43,10 @@
 using ::testing::UnorderedElementsAreArray;
 using ::testing::UnorderedPointwise;
 
+std::string guard(llvm::StringRef Code) {
+  return "#pragma once\n" + Code.str();
+}
+
 MATCHER_P2(FileRange, File, Range, "") {
   return Location{URIForFile::canonicalize(File, testRoot()), Range} == arg;
 }
@@ -2293,6 +2297,51 @@
 checkFindRefs(Test);
 }
 
+TEST(FindReferences, UsedSymbolsFromInclude) {
+  const char *Tests[] = {
+  R"cpp([[#include ^"bar.h"]]
+#include 
+int fstBar = [[bar1]]();
+int sndBar = [[bar2]]();
+[[Bar]] bar;
+int macroBar = [[BAR]];
+std::vector vec;
+  )cpp",
+
+  R"cpp([[#in^clude ]]
+std::[[vector]] vec;
+  )cpp"};
+  for (const char *Test : Tests) {
+Annotations T(Test);
+auto TU = TestTU::withCode(T.code());
+TU.ExtraArgs.push_back("-std=c++20");
+TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+  #define BAR 5
+  int bar1();
+  int bar2();
+  class Bar {};
+)cpp");
+TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+  namespace std {
+template
+class vector{};
+  }
+)cpp");
+TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+auto AST = TU.build();
+std::vector> ExpectedLocations;
+for (const auto &R : T.ranges())
+  ExpectedLocations.push_back(AllOf(rangeIs(R), attrsAre(0u)));
+for (const auto &P : T.points()) {
+  EXPECT_THAT(findReferences(AST, P, 0).References,
+  UnorderedElementsAreArray(ExpectedLocations))
+  << "Failed for Refs at " << P << "\n"
+  << Test;
+}
+  }
+}
+
 TEST(FindReferences, NeedsIndexForSymbols) {
   const char *Header = "int foo();";
   Annotations Main("int main() { [[f^oo]](); }");
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -10,12 +10,15 @@
 #include "FindSymbols.h"
 #include "FindTarget.h"
 #include "HeuristicResolver.h"
+#include "IncludeCleaner.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "Quality.h"
 #include "Selection.h"
 #include "SourceCode.h"
 #include "URI.h"
+#include "clang-include-cleaner/Analysis.h"
+#include "clang-include-cleaner/Types.h"
 #include "index/Index.h"
 #include "index/Merge.h"
 #include "index/Relation.h"
@@ -48,6 +51,7 @@
 #include "clang/Index/IndexingAction.h"
 #include "clang/Index/IndexingOptions.h"
 #include "clang/Index/USRGeneration.h"
+#include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
@@ -61,6 +65,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
+#include 
 #include 
 
 namespace clang {
@@ -1312,6 +1317,63 @@
 }
 } // namespace
 
+ReferencesResult maybeFindIncludeReferences(ParsedAST &AST, Position Pos,
+URIForFile URIMainFile) {
+  ReferencesResult Results;
+  const SourceManager &SM = AST.getSourceManager();
+  auto Includes = AST.getIncludeStructure().MainFileIncludes;
+  auto ConvertedMainFileIncludes = convertIncludes(SM, Includes);
+  for (auto &Inc : Includes) {
+if (Inc.HashLine != Pos.line)
+  continue;
+
+auto ReferencedInclude = convertIncludes(SM, Inc);
+include_cleaner::walkUsed(
+AST.getLocalTopLevelDecls(), collectMacroReferences(AST),
+AST.getPragmaIncludes(), SM,
+[&](const include_cleaner::SymbolReference &Ref,
+llvm::ArrayRef Providers) {
+  if (Ref.RT != include_cleaner::RefType::Explicit)
+return;
+
+  auto Provider =
+  firstSatisfiedProvider(ConvertedMainFileIncludes, Providers);
+  if (!Provider)
+return;
+
+  // Check if the referenced include matches this provider.
+  if (ReferencedInclude.match(*Provider).empty())
+return;
+
+  auto Loc = SM.getFileLoc(Ref.RefLocation);
+  // File locations can be outside of the main file if macro is
+  // expanded through an #include.
+  while (SM.getFileID(Loc) != SM.getMainFil

[PATCH] D142617: [clang][Interp] Check This pointer without creating InterpFrame

2023-03-31 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 rG943ef0642010: [clang][Interp] Check This pointer without 
creating InterpFrame (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142617

Files:
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/InterpStack.cpp
  clang/lib/AST/Interp/InterpStack.h


Index: clang/lib/AST/Interp/InterpStack.h
===
--- clang/lib/AST/Interp/InterpStack.h
+++ clang/lib/AST/Interp/InterpStack.h
@@ -64,11 +64,16 @@
 
   /// Returns a reference to the value on the top of the stack.
   template  T &peek() const {
-return *reinterpret_cast(peek(aligned_size()));
+return *reinterpret_cast(peekData(aligned_size()));
+  }
+
+  template  T &peek(size_t Offset) const {
+assert(aligned(Offset));
+return *reinterpret_cast(peekData(Offset));
   }
 
   /// Returns a pointer to the top object.
-  void *top() const { return Chunk ? peek(0) : nullptr; }
+  void *top() const { return Chunk ? peekData(0) : nullptr; }
 
   /// Returns the size of the stack in bytes.
   size_t size() const { return StackSize; }
@@ -90,7 +95,7 @@
   /// Grows the stack to accommodate a value and returns a pointer to it.
   void *grow(size_t Size);
   /// Returns a pointer from the top of the stack.
-  void *peek(size_t Size) const;
+  void *peekData(size_t Size) const;
   /// Shrinks the stack.
   void shrink(size_t Size);
 
Index: clang/lib/AST/Interp/InterpStack.cpp
===
--- clang/lib/AST/Interp/InterpStack.cpp
+++ clang/lib/AST/Interp/InterpStack.cpp
@@ -46,7 +46,7 @@
   return Object;
 }
 
-void *InterpStack::peek(size_t Size) const {
+void *InterpStack::peekData(size_t Size) const {
   assert(Chunk && "Stack is empty!");
 
   StackChunk *Ptr = Chunk;
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -1492,10 +1492,11 @@
 }
 
 inline bool Call(InterpState &S, CodePtr &PC, const Function *Func) {
-  auto NewFrame = std::make_unique(S, Func, PC);
-  Pointer ThisPtr;
   if (Func->hasThisPointer()) {
-ThisPtr = NewFrame->getThis();
+size_t ThisOffset =
+Func->getArgSize() + (Func->hasRVO() ? primSize(PT_Ptr) : 0);
+const Pointer &ThisPtr = S.Stk.peek(ThisOffset);
+
 if (!CheckInvoke(S, PC, ThisPtr))
   return false;
 
@@ -1506,6 +1507,7 @@
   if (!CheckCallable(S, PC, Func))
 return false;
 
+  auto NewFrame = std::make_unique(S, Func, PC);
   InterpFrame *FrameBefore = S.Current;
   S.Current = NewFrame.get();
 


Index: clang/lib/AST/Interp/InterpStack.h
===
--- clang/lib/AST/Interp/InterpStack.h
+++ clang/lib/AST/Interp/InterpStack.h
@@ -64,11 +64,16 @@
 
   /// Returns a reference to the value on the top of the stack.
   template  T &peek() const {
-return *reinterpret_cast(peek(aligned_size()));
+return *reinterpret_cast(peekData(aligned_size()));
+  }
+
+  template  T &peek(size_t Offset) const {
+assert(aligned(Offset));
+return *reinterpret_cast(peekData(Offset));
   }
 
   /// Returns a pointer to the top object.
-  void *top() const { return Chunk ? peek(0) : nullptr; }
+  void *top() const { return Chunk ? peekData(0) : nullptr; }
 
   /// Returns the size of the stack in bytes.
   size_t size() const { return StackSize; }
@@ -90,7 +95,7 @@
   /// Grows the stack to accommodate a value and returns a pointer to it.
   void *grow(size_t Size);
   /// Returns a pointer from the top of the stack.
-  void *peek(size_t Size) const;
+  void *peekData(size_t Size) const;
   /// Shrinks the stack.
   void shrink(size_t Size);
 
Index: clang/lib/AST/Interp/InterpStack.cpp
===
--- clang/lib/AST/Interp/InterpStack.cpp
+++ clang/lib/AST/Interp/InterpStack.cpp
@@ -46,7 +46,7 @@
   return Object;
 }
 
-void *InterpStack::peek(size_t Size) const {
+void *InterpStack::peekData(size_t Size) const {
   assert(Chunk && "Stack is empty!");
 
   StackChunk *Ptr = Chunk;
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -1492,10 +1492,11 @@
 }
 
 inline bool Call(InterpState &S, CodePtr &PC, const Function *Func) {
-  auto NewFrame = std::make_unique(S, Func, PC);
-  Pointer ThisPtr;
   if (Func->hasThisPointer()) {
-ThisPtr = NewFrame->getThis();
+size_t ThisOffset =
+Func->getArgSize() + (Func->hasRVO() ? primSize(PT_Ptr) : 0);
+const Pointer &ThisPtr = S.Stk.peek(ThisOffset);
+
 if (!CheckInvoke(S, PC, ThisPtr))
   return false;
 
@@ 

[clang] 943ef06 - [clang][Interp] Check This pointer without creating InterpFrame

2023-03-31 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-03-31T16:18:15+02:00
New Revision: 943ef06420105cad23e3caea24d6a274cdb0316f

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

LOG: [clang][Interp] Check This pointer without creating InterpFrame

The InterpFrame was only created so early so we could use getThis().
However, we need to know the Function when creating the InterpFrame and
in the case of virtual functions, we need to determine what function to
call at interpretation time.

Get the This pointer ourselves and just create the InterpFrame later.

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

Added: 


Modified: 
clang/lib/AST/Interp/Interp.h
clang/lib/AST/Interp/InterpStack.cpp
clang/lib/AST/Interp/InterpStack.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index bb34737e018b..afc5f24baf73 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1492,10 +1492,11 @@ inline bool CheckGlobalCtor(InterpState &S, CodePtr 
&PC) {
 }
 
 inline bool Call(InterpState &S, CodePtr &PC, const Function *Func) {
-  auto NewFrame = std::make_unique(S, Func, PC);
-  Pointer ThisPtr;
   if (Func->hasThisPointer()) {
-ThisPtr = NewFrame->getThis();
+size_t ThisOffset =
+Func->getArgSize() + (Func->hasRVO() ? primSize(PT_Ptr) : 0);
+const Pointer &ThisPtr = S.Stk.peek(ThisOffset);
+
 if (!CheckInvoke(S, PC, ThisPtr))
   return false;
 
@@ -1506,6 +1507,7 @@ inline bool Call(InterpState &S, CodePtr &PC, const 
Function *Func) {
   if (!CheckCallable(S, PC, Func))
 return false;
 
+  auto NewFrame = std::make_unique(S, Func, PC);
   InterpFrame *FrameBefore = S.Current;
   S.Current = NewFrame.get();
 

diff  --git a/clang/lib/AST/Interp/InterpStack.cpp 
b/clang/lib/AST/Interp/InterpStack.cpp
index 7fe678e62192..63a088be6705 100644
--- a/clang/lib/AST/Interp/InterpStack.cpp
+++ b/clang/lib/AST/Interp/InterpStack.cpp
@@ -46,7 +46,7 @@ void *InterpStack::grow(size_t Size) {
   return Object;
 }
 
-void *InterpStack::peek(size_t Size) const {
+void *InterpStack::peekData(size_t Size) const {
   assert(Chunk && "Stack is empty!");
 
   StackChunk *Ptr = Chunk;

diff  --git a/clang/lib/AST/Interp/InterpStack.h 
b/clang/lib/AST/Interp/InterpStack.h
index e625ffd8e421..435120d0e441 100644
--- a/clang/lib/AST/Interp/InterpStack.h
+++ b/clang/lib/AST/Interp/InterpStack.h
@@ -64,11 +64,16 @@ class InterpStack final {
 
   /// Returns a reference to the value on the top of the stack.
   template  T &peek() const {
-return *reinterpret_cast(peek(aligned_size()));
+return *reinterpret_cast(peekData(aligned_size()));
+  }
+
+  template  T &peek(size_t Offset) const {
+assert(aligned(Offset));
+return *reinterpret_cast(peekData(Offset));
   }
 
   /// Returns a pointer to the top object.
-  void *top() const { return Chunk ? peek(0) : nullptr; }
+  void *top() const { return Chunk ? peekData(0) : nullptr; }
 
   /// Returns the size of the stack in bytes.
   size_t size() const { return StackSize; }
@@ -90,7 +95,7 @@ class InterpStack final {
   /// Grows the stack to accommodate a value and returns a pointer to it.
   void *grow(size_t Size);
   /// Returns a pointer from the top of the stack.
-  void *peek(size_t Size) const;
+  void *peekData(size_t Size) const;
   /// Shrinks the stack.
   void shrink(size_t Size);
 



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


[PATCH] D147324: [OpenMP][MLIR][Flang][bbc][Driver] Add OpenMP RTL Flags to Flang and generate omp.FlagsAttr from them

2023-03-31 Thread Andrew Gozillon via Phabricator via cfe-commits
agozillon added a comment.

The flag addition and FlagsAttr generation component of: 
https://reviews.llvm.org/D145264 the LLVM-IR generation will come in a 
subsequent phabricator patch once I have created some additional tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147324

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


[PATCH] D147324: [OpenMP][MLIR][Flang][bbc][Driver] Add OpenMP RTL Flags to Flang and generate omp.FlagsAttr from them

2023-03-31 Thread Andrew Gozillon via Phabricator via cfe-commits
agozillon created this revision.
Herald added subscribers: sunshaoce, bzcheeseman, rriddle, guansong, yaxunl.
Herald added a reviewer: sscalpone.
Herald added a reviewer: awarzynski.
Herald added a reviewer: kiranchandramohan.
Herald added projects: Flang, All.
agozillon requested review of this revision.
Herald added subscribers: cfe-commits, jplehr, sstefan1, stephenneuendorffer, 
jdoerfert, MaskRay.
Herald added a reviewer: jdoerfert.
Herald added a project: clang.

This patch ports OpenMP RTL flags from the shared Clang compiler
options to Flang. As well as adding a limited subset to bbc.

This patch enables the flags below (and any equals or inverse variants)
for Flang that exist in Clang:

-fopenmp-target-debug
-fopenmp-assume-threads-oversubscription
-fopenmp-assume-teams-oversubscription
-fopenmp-assume-no-nested-parallelism
-fopenmp-assume-no-thread-state

For the bbc tool it only utilises the primary variants to minimize
additional complexity in the tool.

The patch also provides FlagAttr generation from these flags. Which
will be lowered to LLVM-IR in a subsequent patch.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147324

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/LangOptions.def
  flang/include/flang/Tools/CrossToolHelpers.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Driver/driver-help.f90
  flang/test/Driver/omp-frontend-forwarding.f90
  flang/test/Lower/OpenMP/rtl-flags.f90
  flang/tools/bbc/bbc.cpp

Index: flang/tools/bbc/bbc.cpp
===
--- flang/tools/bbc/bbc.cpp
+++ flang/tools/bbc/bbc.cpp
@@ -129,6 +129,38 @@
llvm::cl::desc("enable openmp device compilation"),
llvm::cl::init(false));
 
+// A simplified subset of the OpenMP RTL Flags from Flang, only the primary
+// positive options are available, no negative options e.g. fopen_assume* vs
+// fno_open_assume*
+static llvm::cl::opt setOpenMPTargetDebug(
+"fopenmp-target-debug",
+llvm::cl::desc("Enable debugging in the OpenMP offloading device RTL"),
+llvm::cl::init(0));
+
+static llvm::cl::opt setOpenMPThreadSubscription(
+"fopenmp-assume-threads-oversubscription",
+llvm::cl::desc("Assume work-shared loops do not have more "
+   "iterations than participating threads."),
+llvm::cl::init(false));
+
+static llvm::cl::opt setOpenMPTeamSubscription(
+"fopenmp-assume-teams-oversubscription",
+llvm::cl::desc("Assume distributed loops do not have more iterations than "
+   "participating teams."),
+llvm::cl::init(false));
+
+static llvm::cl::opt setOpenMPNoThreadState(
+"fopenmp-assume-no-thread-state",
+llvm::cl::desc(
+"Assume that no thread in a parallel region will modify an ICV."),
+llvm::cl::init(false));
+
+static llvm::cl::opt setOpenMPNoNestedParallelism(
+"fopenmp-assume-no-nested-parallelism",
+llvm::cl::desc("Assume that no thread in a parallel region will encounter "
+   "a parallel region."),
+llvm::cl::init(false));
+
 static llvm::cl::opt enableOpenACC("fopenacc",
  llvm::cl::desc("enable openacc"),
  llvm::cl::init(false));
@@ -244,8 +276,13 @@
   kindMap, loweringOptions, {});
   burnside.lower(parseTree, semanticsContext);
   mlir::ModuleOp mlirModule = burnside.getModule();
-  if (enableOpenMP)
-setOffloadModuleInterfaceAttributes(mlirModule, enableOpenMPDevice);
+  if (enableOpenMP) {
+auto offloadModuleOpts =
+OffloadModuleOpts(setOpenMPTargetDebug, setOpenMPTeamSubscription,
+  setOpenMPThreadSubscription, setOpenMPNoThreadState,
+  setOpenMPNoNestedParallelism, enableOpenMPDevice);
+setOffloadModuleInterfaceAttributes(mlirModule, offloadModuleOpts);
+  }
   std::error_code ec;
   std::string outputName = outputFilename;
   if (!outputName.size())
Index: flang/test/Lower/OpenMP/rtl-flags.f90
===
--- /dev/null
+++ flang/test/Lower/OpenMP/rtl-flags.f90
@@ -0,0 +1,29 @@
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-is-device %s -o - | FileCheck %s --check-prefix=DEFAULT-DEVICE-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp %s -o - | FileCheck %s --check-prefix=DEFAULT-HOST-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-target-debug -fopenmp-is-device %s -o - | FileCheck %s --check-prefix=DBG-DEVICE-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-target-debug=111 -fopenmp-is-device %s -o - | FileCheck %s --check-prefix=DBG-EQ-DEVICE-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-assume-teams-oversubscription -fopenmp-is-device %s -o - | FileCheck %s --check-prefix=TEAMS-OSUB-DEVICE-FIR
+!RUN: %flang_fc1 -emit-fir -fopenmp -fopenmp-assume-thread

[PATCH] D146101: [clang-format] Add BracedInitializerIndentWidth option.

2023-03-31 Thread Jon Phillips via Phabricator via cfe-commits
jp4a50 updated this revision to Diff 510022.
jp4a50 added a comment.

Alphabetical ordering.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146101

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/docs/tools/dump_format_style.py
  clang/include/clang/Format/Format.h
  clang/lib/Format/ContinuationIndenter.cpp
  clang/lib/Format/Format.cpp
  clang/unittests/Format/ConfigParseTest.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -4855,6 +4855,191 @@
"[5] = ee};");
 }
 
+TEST_F(FormatTest, BracedInitializerIndentWidth) {
+  auto Style = getLLVMStyleWithColumns(60);
+  Style.BinPackArguments = true;
+  Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
+  Style.BracedInitializerIndentWidth = 6;
+
+  // Non-initializing braces are unaffected by BracedInitializerIndentWidth.
+  verifyFormat("enum class {\n"
+   "  One,\n"
+   "  Two,\n"
+   "};\n",
+   Style);
+  verifyFormat("class Foo {\n"
+   "  Foo() {}\n"
+   "  void bar();\n"
+   "};\n",
+   Style);
+  verifyFormat("void foo() {\n"
+   "  auto bar = baz;\n"
+   "  return baz;\n"
+   "};\n",
+   Style);
+  verifyFormat("auto foo = [&] {\n"
+   "  auto bar = baz;\n"
+   "  return baz;\n"
+   "};\n",
+   Style);
+  verifyFormat("{\n"
+   "  auto bar = baz;\n"
+   "  return baz;\n"
+   "};\n",
+   Style);
+  // Non-brace initialization is unaffected by BracedInitializerIndentWidth.
+  verifyFormat("SomeClass clazz(\n"
+   "\"xx\", \"yy\",\n"
+   "\"zz\");\n",
+   Style);
+
+  // The following types of initialization are all affected by
+  // BracedInitializerIndentWidth. Aggregate initialization.
+  verifyFormat("int LongVariable[2] = {\n"
+   "  1000, 2000};",
+   Style);
+  verifyFormat("SomeStruct s{\n"
+   "  \"\", \"\",\n"
+   "  \"\"};\n",
+   Style);
+  // Designated initializers.
+  verifyFormat("int LongVariable[1] = {\n"
+   "  [0] = 1000, [1] = 2000};",
+   Style);
+  verifyFormat("SomeStruct s{\n"
+   "  .foo = \"x\",\n"
+   "  .bar = \"y\",\n"
+   "  .baz = \"z\"};\n",
+   Style);
+  // List initialization.
+  verifyFormat("SomeStruct s{\n"
+   "  \"x\",\n"
+   "  \"y\",\n"
+   "  \"z\",\n"
+   "};\n",
+   Style);
+  verifyFormat("SomeStruct{\n"
+   "  \"x\",\n"
+   "  \"y\",\n"
+   "  \"z\",\n"
+   "};\n",
+   Style);
+  verifyFormat("new SomeStruct{\n"
+   "  \"x\",\n"
+   "  \"y\",\n"
+   "  \"z\",\n"
+   "};\n",
+   Style);
+  // Member initializer.
+  verifyFormat("class SomeClass {\n"
+   "  SomeStruct s{\n"
+   "\"x\",\n"
+   "\"y\",\n"
+   "\"z\",\n"
+   "  };\n"
+   "};\n",
+   Style);
+  // Constructor member initializer.
+  verifyFormat("SomeClass::SomeClass : strct{\n"
+   " \"x\",\n"
+   " \"y\",\n"
+   " \"z\",\n"
+   "   } {}\n",
+   Style);
+  // Copy initialization.
+  verifyFormat("SomeStruct s = SomeStruct{\n"
+   "  \"x\",\n"
+   "  \"y\",\n"
+   "  \"z\",\n"
+   "};\n",
+   Style);
+  // Copy list initialization.
+  verifyFormat("SomeStruct s = {\n"
+   "  \"x\",\n"
+   "  \"y\",\n"
+   "  \"z\",\n"
+   "};\n",
+   Style);
+  // Assignment operand initialization.
+  verifyFormat("s = {\n"
+   "  \"x\",\n"
+   " 

[PATCH] D144522: [clang-tidy] Add readability-operators-representation check

2023-03-31 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added a comment.

@carlosgalvezp
Thank you, by any chance would you be able to look into other reviews ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144522

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


[PATCH] D142448: [clang][Interp] Handle TypeTraitExprs

2023-03-31 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 rG8d2899acbcf1: [clang][Interp] Handle TypeTraitExprs 
(authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142448

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  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
@@ -743,3 +743,26 @@
   static_assert(get3() == 3, "");
 #endif
 };
+
+namespace TypeTraits {
+  static_assert(__is_trivial(int), "");
+  static_assert(__is_trivial(float), "");
+  static_assert(__is_trivial(E), "");
+  struct S{};
+  static_assert(__is_trivial(S), "");
+  struct S2 {
+S2() {}
+  };
+  static_assert(!__is_trivial(S2), "");
+
+  template 
+  struct S3 {
+constexpr bool foo() const { return __is_trivial(T); }
+  };
+  struct T {
+~T() {}
+  };
+  struct U {};
+  static_assert(S3{}.foo(), "");
+  static_assert(!S3{}.foo(), "");
+}
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -92,6 +92,7 @@
   bool VisitExprWithCleanups(const ExprWithCleanups *E);
   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
+  bool VisitTypeTraitExpr(const TypeTraitExpr *E);
 
 protected:
   bool visitExpr(const Expr *E) override;
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -897,6 +897,11 @@
   return false;
 }
 
+template 
+bool ByteCodeExprGen::VisitTypeTraitExpr(const TypeTraitExpr *E) {
+  return this->emitConstBool(E->getValue(), E);
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
   if (E->containsErrors())
 return false;


Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -743,3 +743,26 @@
   static_assert(get3() == 3, "");
 #endif
 };
+
+namespace TypeTraits {
+  static_assert(__is_trivial(int), "");
+  static_assert(__is_trivial(float), "");
+  static_assert(__is_trivial(E), "");
+  struct S{};
+  static_assert(__is_trivial(S), "");
+  struct S2 {
+S2() {}
+  };
+  static_assert(!__is_trivial(S2), "");
+
+  template 
+  struct S3 {
+constexpr bool foo() const { return __is_trivial(T); }
+  };
+  struct T {
+~T() {}
+  };
+  struct U {};
+  static_assert(S3{}.foo(), "");
+  static_assert(!S3{}.foo(), "");
+}
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -92,6 +92,7 @@
   bool VisitExprWithCleanups(const ExprWithCleanups *E);
   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
+  bool VisitTypeTraitExpr(const TypeTraitExpr *E);
 
 protected:
   bool visitExpr(const Expr *E) override;
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -897,6 +897,11 @@
   return false;
 }
 
+template 
+bool ByteCodeExprGen::VisitTypeTraitExpr(const TypeTraitExpr *E) {
+  return this->emitConstBool(E->getValue(), E);
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) {
   if (E->containsErrors())
 return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8d2899a - [clang][Interp] Handle TypeTraitExprs

2023-03-31 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-03-31T15:54:44+02:00
New Revision: 8d2899acbcf1b8ce120bc219aeb30207d4422042

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

LOG: [clang][Interp] Handle TypeTraitExprs

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

Added: 


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

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 1b605a9e0927..733247787d76 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -897,6 +897,11 @@ bool ByteCodeExprGen::VisitCompoundLiteralExpr(
   return false;
 }
 
+template 
+bool ByteCodeExprGen::VisitTypeTraitExpr(const TypeTraitExpr *E) {
+  return this->emitConstBool(E->getValue(), E);
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
   if (E->containsErrors())
 return false;

diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 03d2eb87b5e1..4baf5d433c9e 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -92,6 +92,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitExprWithCleanups(const ExprWithCleanups *E);
   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
+  bool VisitTypeTraitExpr(const TypeTraitExpr *E);
 
 protected:
   bool visitExpr(const Expr *E) override;

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index fc36c13ed07b..5883c1879b92 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -743,3 +743,26 @@ namespace CompoundLiterals {
   static_assert(get3() == 3, "");
 #endif
 };
+
+namespace TypeTraits {
+  static_assert(__is_trivial(int), "");
+  static_assert(__is_trivial(float), "");
+  static_assert(__is_trivial(E), "");
+  struct S{};
+  static_assert(__is_trivial(S), "");
+  struct S2 {
+S2() {}
+  };
+  static_assert(!__is_trivial(S2), "");
+
+  template 
+  struct S3 {
+constexpr bool foo() const { return __is_trivial(T); }
+  };
+  struct T {
+~T() {}
+  };
+  struct U {};
+  static_assert(S3{}.foo(), "");
+  static_assert(!S3{}.foo(), "");
+}



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


[PATCH] D141215: [clang-repl] Introduce Value to capture expression results

2023-03-31 Thread Jun Zhang via Phabricator via cfe-commits
junaire updated this revision to Diff 510017.
junaire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141215

Files:
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Interpreter/Interpreter.h
  clang/include/clang/Interpreter/Value.h
  clang/include/clang/Parse/Parser.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Frontend/PrintPreprocessedOutput.cpp
  clang/lib/Interpreter/CMakeLists.txt
  clang/lib/Interpreter/IncrementalExecutor.cpp
  clang/lib/Interpreter/IncrementalExecutor.h
  clang/lib/Interpreter/IncrementalParser.cpp
  clang/lib/Interpreter/IncrementalParser.h
  clang/lib/Interpreter/Interpreter.cpp
  clang/lib/Interpreter/InterpreterUtils.cpp
  clang/lib/Interpreter/InterpreterUtils.h
  clang/lib/Interpreter/Value.cpp
  clang/lib/Lex/PPLexerChange.cpp
  clang/lib/Parse/ParseCXXInlineMethods.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Parse/Parser.cpp
  clang/tools/clang-repl/CMakeLists.txt
  clang/unittests/Interpreter/CMakeLists.txt
  clang/unittests/Interpreter/InterpreterTest.cpp

Index: clang/unittests/Interpreter/InterpreterTest.cpp
===
--- clang/unittests/Interpreter/InterpreterTest.cpp
+++ clang/unittests/Interpreter/InterpreterTest.cpp
@@ -17,6 +17,7 @@
 #include "clang/AST/Mangle.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/TextDiagnosticPrinter.h"
+#include "clang/Interpreter/Value.h"
 #include "clang/Sema/Lookup.h"
 #include "clang/Sema/Sema.h"
 
@@ -33,6 +34,10 @@
 #define CLANG_INTERPRETER_NO_SUPPORT_EXEC
 #endif
 
+int Global = 42;
+int getGlobal() { return Global; }
+void setGlobal(int val) { Global = val; }
+
 namespace {
 using Args = std::vector;
 static std::unique_ptr
@@ -276,8 +281,7 @@
   std::vector Args = {"-fno-delayed-template-parsing"};
   std::unique_ptr Interp = createInterpreter(Args);
 
-  llvm::cantFail(Interp->Parse("void* operator new(__SIZE_TYPE__, void* __p);"
-   "extern \"C\" int printf(const char*,...);"
+  llvm::cantFail(Interp->Parse("extern \"C\" int printf(const char*,...);"
"class A {};"
"struct B {"
"  template"
@@ -314,4 +318,38 @@
   free(NewA);
 }
 
+TEST(InterpreterTest, Value) {
+  std::unique_ptr Interp = createInterpreter();
+
+  Value V1;
+  llvm::cantFail(Interp->ParseAndExecute("int x = 42;"));
+  llvm::cantFail(Interp->ParseAndExecute("x", &V1));
+  EXPECT_EQ(V1.getInt(), 42);
+  EXPECT_TRUE(V1.getType()->isIntegerType());
+
+  Value V2;
+  llvm::cantFail(Interp->ParseAndExecute("double y = 3.14;"));
+  llvm::cantFail(Interp->ParseAndExecute("y", &V2));
+  EXPECT_EQ(V2.getAs(), 3.14);
+  EXPECT_TRUE(V2.getType()->isFloatingType());
+  EXPECT_EQ(V2.castAs(), 3);
+
+  llvm::cantFail(Interp->ParseAndExecute("int getGlobal();"));
+  llvm::cantFail(Interp->ParseAndExecute("void setGlobal(int);"));
+  Value V3;
+  llvm::cantFail(Interp->ParseAndExecute("getGlobal()", &V3));
+  EXPECT_EQ(V3.getInt(), 42);
+  EXPECT_TRUE(V3.getType()->isIntegerType());
+
+  // Change the global from the compiled code.
+  setGlobal(43);
+  Value V4;
+  llvm::cantFail(Interp->ParseAndExecute("getGlobal()", &V4));
+  EXPECT_EQ(V4.getInt(), 43);
+  EXPECT_TRUE(V4.getType()->isIntegerType());
+
+  // Change the global from the interpreted code.
+  llvm::cantFail(Interp->ParseAndExecute("setGlobal(44);"));
+  EXPECT_EQ(getGlobal(), 44);
+}
 } // end anonymous namespace
Index: clang/unittests/Interpreter/CMakeLists.txt
===
--- clang/unittests/Interpreter/CMakeLists.txt
+++ clang/unittests/Interpreter/CMakeLists.txt
@@ -22,3 +22,5 @@
 if(NOT WIN32)
   add_subdirectory(ExceptionTests)
 endif()
+
+export_executable_symbols(ClangReplInterpreterTests)
Index: clang/tools/clang-repl/CMakeLists.txt
===
--- clang/tools/clang-repl/CMakeLists.txt
+++ clang/tools/clang-repl/CMakeLists.txt
@@ -12,6 +12,7 @@
   )
 
 clang_target_link_libraries(clang-repl PRIVATE
+  clangAST
   clangBasic
   clangFrontend
   clangInterpreter
Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -320,6 +320,7 @@
 case tok::annot_module_begin:
 case tok::annot_module_end:
 case tok::annot_module_include:
+case tok::annot_input_end:
   // Stop before we change submodules. They generally indicate a "good"
   // place to pick up parsing again (except in the special case where
   // we're trying to skip to EOF).
@@ -616,8 +617,8 @@
 
   // Skip over the EOF token, flagging end of previous input for incremental
   // processing
-  if (PP.isIncrementalProcessingEnabled(

[PATCH] D141215: [clang-repl] Introduce Value to capture expression results

2023-03-31 Thread Jun Zhang via Phabricator via cfe-commits
junaire marked 9 inline comments as done.
junaire added inline comments.



Comment at: clang/include/clang/Interpreter/Interpreter.h:119
+
+  std::unique_ptr GenModule();
+

v.g.vassilev wrote:
> We should not need this interface.
`Interpreter::CompileDecl` needs it. So we don't have to do a dummy 
`Interp.Parse("")` to get a llvm::Module.



Comment at: clang/lib/Parse/ParseStmt.cpp:551
+ConsumeAnyToken();
+setPrettyPrintMode();
+  } else {

v.g.vassilev wrote:
> I think the cleaner solution here is to remove the global flag and pass it 
> `handleExprStmt` and extend `Sema::ActOnExprStmt`.
I dont understand, can you elaborate a bit?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141215

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


[PATCH] D141215: [clang-repl] Introduce Value to capture expression results

2023-03-31 Thread Jun Zhang via Phabricator via cfe-commits
junaire updated this revision to Diff 510014.
junaire added a comment.

Address more comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141215

Files:
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Interpreter/Interpreter.h
  clang/include/clang/Interpreter/Value.h
  clang/include/clang/Parse/Parser.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Frontend/PrintPreprocessedOutput.cpp
  clang/lib/Interpreter/CMakeLists.txt
  clang/lib/Interpreter/IncrementalExecutor.cpp
  clang/lib/Interpreter/IncrementalExecutor.h
  clang/lib/Interpreter/IncrementalParser.cpp
  clang/lib/Interpreter/IncrementalParser.h
  clang/lib/Interpreter/Interpreter.cpp
  clang/lib/Interpreter/InterpreterUtils.cpp
  clang/lib/Interpreter/InterpreterUtils.h
  clang/lib/Interpreter/Value.cpp
  clang/lib/Lex/PPLexerChange.cpp
  clang/lib/Parse/ParseCXXInlineMethods.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Parse/Parser.cpp
  clang/tools/clang-repl/CMakeLists.txt
  clang/unittests/Interpreter/CMakeLists.txt
  clang/unittests/Interpreter/InterpreterTest.cpp

Index: clang/unittests/Interpreter/InterpreterTest.cpp
===
--- clang/unittests/Interpreter/InterpreterTest.cpp
+++ clang/unittests/Interpreter/InterpreterTest.cpp
@@ -17,6 +17,7 @@
 #include "clang/AST/Mangle.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/TextDiagnosticPrinter.h"
+#include "clang/Interpreter/Value.h"
 #include "clang/Sema/Lookup.h"
 #include "clang/Sema/Sema.h"
 
@@ -33,6 +34,10 @@
 #define CLANG_INTERPRETER_NO_SUPPORT_EXEC
 #endif
 
+int Global = 42;
+int getGlobal() { return Global; }
+void setGlobal(int val) { Global = val; }
+
 namespace {
 using Args = std::vector;
 static std::unique_ptr
@@ -276,8 +281,7 @@
   std::vector Args = {"-fno-delayed-template-parsing"};
   std::unique_ptr Interp = createInterpreter(Args);
 
-  llvm::cantFail(Interp->Parse("void* operator new(__SIZE_TYPE__, void* __p);"
-   "extern \"C\" int printf(const char*,...);"
+  llvm::cantFail(Interp->Parse("extern \"C\" int printf(const char*,...);"
"class A {};"
"struct B {"
"  template"
@@ -314,4 +318,38 @@
   free(NewA);
 }
 
+TEST(InterpreterTest, Value) {
+  std::unique_ptr Interp = createInterpreter();
+
+  Value V1;
+  llvm::cantFail(Interp->ParseAndExecute("int x = 42;"));
+  llvm::cantFail(Interp->ParseAndExecute("x", &V1));
+  EXPECT_EQ(V1.getInt(), 42);
+  EXPECT_TRUE(V1.getType()->isIntegerType());
+
+  Value V2;
+  llvm::cantFail(Interp->ParseAndExecute("double y = 3.14;"));
+  llvm::cantFail(Interp->ParseAndExecute("y", &V2));
+  EXPECT_EQ(V2.getAs(), 3.14);
+  EXPECT_TRUE(V2.getType()->isFloatingType());
+  EXPECT_EQ(V2.castAs(), 3);
+
+  llvm::cantFail(Interp->ParseAndExecute("int getGlobal();"));
+  llvm::cantFail(Interp->ParseAndExecute("void setGlobal(int);"));
+  Value V3;
+  llvm::cantFail(Interp->ParseAndExecute("getGlobal()", &V3));
+  EXPECT_EQ(V3.getInt(), 42);
+  EXPECT_TRUE(V3.getType()->isIntegerType());
+
+  // Change the global from the compiled code.
+  setGlobal(43);
+  Value V4;
+  llvm::cantFail(Interp->ParseAndExecute("getGlobal()", &V4));
+  EXPECT_EQ(V4.getInt(), 43);
+  EXPECT_TRUE(V4.getType()->isIntegerType());
+
+  // Change the global from the interpreted code.
+  llvm::cantFail(Interp->ParseAndExecute("setGlobal(44);"));
+  EXPECT_EQ(getGlobal(), 44);
+}
 } // end anonymous namespace
Index: clang/unittests/Interpreter/CMakeLists.txt
===
--- clang/unittests/Interpreter/CMakeLists.txt
+++ clang/unittests/Interpreter/CMakeLists.txt
@@ -22,3 +22,5 @@
 if(NOT WIN32)
   add_subdirectory(ExceptionTests)
 endif()
+
+export_executable_symbols(ClangReplInterpreterTests)
Index: clang/tools/clang-repl/CMakeLists.txt
===
--- clang/tools/clang-repl/CMakeLists.txt
+++ clang/tools/clang-repl/CMakeLists.txt
@@ -12,6 +12,7 @@
   )
 
 clang_target_link_libraries(clang-repl PRIVATE
+  clangAST
   clangBasic
   clangFrontend
   clangInterpreter
Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -320,6 +320,7 @@
 case tok::annot_module_begin:
 case tok::annot_module_end:
 case tok::annot_module_include:
+case tok::annot_input_end:
   // Stop before we change submodules. They generally indicate a "good"
   // place to pick up parsing again (except in the special case where
   // we're trying to skip to EOF).
@@ -616,8 +617,8 @@
 
   // Skip over the EOF token, flagging end of previous input for incremental
   // processing
-  if (PP.isIncrementalPro

  1   2   >