[PATCH] D125418: [Arm64EC 6/?] Implement C/C++ mangling for Arm64EC function definitions.

2022-08-31 Thread chenglin.bi via Phabricator via cfe-commits
bcl5980 added a comment.

In D125418#3759174 , @efriedma wrote:

> The reason struct returns require register shuffling is that AArch64 passes 
> the sret pointer in x8 (i.e. RAX), but the x64 calling convention expects in 
> in RCX (i.e. x0).

So, for the function: s64 f(int a):
AArch64 CC:void f(x8, x0)
X64 CC:void f(rcx[x0], rdx[x1])
AArch64 --> X64 we need to add instructions before blr

  mov x1, x0
  mov x0, x8

It can match `iexit_thunk$cdecl$m64$i8` when we call extern function not a 
function pointer.

> Have you tried to see if the Microsoft-generated thunk actually works?  I 
> found at least one bug in MSVC thunk generation and reported it to Microsoft. 
>  (Microsoft didn't acknowledge the report, but that's a different story...)

You are right. For now, I haven't tested too much case runtime. But it looks if 
a DLL import function pass to a function pointer, then call it will cause 
access violation.
Based on the debug result, it should be exit thunk issue, MSVC generate wrong 
thunk type.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125418

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


[PATCH] D132997: [clang][Interp] Handle DeclRefExpr of reference types

2022-08-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaron.ballman, shafik, erichkeane, tahonermann.
Herald added a project: All.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

And add a couple of tests for it.

Notably, this is missing `MaterializeTemporaryExpr` and `ExprWithCleanups`, but 
the basic support seems to work.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132997

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

Index: clang/test/AST/Interp/references.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/references.cpp
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+
+// expected-no-diagnostics
+// ref-no-diagnostics
+
+constexpr int a = 10;
+constexpr const int &b = a;
+static_assert(a == b, "");
+
+constexpr int assignToReference() {
+  int a = 20;
+  int &b =a;
+
+  b = 100;
+  return a;
+}
+static_assert(assignToReference() == 100, "");
+
+
+constexpr void setValue(int &dest, int val) {
+  dest = val;
+}
+
+constexpr int checkSetValue() {
+  int l = 100;
+  setValue(l, 200);
+  return l;
+}
+static_assert(checkSetValue() == 200, "");
+
+constexpr int readLocalRef() {
+  int a = 20;
+  int &b = a;
+  return b;
+}
+static_assert(readLocalRef() == 20, "");
+
+constexpr int incRef() {
+  int a = 0;
+  int &b = a;
+
+  b = b + 1;
+
+  return a;
+}
+static_assert(incRef() == 1, "");
+
+
+template
+constexpr void Plus3(int &A) {
+  A = V + 3;
+}
+constexpr int foo = 4;
+
+constexpr int callTemplate() {
+  int a = 3;
+  Plus3(a);
+  return a;
+}
+static_assert(callTemplate() == 7, "");
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -845,15 +845,38 @@
 template 
 bool ByteCodeExprGen::VisitDeclRefExpr(const DeclRefExpr *E) {
   const auto *Decl = E->getDecl();
+  bool IsReference = Decl->getType()->isReferenceType();
+  bool FoundDecl = false;
 
   if (auto It = Locals.find(Decl); It != Locals.end()) {
 const unsigned Offset = It->second.Offset;
-return this->emitGetPtrLocal(Offset, E);
+if (!this->emitGetPtrLocal(Offset, E))
+  return false;
+
+FoundDecl = true;
   } else if (auto GlobalIndex = P.getGlobal(Decl)) {
-return this->emitGetPtrGlobal(*GlobalIndex, E);
+if (!this->emitGetPtrGlobal(*GlobalIndex, E))
+  return false;
+
+FoundDecl = true;
   } else if (const auto *PVD = dyn_cast(Decl)) {
-if (auto It = this->Params.find(PVD); It != this->Params.end())
-  return this->emitGetPtrParam(It->second, E);
+if (auto It = this->Params.find(PVD); It != this->Params.end()) {
+  if (!this->emitGetPtrParam(It->second, E))
+return false;
+
+  FoundDecl = true;
+}
+  }
+
+  // References are implemented using pointers, so when we get here,
+  // we have a pointer to a pointer, which we need to de-reference once.
+  if (FoundDecl) {
+if (IsReference) {
+  if (!this->emitLoadPop(PT_Ptr, E))
+return false;
+}
+
+return true;
   }
 
   return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132998: [clang-tidy] Restrict use-equals-default to c++11-or-later

2022-08-31 Thread Alexander Shaposhnikov via Phabricator via cfe-commits
alexander-shaposhnikov created this revision.
alexander-shaposhnikov added reviewers: gribozavr2, njames93, aaron.ballman.
alexander-shaposhnikov created this object with visibility "All Users".
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a project: All.
alexander-shaposhnikov requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Restrict use-equals-default to c++11-or-later.

Test plan: ninja check-all


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132998

Files:
  clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx98.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx98.cpp
===
--- /dev/null
+++ 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx98.cpp
@@ -0,0 +1,8 @@
+// RUN: %check_clang_tidy -std=c++98 %s modernize-use-equals-default %t
+
+struct S {
+  S() {}
+  // CHECK-FIXES: S() {}
+  ~S() {}
+  // CHECK-FIXES: ~S() {}
+};
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -139,7 +139,7 @@
 - Improved `modernize-use-equals-default 
`_ check.
 
   The check now skips unions since in this case a default constructor with 
empty body
-  is not equivalent to the explicitly defaulted one.
+  is not equivalent to the explicitly defaulted one. The check is restricted 
to c++11-or-later.
 
 Removed checks
 ^^
Index: clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
@@ -38,7 +38,7 @@
 public:
   UseEqualsDefaultCheck(StringRef Name, ClangTidyContext *Context);
   bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
-return LangOpts.CPlusPlus;
+return LangOpts.CPlusPlus11;
   }
   void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;


Index: clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx98.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-cxx98.cpp
@@ -0,0 +1,8 @@
+// RUN: %check_clang_tidy -std=c++98 %s modernize-use-equals-default %t
+
+struct S {
+  S() {}
+  // CHECK-FIXES: S() {}
+  ~S() {}
+  // CHECK-FIXES: ~S() {}
+};
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -139,7 +139,7 @@
 - Improved `modernize-use-equals-default `_ check.
 
   The check now skips unions since in this case a default constructor with empty body
-  is not equivalent to the explicitly defaulted one.
+  is not equivalent to the explicitly defaulted one. The check is restricted to c++11-or-later.
 
 Removed checks
 ^^
Index: clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h
@@ -38,7 +38,7 @@
 public:
   UseEqualsDefaultCheck(StringRef Name, ClangTidyContext *Context);
   bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
-return LangOpts.CPlusPlus;
+return LangOpts.CPlusPlus11;
   }
   void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a5ab650 - [clang] Fix a crash in constant evaluation

2022-08-31 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2022-08-31T10:09:24+02:00
New Revision: a5ab650714d05c2e49ec158dc99156118a893027

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

LOG: [clang] Fix a crash in constant evaluation

This was showing up in our internal crash collector. I have no idea how
to test it out though, open for suggestions if there are easy paths but
otherwise I'd move forward with the patch.

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

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 3df0e4292b6ca..2b1a30f8354fb 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4794,6 +4794,11 @@ static bool getDefaultInitValue(QualType T, APValue 
&Result) {
   Result = APValue((const FieldDecl *)nullptr);
   return true;
 }
+// Can't access properties of an incomplete type.
+if (!RD->hasDefinition()) {
+  Result = APValue();
+  return false;
+}
 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  std::distance(RD->field_begin(), RD->field_end()));
 



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


[PATCH] D132918: [clang] Fix a crash in constant evaluation

2022-08-31 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa5ab650714d0: [clang] Fix a crash in constant evaluation 
(authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132918

Files:
  clang/lib/AST/ExprConstant.cpp


Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -4794,6 +4794,11 @@
   Result = APValue((const FieldDecl *)nullptr);
   return true;
 }
+// Can't access properties of an incomplete type.
+if (!RD->hasDefinition()) {
+  Result = APValue();
+  return false;
+}
 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  std::distance(RD->field_begin(), RD->field_end()));
 


Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -4794,6 +4794,11 @@
   Result = APValue((const FieldDecl *)nullptr);
   return true;
 }
+// Can't access properties of an incomplete type.
+if (!RD->hasDefinition()) {
+  Result = APValue();
+  return false;
+}
 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  std::distance(RD->field_begin(), RD->field_end()));
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D129664: [Clang] Adjust extension warnings for delimited sequences

2022-08-31 Thread Jakub Jelínek via Phabricator via cfe-commits
jakubjelinek added a comment.

While accepting all these inside of string and character literals in C and 
C++20 and older is fine, accepting them inside of identifiers can change 
meaning of valid programs.
https://gcc.gnu.org/pipermail/gcc-patches/2022-August/600620.html
#define z(x) 0
#define a z(
int x = a\N{LATIN SMALL LETTER U WITH DIAERESIS});
int y = a\u{1234});
int z = a\U{12345678});


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129664

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


[clang] b58ed43 - Revert "[clang] Fix a crash in constant evaluation"

2022-08-31 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2022-08-31T10:12:52+02:00
New Revision: b58ed43a7f6b67bdb03ab746b654c823f54c261f

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

LOG: Revert "[clang] Fix a crash in constant evaluation"

This reverts commit a5ab650714d05c2e49ec158dc99156118a893027.

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 2b1a30f8354fb..3df0e4292b6ca 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4794,11 +4794,6 @@ static bool getDefaultInitValue(QualType T, APValue 
&Result) {
   Result = APValue((const FieldDecl *)nullptr);
   return true;
 }
-// Can't access properties of an incomplete type.
-if (!RD->hasDefinition()) {
-  Result = APValue();
-  return false;
-}
 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
  std::distance(RD->field_begin(), RD->field_end()));
 



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


[PATCH] D132918: [clang] Fix a crash in constant evaluation

2022-08-31 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

sorry, i missed the other comments around having a lit test. reverting the 
change.




Comment at: clang/lib/AST/ExprConstant.cpp:4797
 }
+// Can't access properties of an incomplete type.
+if (!RD->hasDefinition()) {

shafik wrote:
> erichkeane wrote:
> > It seems to me that we shouldn't GET to this function with an incomplete 
> > type.  I suspect whoever calls this is doing so incorrectly.
> Also note we only check in `ExprConstant.cpp` for `hasDefinition()` in one 
> other place in `findCompleteObject` and that is around extern see: 
> https://github.com/llvm/llvm-project/commit/c0d04a2567c22631595bed8092bc042bb91ea4ee#diff-255a21a02a8966766225831836d482547787baf9a770fbf67178ebb7d7347e27
> It seems to me that we shouldn't GET to this function with an incomplete 
> type. I suspect whoever calls this is doing so incorrectly.

Agreed, that's also my assumption. but we've been unable to get a minimal 
crasher. i am not a fan of landing these changes without reproducers but this 
was clearly fixing the issue we had (moreover, it's happening on invalid code).

moreover we're checking for recorddecl being invalid up above, so it felt quite 
likely to hit this code path with incomplete types as well (or there were some 
changes up the callstack that forgot to update the implementation here).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132918

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


[PATCH] D132950: Remove unnecessary `REQUIRES: x86-registered-target` from ps4/ps5 driver tests.

2022-08-31 Thread Ying Yi via Phabricator via cfe-commits
MaggieYi added a comment.

Thanks Paul.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132950

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


[PATCH] D132998: [clang-tidy] Restrict use-equals-default to c++11-or-later

2022-08-31 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

There's going to be contention with this. The modernize module is designed for 
converting pre c++11 codebases to c++11, can't really do that if the check is 
disabled on those older codebases.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132998

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


[PATCH] D132950: Remove unnecessary `REQUIRES: x86-registered-target` from ps4/ps5 driver tests.

2022-08-31 Thread Ying Yi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0e5fe1cdacdc: Remove `REQUIRES: x86-registered-target` from 
ps4/ps5 driver tests (authored by MaggieYi).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132950

Files:
  clang/test/Driver/ps4-pic.c
  clang/test/Driver/ps4-ps5-header-search.c
  clang/test/Driver/ps4-ps5-linker-non-win.c
  clang/test/Driver/ps4-ps5-linker-win.c
  clang/test/Driver/ps4-ps5-relax-relocations.c
  clang/test/Driver/ps4-ps5-runtime-flags.c
  clang/test/Driver/ps4-sdk-root.c
  clang/test/Driver/ps4ps5base.c
  clang/test/Driver/ps5-pic.c
  clang/test/Driver/ps5-sdk-root.c

Index: clang/test/Driver/ps5-sdk-root.c
===
--- clang/test/Driver/ps5-sdk-root.c
+++ clang/test/Driver/ps5-sdk-root.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-
 /// (Essentially identical to ps4-sdk-root.c except for the target.)
 
 /// Check that PS5 clang doesn't report a warning message when locating
Index: clang/test/Driver/ps5-pic.c
===
--- clang/test/Driver/ps5-pic.c
+++ clang/test/Driver/ps5-pic.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-
 // Test the driver's control over the PIC behavior for PS5 compiler.
 // These consist of tests of the relocation model flags and the
 // pic level flags passed to CC1.
Index: clang/test/Driver/ps4ps5base.c
===
--- clang/test/Driver/ps4ps5base.c
+++ clang/test/Driver/ps4ps5base.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-
 // Test that the driver always emits -fno-use-init-array on the PS4/PS5 targets
 // since their ABI does not support the .init_array section.
 
Index: clang/test/Driver/ps4-sdk-root.c
===
--- clang/test/Driver/ps4-sdk-root.c
+++ clang/test/Driver/ps4-sdk-root.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-
 // Check that PS4 clang doesn't report a warning message when locating
 // system header files (either by looking at the value of SCE_ORBIS_SDK_DIR
 // or relative to the location of the compiler driver), if "-nostdinc",
Index: clang/test/Driver/ps4-ps5-runtime-flags.c
===
--- clang/test/Driver/ps4-ps5-runtime-flags.c
+++ clang/test/Driver/ps4-ps5-runtime-flags.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-//
 /// Test the profile runtime library to be linked for PS4/PS5 compiler.
 /// Check runtime flag --dependent-lib which does not append the default library search path.
 //
Index: clang/test/Driver/ps4-ps5-relax-relocations.c
===
--- clang/test/Driver/ps4-ps5-relax-relocations.c
+++ clang/test/Driver/ps4-ps5-relax-relocations.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-
 // RUN: %clang -### -target x86_64-scei-ps4 %s -o - 2>&1 | \
 // RUN:   FileCheck %s
 // RUN: %clang -### -target x86_64-scei-ps4 -Wa,-mrelax-relocations=yes %s -o - 2>&1 | \
Index: clang/test/Driver/ps4-ps5-linker-win.c
===
--- clang/test/Driver/ps4-ps5-linker-win.c
+++ clang/test/Driver/ps4-ps5-linker-win.c
@@ -1,7 +1,7 @@
 // This test checks that orbis-ld is used for PS4 linker all the time, and
 // prospero-lld is used for PS5 linker. Specifying -fuse-ld causes an error.
 
-// REQUIRES: system-windows, x86-registered-target
+// REQUIRES: system-windows
 
 // RUN: mkdir -p %t
 // RUN: touch %t/orbis-ld.exe
Index: clang/test/Driver/ps4-ps5-linker-non-win.c
===
--- clang/test/Driver/ps4-ps5-linker-non-win.c
+++ clang/test/Driver/ps4-ps5-linker-non-win.c
@@ -1,6 +1,5 @@
 /// Checks proper linker prefixing for PS4 and PS5.
 // UNSUPPORTED: system-windows
-// REQUIRES: x86-registered-target
 
 // RUN: mkdir -p %t
 // RUN: rm -f %t/orbis-ld
Index: clang/test/Driver/ps4-ps5-header-search.c
===
--- clang/test/Driver/ps4-ps5-header-search.c
+++ clang/test/Driver/ps4-ps5-header-search.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-
 /// PS4 and PS5 use the same SDK layout, so use the same tree for both.
 // RUN: env SCE_ORBIS_SDK_DIR=%S/Inputs/scei-ps4_tree %clang -target x86_64-scei-ps4 -E -v %s 2>&1 | FileCheck %s --check-prefix=ENVPS4
 // RUN: env SCE_PROSPERO_SDK_DIR=%S/Inputs/scei-ps4_tree %clang -target x86_64-sie-ps5 -E -v %s 2>&1 | FileCheck %s --check-prefix=ENVPS4
Index: clang/test/Driver/ps4-pic.c
===
--- clang/test/Driver/ps4-pic.c
+++ clang/test/Driver/ps4-pic.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-
 // Test the driver's control over

[clang] 0e5fe1c - Remove `REQUIRES: x86-registered-target` from ps4/ps5 driver tests

2022-08-31 Thread Ying Yi via cfe-commits

Author: Ying Yi
Date: 2022-08-31T09:56:37+01:00
New Revision: 0e5fe1cdacdca65edc84c89cc7a6de27f406de61

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

LOG: Remove `REQUIRES: x86-registered-target` from ps4/ps5 driver tests

Reviewed By: probinson

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

Added: 


Modified: 
clang/test/Driver/ps4-pic.c
clang/test/Driver/ps4-ps5-header-search.c
clang/test/Driver/ps4-ps5-linker-non-win.c
clang/test/Driver/ps4-ps5-linker-win.c
clang/test/Driver/ps4-ps5-relax-relocations.c
clang/test/Driver/ps4-ps5-runtime-flags.c
clang/test/Driver/ps4-sdk-root.c
clang/test/Driver/ps4ps5base.c
clang/test/Driver/ps5-pic.c
clang/test/Driver/ps5-sdk-root.c

Removed: 




diff  --git a/clang/test/Driver/ps4-pic.c b/clang/test/Driver/ps4-pic.c
index c023dcfd0c35..fc429f130c75 100644
--- a/clang/test/Driver/ps4-pic.c
+++ b/clang/test/Driver/ps4-pic.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-
 // Test the driver's control over the PIC behavior for PS4 compiler.
 // These consist of tests of the relocation model flags and the
 // pic level flags passed to CC1.

diff  --git a/clang/test/Driver/ps4-ps5-header-search.c 
b/clang/test/Driver/ps4-ps5-header-search.c
index 6848901df559..6762c707dde6 100644
--- a/clang/test/Driver/ps4-ps5-header-search.c
+++ b/clang/test/Driver/ps4-ps5-header-search.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-
 /// PS4 and PS5 use the same SDK layout, so use the same tree for both.
 // RUN: env SCE_ORBIS_SDK_DIR=%S/Inputs/scei-ps4_tree %clang -target 
x86_64-scei-ps4 -E -v %s 2>&1 | FileCheck %s --check-prefix=ENVPS4
 // RUN: env SCE_PROSPERO_SDK_DIR=%S/Inputs/scei-ps4_tree %clang -target 
x86_64-sie-ps5 -E -v %s 2>&1 | FileCheck %s --check-prefix=ENVPS4

diff  --git a/clang/test/Driver/ps4-ps5-linker-non-win.c 
b/clang/test/Driver/ps4-ps5-linker-non-win.c
index b9686b88a757..8b8c0b018428 100644
--- a/clang/test/Driver/ps4-ps5-linker-non-win.c
+++ b/clang/test/Driver/ps4-ps5-linker-non-win.c
@@ -1,6 +1,5 @@
 /// Checks proper linker prefixing for PS4 and PS5.
 // UNSUPPORTED: system-windows
-// REQUIRES: x86-registered-target
 
 // RUN: mkdir -p %t
 // RUN: rm -f %t/orbis-ld

diff  --git a/clang/test/Driver/ps4-ps5-linker-win.c 
b/clang/test/Driver/ps4-ps5-linker-win.c
index acff2c0f1f24..f02f5a2055ec 100644
--- a/clang/test/Driver/ps4-ps5-linker-win.c
+++ b/clang/test/Driver/ps4-ps5-linker-win.c
@@ -1,7 +1,7 @@
 // This test checks that orbis-ld is used for PS4 linker all the time, and
 // prospero-lld is used for PS5 linker. Specifying -fuse-ld causes an error.
 
-// REQUIRES: system-windows, x86-registered-target
+// REQUIRES: system-windows
 
 // RUN: mkdir -p %t
 // RUN: touch %t/orbis-ld.exe

diff  --git a/clang/test/Driver/ps4-ps5-relax-relocations.c 
b/clang/test/Driver/ps4-ps5-relax-relocations.c
index 1c8200a6d58b..22490e486052 100644
--- a/clang/test/Driver/ps4-ps5-relax-relocations.c
+++ b/clang/test/Driver/ps4-ps5-relax-relocations.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-
 // RUN: %clang -### -target x86_64-scei-ps4 %s -o - 2>&1 | \
 // RUN:   FileCheck %s
 // RUN: %clang -### -target x86_64-scei-ps4 -Wa,-mrelax-relocations=yes %s -o 
- 2>&1 | \

diff  --git a/clang/test/Driver/ps4-ps5-runtime-flags.c 
b/clang/test/Driver/ps4-ps5-runtime-flags.c
index 96c9c1244ddd..e75ba97948d2 100644
--- a/clang/test/Driver/ps4-ps5-runtime-flags.c
+++ b/clang/test/Driver/ps4-ps5-runtime-flags.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-//
 /// Test the profile runtime library to be linked for PS4/PS5 compiler.
 /// Check runtime flag --dependent-lib which does not append the default 
library search path.
 //

diff  --git a/clang/test/Driver/ps4-sdk-root.c 
b/clang/test/Driver/ps4-sdk-root.c
index ee22d6c8f0cf..e1a04522030c 100644
--- a/clang/test/Driver/ps4-sdk-root.c
+++ b/clang/test/Driver/ps4-sdk-root.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-
 // Check that PS4 clang doesn't report a warning message when locating
 // system header files (either by looking at the value of SCE_ORBIS_SDK_DIR
 // or relative to the location of the compiler driver), if "-nostdinc",

diff  --git a/clang/test/Driver/ps4ps5base.c b/clang/test/Driver/ps4ps5base.c
index bd583f88dd6e..a688c250129f 100644
--- a/clang/test/Driver/ps4ps5base.c
+++ b/clang/test/Driver/ps4ps5base.c
@@ -1,5 +1,3 @@
-// REQUIRES: x86-registered-target
-
 // Test that the driver always emits -fno-use-init-array on the PS4/PS5 targets
 // since their ABI does not support the .init_array section.
 

diff  --git a/clang/test/Driver/ps5-pic.c b/clang/test/Driver/ps5-pic.c
index 0396122accf4..4db107cd8c86 100644
--- a/clang/test/Driver/ps5-pic.c
+++ b/clang/test/Driver/ps5-pic.c
@@ -1,5 +1

[PATCH] D132998: [clang-tidy] Restrict use-equals-default to c++11-or-later

2022-08-31 Thread Alexander Shaposhnikov via Phabricator via cfe-commits
alexander-shaposhnikov added a comment.

My assumption was that a codebase needs to compile with c++11 in the first 
place - otherwise the automatic fixit will break the build (as it happens right 
now).
I was looking at modernize/UseOverrideCheck.h - it requires c++11 and this 
seemed to be quite natural.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132998

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


[libclc] a11e2d7 - [libclc] Quote addition of CLC/LLAsm flags

2022-08-31 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2022-08-31T11:10:24+02:00
New Revision: a11e2d7366a11385e23d142ac93065a861b70a16

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

LOG: [libclc] Quote addition of CLC/LLAsm flags

Otherwise cmake will insert a semicolon if flags are already set.

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

Added: 


Modified: 
libclc/CMakeLists.txt

Removed: 




diff  --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt
index 9773b2cc925ff..96519e09e28e4 100644
--- a/libclc/CMakeLists.txt
+++ b/libclc/CMakeLists.txt
@@ -136,8 +136,8 @@ set( LLVM_VERSION_DEFINE 
"-DHAVE_LLVM=0x${LLVM_MAJOR}0${LLVM_MINOR}" )
 
 # LLVM 13 enables standard includes by default
 if( ${LLVM_VERSION} VERSION_GREATER "12.99.99" )
-   set( CMAKE_LLAsm_FLAGS ${CMAKE_LLAsm_FLAGS} 
-cl-no-stdinc )
-   set( CMAKE_CLC_FLAGS ${CMAKE_CLC_FLAGS} 
-cl-no-stdinc )
+   set( CMAKE_LLAsm_FLAGS "${CMAKE_LLAsm_FLAGS} 
-cl-no-stdinc")
+   set( CMAKE_CLC_FLAGS "${CMAKE_CLC_FLAGS} 
-cl-no-stdinc")
 endif()
 
 enable_language( CLC LLAsm )



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


[PATCH] D133006: [clang-tidy] Skip copy assignment operators with nonstandard return types

2022-08-31 Thread Alexander Shaposhnikov via Phabricator via cfe-commits
alexander-shaposhnikov created this revision.
alexander-shaposhnikov added reviewers: njames93, gribozavr2, aaron.ballman.
alexander-shaposhnikov created this object with visibility "All Users".
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a project: All.
alexander-shaposhnikov requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Skip copy assignment operators with nonstandard return types since they cannot 
be defaulted.

Test plan: ninja check-clang-tools


Repository:
  rL LLVM

https://reviews.llvm.org/D133006

Files:
  clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
@@ -444,6 +444,13 @@
   return *this;
 }
 
+// Wrong return type.
+struct WRTConstRef {
+  const WRTConstRef &operator = (const WRTConstRef &) {
+return *this;
+  }
+};
+
 // Try-catch.
 struct ITC {
   ITC(const ITC &Other)
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -139,7 +139,8 @@
 - Improved `modernize-use-equals-default 
`_ check.
 
   The check now skips unions since in this case a default constructor with 
empty body
-  is not equivalent to the explicitly defaulted one.
+  is not equivalent to the explicitly defaulted one. The check also skips
+  copy assignment operators with nonstandard return types.
 
 Removed checks
 ^^
Index: clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -8,6 +8,7 @@
 
 #include "UseEqualsDefaultCheck.h"
 #include "../utils/LexerUtils.h"
+#include "../utils/Matchers.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/Lexer.h"
@@ -247,7 +248,12 @@
 // isCopyAssignmentOperator() allows the parameter to be
 // passed by value, and in this case it cannot be
 // defaulted.
-hasParameter(0, hasType(lValueReferenceType(
+hasParameter(0, hasType(lValueReferenceType())),
+// isCopyAssignmentOperator() allows non lvalue reference
+// return types, and in this case it cannot be defaulted.
+returns(qualType(hasCanonicalType(
+allOf(lValueReferenceType(pointee(type())),
+  unless(matchers::isReferenceToConst()))
   .bind(SpecialFunction),
   this);
 }


Index: clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize/use-equals-default-copy.cpp
@@ -444,6 +444,13 @@
   return *this;
 }
 
+// Wrong return type.
+struct WRTConstRef {
+  const WRTConstRef &operator = (const WRTConstRef &) {
+return *this;
+  }
+};
+
 // Try-catch.
 struct ITC {
   ITC(const ITC &Other)
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -139,7 +139,8 @@
 - Improved `modernize-use-equals-default `_ check.
 
   The check now skips unions since in this case a default constructor with empty body
-  is not equivalent to the explicitly defaulted one.
+  is not equivalent to the explicitly defaulted one. The check also skips
+  copy assignment operators with nonstandard return types.
 
 Removed checks
 ^^
Index: clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp
@@ -8,6 +8,7 @@
 
 #include "UseEqualsDefaultCheck.h"
 #include "../utils/LexerUtils.h"
+#include "../utils/Matchers.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/Lexer.h"
@@ -247,7 +248,12 @@
 // isCopyAssignmentOperator() allows the parameter to be
 // p

[PATCH] D132990: [Clang] Fix compat diagnostic to detect a nontype template parameter has a placeholder type using getContainedAutoType()

2022-08-31 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov added a reviewer: mizvekov.
mizvekov added inline comments.



Comment at: clang/lib/Sema/SemaTemplate.cpp:1534-1538
+  if (TInfo->getType()->getContainedAutoType()) {
 Diag(D.getIdentifierLoc(),
  diag::warn_cxx14_compat_template_nontype_parm_auto_type)
   << QualType(TInfo->getType()->getContainedAutoType(), 0);
   }

I think checking that the deduced type is undeduced was really unnecessary 
though, as I don't think we update the type source infos after deduction in any 
case.



Comment at: clang/test/SemaTemplate/temp_arg_nontype_diagnostic_cxx1z.cpp:7
+
+template  // ok, no diagnostic expected
+void func() {}

I think this should have a new diagnostic per above, as this is not compatible 
with C++17.


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

https://reviews.llvm.org/D132990

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


[PATCH] D132640: [clang-tidy] Fix modernize-use-emplace to support alias cases

2022-08-31 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG495d984e14bd: [clang-tidy] Fix modernize-use-emplace to 
support alias cases (authored by corona10, committed by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132640

Files:
  clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp
@@ -1061,6 +1061,82 @@
   // CHECK-FIXES: priority_queue.emplace(13);
 }
 
+void test_AliasEmplacyFunctions() {
+  typedef std::list L;
+  using DQ = std::deque;
+  L l;
+  l.emplace_back(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: unnecessary temporary object created while calling emplace_back
+  // CHECK-FIXES: l.emplace_back(3);
+
+  DQ dq;
+  dq.emplace_back(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: unnecessary temporary object created while calling emplace_back
+  // CHECK-FIXES: dq.emplace_back(3);
+
+  typedef std::stack STACK;
+  using PQ = std::priority_queue;
+  STACK stack;
+  stack.emplace(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: unnecessary temporary object created while calling emplace
+  // CHECK-FIXES: stack.emplace(3);
+
+  PQ pq;
+  pq.emplace(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: unnecessary temporary object created while calling emplace
+  // CHECK-FIXES: pq.emplace(3);
+
+  typedef std::forward_list FL;
+  using DQ2 = std::deque;
+  FL fl;
+  fl.emplace_front(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: unnecessary temporary object created while calling emplace_front
+  // CHECK-FIXES: fl.emplace_front(3);
+
+  DQ2 dq2;
+  dq2.emplace_front(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: unnecessary temporary object created while calling emplace_front
+  // CHECK-FIXES: dq2.emplace_front(3);
+}
+
+void test_Alias() {
+  typedef std::list L;
+  using DQ = std::deque;
+  L l;
+  l.push_back(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use emplace_back instead of push_back [modernize-use-emplace]
+  // CHECK-FIXES: l.emplace_back(3);
+
+  DQ dq;
+  dq.push_back(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use emplace_back instead of push_back [modernize-use-emplace]
+  // CHECK-FIXES: dq.emplace_back(3);
+
+  typedef std::stack STACK;
+  using PQ = std::priority_queue;
+  STACK stack;
+  stack.push(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: use emplace instead of push [modernize-use-emplace]
+  // CHECK-FIXES: stack.emplace(3);
+
+  PQ pq;
+  pq.push(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use emplace instead of push [modernize-use-emplace]
+  // CHECK-FIXES: pq.emplace(3);
+
+  typedef std::forward_list FL;
+  using DQ2 = std::deque;
+  FL fl;
+  fl.push_front(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use emplace_front instead of push_front [modernize-use-emplace]
+  // CHECK-FIXES: fl.emplace_front(3);
+
+  DQ2 dq2;
+  dq2.push_front(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use emplace_front instead of push_front [modernize-use-emplace]
+  // CHECK-FIXES: dq2.emplace_front(3);
+}
+
 struct Bar {
 public:
   Bar(){};
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -129,13 +129,17 @@
   ` when warnings
   would be emitted for uninitialized members of an anonymous union despite
   there being an initializer for one of the other members.
-  
+
 - Improved `modernize-use-emplace `_ check.
 
   The check now supports detecting inefficient invocations of ``push`` and
   ``push_front`` on STL-style containers and replacing them with ``emplace``
   or ``emplace_front``.
 
+  The check now supports detecting alias cases of ``push_back`` ``push`` and
+  ``push_front`` on STL-style containers and replacing them with ``emplace_back``,
+  ``emplace`` or ``emplace_front``.
+
 - Improved `modernize-use-equals-default `_ check.
 
   The check now skips unions since in this case a default constructor with empty body
Index: clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
@@ -134,22 +134,25 @@
   // + match for emplace calls that should be replaced with insertion
   auto CallPushBack = cxxMemberCallExpr(
   hasDeclaration(functionDecl(hasName("push_back"))),
-  on(has

[clang-tools-extra] 495d984 - [clang-tidy] Fix modernize-use-emplace to support alias cases

2022-08-31 Thread Nathan James via cfe-commits

Author: corona10
Date: 2022-08-31T10:21:10+01:00
New Revision: 495d984e14bd8367017ffdea8183840c8267cbbf

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

LOG: [clang-tidy] Fix modernize-use-emplace to support alias cases

Fix modernize-use-emplace to support alias cases

Reviewed By: njames93

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
index abf5ba918d89f..1b7853d781ce9 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
@@ -134,22 +134,25 @@ void UseEmplaceCheck::registerMatchers(MatchFinder 
*Finder) {
   // + match for emplace calls that should be replaced with insertion
   auto CallPushBack = cxxMemberCallExpr(
   hasDeclaration(functionDecl(hasName("push_back"))),
-  on(hasType(cxxRecordDecl(hasAnyName(ContainersWithPushBack);
+  on(hasType(hasCanonicalType(
+  
hasDeclaration(cxxRecordDecl(hasAnyName(ContainersWithPushBack)));
 
-  auto CallPush = cxxMemberCallExpr(
-  hasDeclaration(functionDecl(hasName("push"))),
-  on(hasType(cxxRecordDecl(hasAnyName(ContainersWithPush);
+  auto CallPush =
+  cxxMemberCallExpr(hasDeclaration(functionDecl(hasName("push"))),
+on(hasType(hasCanonicalType(hasDeclaration(
+cxxRecordDecl(hasAnyName(ContainersWithPush)));
 
   auto CallPushFront = cxxMemberCallExpr(
   hasDeclaration(functionDecl(hasName("push_front"))),
-  on(hasType(cxxRecordDecl(hasAnyName(ContainersWithPushFront);
+  on(hasType(hasCanonicalType(hasDeclaration(
+  cxxRecordDecl(hasAnyName(ContainersWithPushFront)));
 
   auto CallEmplacy = cxxMemberCallExpr(
   hasDeclaration(
   functionDecl(hasAnyNameIgnoringTemplates(EmplacyFunctions))),
-  on(hasType(cxxRecordDecl(has(typedefNameDecl(
+  on(hasType(hasCanonicalType(hasDeclaration(has(typedefNameDecl(
   hasName("value_type"), hasType(type(hasUnqualifiedDesugaredType(
- recordType().bind("value_type"));
+ recordType().bind("value_type")));
 
   // We can't replace push_backs of smart pointer because
   // if emplacement fails (f.e. bad_alloc in vector) we will have leak of

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 1734f4acf6865..9bd3a5fc799cf 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -129,13 +129,17 @@ Changes in existing checks
   ` when warnings
   would be emitted for uninitialized members of an anonymous union despite
   there being an initializer for one of the other members.
-  
+
 - Improved `modernize-use-emplace 
`_ check.
 
   The check now supports detecting inefficient invocations of ``push`` and
   ``push_front`` on STL-style containers and replacing them with ``emplace``
   or ``emplace_front``.
 
+  The check now supports detecting alias cases of ``push_back`` ``push`` and
+  ``push_front`` on STL-style containers and replacing them with 
``emplace_back``,
+  ``emplace`` or ``emplace_front``.
+
 - Improved `modernize-use-equals-default 
`_ check.
 
   The check now skips unions since in this case a default constructor with 
empty body

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp
index 29ba88117b5f7..04ff0775d285c 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-emplace.cpp
@@ -1061,6 +1061,82 @@ void testAllSTLEmplacyFunctions() {
   // CHECK-FIXES: priority_queue.emplace(13);
 }
 
+void test_AliasEmplacyFunctions() {
+  typedef std::list L;
+  using DQ = std::deque;
+  L l;
+  l.emplace_back(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: unnecessary temporary object 
created while calling emplace_back
+  // CHECK-FIXES: l.emplace_back(3);
+
+  DQ dq;
+  dq.emplace_back(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: unnecessary temporary object 
created while calling emplace_back
+  // CHECK-FIXES: dq.emplace_back(3);
+
+  typedef std::stack STACK;
+  using PQ = std::priority_queue;
+  STACK stack;
+  stack.emplace(Foo(3));
+  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: unnecessary te

[PATCH] D132461: [clang-tidy] Add cppcoreguidelines-avoid-do-while check

2022-08-31 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

@njames93 Is there anything else I should address?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132461

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


[PATCH] D132990: [Clang] Fix compat diagnostic to detect a nontype template parameter has a placeholder type using getContainedAutoType()

2022-08-31 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov added inline comments.



Comment at: clang/test/SemaTemplate/temp_arg_nontype_diagnostic_cxx1z.cpp:1
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++20 -Wpre-c++17-compat %s
+

One thing we could do is to run this test also in std=c++17 mode, with a 
different expectancy, as a kind of sanity check that the warning is in sync.


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

https://reviews.llvm.org/D132990

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


[PATCH] D133009: [libclang] Fix conversion from `StringRef` to `CXString`

2022-08-31 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan created this revision.
egorzhdan added a reviewer: gribozavr2.
Herald added a subscriber: arphaman.
Herald added a project: All.
egorzhdan requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

`CXString createRef(StringRef String)` used to return an invalid string when 
invoked with some empty strings:

If a `StringRef` holds a non-nullptr pointer, for instance, pointing into 
contents of a larger string, and has a zero length, `createRef` previously 
returned the entire larger string, ignoring the fact that the actual string 
passed to it as a param is empty.

This was discovered when invoking `c-index-test` to dump the contents of 
documentation comments, in case the comment contains an empty HTML attribute, 
such as `src=""`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133009

Files:
  clang/test/Index/comment-to-html-xml-conversion.cpp
  clang/tools/libclang/CXString.cpp


Index: clang/tools/libclang/CXString.cpp
===
--- clang/tools/libclang/CXString.cpp
+++ clang/tools/libclang/CXString.cpp
@@ -78,13 +78,22 @@
 }
 
 CXString createRef(StringRef String) {
+  if (!String.data())
+return createNull();
+
+  // If the string is empty, it might point to a position in another string
+  // while having zero length. Make sure we don't create a reference to the
+  // larger string.
+  if (String.empty())
+return createEmpty();
+
   // If the string is not nul-terminated, we have to make a copy.
 
   // FIXME: This is doing a one past end read, and should be removed! For 
memory
   // we don't manage, the API string can become unterminated at any time 
outside
   // our control.
 
-  if (!String.empty() && String.data()[String.size()] != 0)
+  if (String.data()[String.size()] != 0)
 return createDup(String);
 
   CXString Result;
Index: clang/test/Index/comment-to-html-xml-conversion.cpp
===
--- clang/test/Index/comment-to-html-xml-conversion.cpp
+++ clang/test/Index/comment-to-html-xml-conversion.cpp
@@ -744,6 +744,15 @@
 // CHECK-NEXT: (CXComment_Text Text=[ ] IsWhitespace)
 // CHECK-NEXT: (CXComment_InlineCommand CommandName=[anchor] 
RenderAnchor Arg[0]=A)))]
 
+/// Aaa ccc
+void comment_to_html_conversion_40();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: 
FunctionDecl=comment_to_html_conversion_40:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_40c:@F@comment_to_html_conversion_40#void
 comment_to_html_conversion_40() Aaa 
ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=)
 
 /// Aaa.
 class comment_to_xml_conversion_01 {


Index: clang/tools/libclang/CXString.cpp
===
--- clang/tools/libclang/CXString.cpp
+++ clang/tools/libclang/CXString.cpp
@@ -78,13 +78,22 @@
 }
 
 CXString createRef(StringRef String) {
+  if (!String.data())
+return createNull();
+
+  // If the string is empty, it might point to a position in another string
+  // while having zero length. Make sure we don't create a reference to the
+  // larger string.
+  if (String.empty())
+return createEmpty();
+
   // If the string is not nul-terminated, we have to make a copy.
 
   // FIXME: This is doing a one past end read, and should be removed! For memory
   // we don't manage, the API string can become unterminated at any time outside
   // our control.
 
-  if (!String.empty() && String.data()[String.size()] != 0)
+  if (String.data()[String.size()] != 0)
 return createDup(String);
 
   CXString Result;
Index: clang/test/Index/comment-to-html-xml-conversion.cpp
===
--- clang/test/Index/comment-to-html-xml-conversion.cpp
+++ clang/test/Index/comment-to-html-xml-conversion.cpp
@@ -744,6 +744,15 @@
 // CHECK-NEXT: (CXComment_Text Text=[ ] IsWhitespace)
 // CHECK-NEXT: (CXComment_InlineCommand CommandName=[anchor] RenderAnchor Arg[0]=A)))]
 
+/// Aaa ccc
+void comment_to_html_conversion_40();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_40:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_40c:@F@comment_to_html_conversion_40#void comment_to_html_conversion_40() Aaa ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=)
 
 /// Aaa.
 class comment_to_xml_conversion_01 {
___
cfe-commits maili

[PATCH] D132136: [clang] Perform implicit lvalue-to-rvalue cast with new interpreter

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

In D132136#3755724 , @aaron.ballman 
wrote:

> In D132136#3753290 , @tbaeder wrote:
>
>> In D132136#3751702 , @erichkeane 
>> wrote:
>>
>>> Would be great if we had a better test here... is there anything we can do 
>>> to validate this is happening other than checking for that one note?
>>
>> `EvaluateAsRValue` is called from `Expr::EvaluateAsRValue()`, so I think it 
>> would be possible to write a unittest for this. But I think that would be a 
>> lot of effort just to test this. There is even 
>> `unittests/AST/EvaluateAsRValueTest.cpp` already, but it tests the wrong 
>> thing :(
>
> The existing test coverage being wrong seems like all the more reason to add 
> correct test coverage. LValue to RValue conversions are important to get 
> right (lol here's a wonderful demonstration of where we didn't bother to see 
> if we got it right that I accidentally stumbled into when trying to give you 
> a constexpr test case: https://godbolt.org/z/bdxbers3M), especially because 
> they're going to impact which overload gets called when picking between an 
> `&&` and `&` overload.

To be clear, can I land this patch without the unittest? I tried adding this to 
`EvaluateAsRValueTest.cpp` but I just run into other problems in the new 
interpreter :) So more unittests would definitely be good.


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

https://reviews.llvm.org/D132136

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


[PATCH] D132829: [clang][Interp] Handle ImplictValueInitExprs

2022-08-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 456915.

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

https://reviews.llvm.org/D132829

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Opcodes.td
  clang/test/AST/Interp/arrays.cpp


Index: clang/test/AST/Interp/arrays.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/arrays.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+
+/// expected-no-diagnostics
+/// ref-no-diagnostics
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wc99-extensions"
+#pragma clang diagnostic ignored "-Winitializer-overrides"
+/// FIXME: The example below tests ImplicitValueInitExprs, but we can't
+///   currently evaluate other parts of it.
+#if 0
+struct fred {
+  char s [6];
+  int n;
+};
+
+struct fred y [] = { [0] = { .s[0] = 'q' } };
+#endif
+#pragma clang diagnostic pop
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -203,6 +203,7 @@
 // [] -> [Integer]
 def Zero : Opcode {
   let Types = [AluTypeClass];
+  let HasGroup = 1;
 }
 
 // [] -> [Pointer]
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -75,6 +75,7 @@
   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E);
   bool VisitUnaryOperator(const UnaryOperator *E);
   bool VisitDeclRefExpr(const DeclRefExpr *E);
+  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *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
@@ -223,6 +223,14 @@
   return this->bail(BO);
 }
 
+template 
+bool ByteCodeExprGen::VisitImplicitValueInitExpr(const 
ImplicitValueInitExpr *E) {
+  if (Optional T = classify(E))
+return this->emitZero(*T, E);
+
+  return false;
+}
+
 template 
 bool ByteCodeExprGen::discard(const Expr *E) {
   OptionScope Scope(this, /*NewDiscardResult=*/true);


Index: clang/test/AST/Interp/arrays.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/arrays.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+
+/// expected-no-diagnostics
+/// ref-no-diagnostics
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wc99-extensions"
+#pragma clang diagnostic ignored "-Winitializer-overrides"
+/// FIXME: The example below tests ImplicitValueInitExprs, but we can't
+///   currently evaluate other parts of it.
+#if 0
+struct fred {
+  char s [6];
+  int n;
+};
+
+struct fred y [] = { [0] = { .s[0] = 'q' } };
+#endif
+#pragma clang diagnostic pop
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -203,6 +203,7 @@
 // [] -> [Integer]
 def Zero : Opcode {
   let Types = [AluTypeClass];
+  let HasGroup = 1;
 }
 
 // [] -> [Pointer]
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -75,6 +75,7 @@
   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E);
   bool VisitUnaryOperator(const UnaryOperator *E);
   bool VisitDeclRefExpr(const DeclRefExpr *E);
+  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *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
@@ -223,6 +223,14 @@
   return this->bail(BO);
 }
 
+template 
+bool ByteCodeExprGen::VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
+  if (Optional T = classify(E))
+return this->emitZero(*T, E);
+
+  return false;
+}
+
 template 
 bool ByteCodeExprGen::discard(const Expr *E) {
   OptionScope Scope(this, /*NewDiscardResult=*/true);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 9e842dd - [clang][dataflow] Extend transfer functions for other `CFGElement`s

2022-08-31 Thread Wei Yi Tee via cfe-commits

Author: Wei Yi Tee
Date: 2022-08-31T10:23:53Z
New Revision: 9e842dd4bd551c42951d1a56bb9d9eef1fa6c385

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

LOG: [clang][dataflow] Extend transfer functions for other `CFGElement`s

Previously, the transfer function `void transfer(const Stmt *, ...)` overriden 
by users is restricted to apply only on `CFGStmt`s and its contained `Stmt`.

By using a transfer function (`void transfer(const CFGElement *, ...)`) that 
takes a `CFGElement` as input, this patch extends user-defined analysis to all 
kinds of `CFGElement`. For example, users can now handle `CFGInitializer`s 
where `CXXCtorInitializer` AST nodes are contained.

Reviewed By: gribozavr2, sgatev

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
clang/unittests/Analysis/FlowSensitive/TestingSupport.h

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
index 4d1f5248f2115..4e084d57ba011 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -15,11 +15,13 @@
 #define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_DATAFLOWANALYSIS_H
 
 #include 
+#include 
 #include 
 #include 
 
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
 #include "clang/Analysis/FlowSensitive/ControlFlowContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h"
@@ -31,6 +33,17 @@
 namespace clang {
 namespace dataflow {
 
+template >
+struct HasTransferFor : std::false_type {};
+
+template 
+struct HasTransferFor<
+AnalysisT, LatticeT, InputT,
+std::void_t().transfer(
+std::declval(), std::declval(),
+std::declval()))>> : std::true_type {};
+
 /// Base class template for dataflow analyses built on a single lattice type.
 ///
 /// Requirements:
@@ -39,8 +52,9 @@ namespace dataflow {
 ///  must provide the following public members:
 ///   * `LatticeT initialElement()` - returns a lattice element that models the
 /// initial state of a basic block;
-///   * `void transfer(const Stmt *, LatticeT &, Environment &)` - applies the
-/// analysis transfer function for a given statement and lattice element.
+///   * `void transfer(const CFGElement *, LatticeT &, Environment &)` - 
applies
+/// the analysis transfer function for a given CFG element and lattice
+/// element.
 ///
 ///  `Derived` can optionally override the following members:
 ///   * `bool merge(QualType, const Value &, const Value &, Value &,
@@ -93,10 +107,20 @@ class DataflowAnalysis : public TypeErasedDataflowAnalysis 
{
 return L1 == L2;
   }
 
-  void transferTypeErased(const Stmt *Stmt, TypeErasedLattice &E,
+  void transferTypeErased(const CFGElement *Element, TypeErasedLattice &E,
   Environment &Env) final {
 Lattice &L = llvm::any_cast(E.Value);
-static_cast(this)->transfer(Stmt, L, Env);
+if constexpr (HasTransferFor::value) {
+  static_cast(this)->transfer(Element, L, Env);
+}
+
+// FIXME: Remove after users have been updated to implement `transfer` on
+// `CFGElement`.
+if constexpr (HasTransferFor::value) {
+  if (auto Stmt = Element->getAs()) {
+static_cast(this)->transfer(Stmt->getStmt(), L, Env);
+  }
+}
   }
 
 private:
@@ -112,37 +136,41 @@ template  struct DataflowAnalysisState 
{
   Environment Env;
 };
 
+// FIXME: Rename to `runDataflowAnalysis` after usages of the overload that
+// applies to `CFGStmt` have been replaced.
+//
 /// Performs dataflow analysis and returns a mapping from basic block IDs to
 /// dataflow analysis states that model the respective basic blocks. The
 /// returned vector, if any, will have the same size as the number of CFG
 /// blocks, with indices corresponding to basic block IDs. Returns an error if
 /// the dataflow analysis cannot be performed successfully. Otherwise, calls
-/// `PostVisitStmt` on each statement with the final analysis results at that
+/// `PostVisitCFG` on each CFG element with the final analysis results at that
 /// program point.
 template 
 llvm::Expected>>>
-runDataflowAnalysis(
+runDataflowAnalysisOnCFG(
 const ControlFlowContext &CFCtx, AnalysisT &Analysis,
 const Environment &InitEnv,
-std::function &)>
-PostVisitStmt

[PATCH] D131614: [clang][dataflow] Extend transfer functions for other `CFGElement`s

2022-08-31 Thread weiyi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9e842dd4bd55: [clang][dataflow] Extend transfer functions 
for other `CFGElement`s (authored by wyt).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131614

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h

Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -71,14 +71,25 @@
   std::vector> &BlockStates;
 };
 
+// FIXME: Rename to `checkDataflow` after usages of the overload that applies to
+// `CFGStmt` have been replaced.
+//
+/// Runs dataflow analysis (specified from `MakeAnalysis`) and the
+/// `PostVisitCFG` function (if provided) on the body of the function that
+/// matches `TargetFuncMatcher` in code snippet `Code`. `VerifyResults` checks
+/// that the results from the analysis are correct.
+///
+/// Requirements:
+///
+///  `AnalysisT` contains a type `Lattice`.
 template 
-llvm::Error checkDataflow(
+llvm::Error checkDataflowOnCFG(
 llvm::StringRef Code,
 ast_matchers::internal::Matcher TargetFuncMatcher,
 std::function MakeAnalysis,
-std::function
-PostVisitStmt,
+PostVisitCFG,
 std::function VerifyResults, ArrayRef Args,
 const tooling::FileContentMappings &VirtualMappedFiles = {}) {
   llvm::Annotations AnnotatedCode(Code);
@@ -112,13 +123,14 @@
   Environment Env(DACtx, *F);
   auto Analysis = MakeAnalysis(Context, Env);
 
-  std::function
-  PostVisitStmtClosure = nullptr;
-  if (PostVisitStmt != nullptr) {
-PostVisitStmtClosure = [&PostVisitStmt, &Context](
-   const CFGStmt &Stmt,
-   const TypeErasedDataflowAnalysisState &State) {
-  PostVisitStmt(Context, Stmt, State);
+  std::function
+  PostVisitCFGClosure = nullptr;
+  if (PostVisitCFG) {
+PostVisitCFGClosure = [&PostVisitCFG, &Context](
+  const CFGElement &Element,
+  const TypeErasedDataflowAnalysisState &State) {
+  PostVisitCFG(Context, Element, State);
 };
   }
 
@@ -130,7 +142,7 @@
 
   llvm::Expected>>
   MaybeBlockStates = runTypeErasedDataflowAnalysis(*CFCtx, Analysis, Env,
-   PostVisitStmtClosure);
+   PostVisitCFGClosure);
   if (!MaybeBlockStates)
 return MaybeBlockStates.takeError();
   auto &BlockStates = *MaybeBlockStates;
@@ -141,6 +153,32 @@
   return llvm::Error::success();
 }
 
+template 
+llvm::Error checkDataflow(
+llvm::StringRef Code,
+ast_matchers::internal::Matcher TargetFuncMatcher,
+std::function MakeAnalysis,
+std::function
+PostVisitStmt,
+std::function VerifyResults, ArrayRef Args,
+const tooling::FileContentMappings &VirtualMappedFiles = {}) {
+  std::function
+  PostVisitCFG = nullptr;
+  if (PostVisitStmt) {
+PostVisitCFG =
+[&PostVisitStmt](ASTContext &Context, const CFGElement &Element,
+ const TypeErasedDataflowAnalysisState &State) {
+  if (auto Stmt = Element.getAs()) {
+PostVisitStmt(Context, *Stmt, State);
+  }
+};
+  }
+  return checkDataflowOnCFG(Code, TargetFuncMatcher, MakeAnalysis, PostVisitCFG,
+VerifyResults, Args, VirtualMappedFiles);
+}
+
 // Runs dataflow on the body of the function that matches `TargetFuncMatcher` in
 // code snippet `Code`. Requires: `AnalysisT` contains a type `Lattice`.
 template 
@@ -157,9 +195,9 @@
 const tooling::FileContentMappings &VirtualMappedFiles = {}) {
   using StateT = DataflowAnalysisState;
 
-  return checkDataflow(
+  return checkDataflowOnCFG(
   Code, std::move(TargetFuncMatcher), std::move(MakeAnalysis),
-  /*PostVisitStmt=*/nullptr,
+  /*PostVisitCFG=*/nullptr,
   [&VerifyResults](AnalysisData AnalysisData) {
 if (AnalysisData.BlockStates.empty()) {
   VerifyResults({}, AnalysisData.ASTCtx);
@@ -180,9 +218,13 @@
   AnalysisData.CFCtx, AnalysisData.BlockStates, *Block,
   AnalysisData.Env, AnalysisData.Analysis,
   [&Results,
-   &Annotations](const clang::CFGStmt &Stmt,
+   &Annotations](const clang::CFGElement &Element,
  const TypeErasedDataflowAnalysisState &State) {
-auto It = Annotations.find(Stmt.getStmt());
+ 

[PATCH] D132997: [clang][Interp] Handle DeclRefExpr of reference types

2022-08-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 456917.

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

https://reviews.llvm.org/D132997

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

Index: clang/test/AST/Interp/references.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/references.cpp
@@ -0,0 +1,73 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+
+// expected-no-diagnostics
+// ref-no-diagnostics
+
+constexpr int a = 10;
+constexpr const int &b = a;
+static_assert(a == b, "");
+
+constexpr int assignToReference() {
+  int a = 20;
+  int &b =a;
+
+  b = 100;
+  return a;
+}
+static_assert(assignToReference() == 100, "");
+
+
+constexpr void setValue(int &dest, int val) {
+  dest = val;
+}
+
+constexpr int checkSetValue() {
+  int l = 100;
+  setValue(l, 200);
+  return l;
+}
+static_assert(checkSetValue() == 200, "");
+
+constexpr int readLocalRef() {
+  int a = 20;
+  int &b = a;
+  return b;
+}
+static_assert(readLocalRef() == 20, "");
+
+constexpr int incRef() {
+  int a = 0;
+  int &b = a;
+
+  b = b + 1;
+
+  return a;
+}
+static_assert(incRef() == 1, "");
+
+
+template
+constexpr void Plus3(int &A) {
+  A = V + 3;
+}
+constexpr int foo = 4;
+
+constexpr int callTemplate() {
+  int a = 3;
+  Plus3(a);
+  return a;
+}
+static_assert(callTemplate() == 7, "");
+
+
+constexpr int& getValue(int *array, int index) {
+  return array[index];
+}
+constexpr int testGetValue() {
+  int values[] = {1, 2, 3, 4};
+  getValue(values, 2) = 30;
+  return values[2];
+}
+static_assert(testGetValue() == 30, "");
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -845,15 +845,38 @@
 template 
 bool ByteCodeExprGen::VisitDeclRefExpr(const DeclRefExpr *E) {
   const auto *Decl = E->getDecl();
+  bool IsReference = Decl->getType()->isReferenceType();
+  bool FoundDecl = false;
 
   if (auto It = Locals.find(Decl); It != Locals.end()) {
 const unsigned Offset = It->second.Offset;
-return this->emitGetPtrLocal(Offset, E);
+if (!this->emitGetPtrLocal(Offset, E))
+  return false;
+
+FoundDecl = true;
   } else if (auto GlobalIndex = P.getGlobal(Decl)) {
-return this->emitGetPtrGlobal(*GlobalIndex, E);
+if (!this->emitGetPtrGlobal(*GlobalIndex, E))
+  return false;
+
+FoundDecl = true;
   } else if (const auto *PVD = dyn_cast(Decl)) {
-if (auto It = this->Params.find(PVD); It != this->Params.end())
-  return this->emitGetPtrParam(It->second, E);
+if (auto It = this->Params.find(PVD); It != this->Params.end()) {
+  if (!this->emitGetPtrParam(It->second, E))
+return false;
+
+  FoundDecl = true;
+}
+  }
+
+  // References are implemented using pointers, so when we get here,
+  // we have a pointer to a pointer, which we need to de-reference once.
+  if (FoundDecl) {
+if (IsReference) {
+  if (!this->emitLoadPop(PT_Ptr, E))
+return false;
+}
+
+return true;
   }
 
   return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D131563: [clang] Fix clang multiarch isssue with musl

2022-08-31 Thread Brahmajit via Phabricator via cfe-commits
listout updated this revision to Diff 456920.
listout marked an inline comment as done.
listout retitled this revision from "[WIP] [clang] Fix clang multiarch isssue 
with musl" to "[clang] Fix clang multiarch isssue with musl".

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

https://reviews.llvm.org/D131563

Files:
  clang/lib/Driver/ToolChains/Linux.cpp


Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -42,6 +42,15 @@
   StringRef SysRoot) const {
   llvm::Triple::EnvironmentType TargetEnvironment =
   TargetTriple.getEnvironment();
+  // Fall back to "-gnu" on unknown environment to preserve the historical
+  // behavior.
+  std::string EnvName =
+  TargetTriple
+  .getEnvironmentTypeName(TargetEnvironment !=
+  llvm::Triple::UnknownEnvironment
+  ? TargetEnvironment
+  : llvm::Triple::GNU)
+  .str();
   bool IsAndroid = TargetTriple.isAndroid();
   bool IsMipsR6 = TargetTriple.getSubArch() == llvm::Triple::MipsSubArch_r6;
   bool IsMipsN32Abi = TargetTriple.getEnvironment() == llvm::Triple::GNUABIN32;
@@ -60,40 +69,30 @@
   case llvm::Triple::thumb:
 if (IsAndroid)
   return "arm-linux-androideabi";
-if (TargetEnvironment == llvm::Triple::GNUEABIHF)
-  return "arm-linux-gnueabihf";
-return "arm-linux-gnueabi";
+return "arm-linux-" + EnvName;
   case llvm::Triple::armeb:
   case llvm::Triple::thumbeb:
-if (TargetEnvironment == llvm::Triple::GNUEABIHF)
-  return "armeb-linux-gnueabihf";
-return "armeb-linux-gnueabi";
+return "armeb-linux-" + EnvName;
   case llvm::Triple::x86:
 if (IsAndroid)
   return "i686-linux-android";
-return "i386-linux-gnu";
+return "i386-linux-" + EnvName;
   case llvm::Triple::x86_64:
-if (IsAndroid)
-  return "x86_64-linux-android";
-if (TargetEnvironment == llvm::Triple::GNUX32)
-  return "x86_64-linux-gnux32";
-return "x86_64-linux-gnu";
+return "x86_64-linux-" + EnvName;
   case llvm::Triple::aarch64:
-if (IsAndroid)
-  return "aarch64-linux-android";
-return "aarch64-linux-gnu";
+return "aarch64-linux-" + EnvName;
   case llvm::Triple::aarch64_be:
-return "aarch64_be-linux-gnu";
+return "aarch64_be-linux-" + EnvName;
 
   case llvm::Triple::m68k:
-return "m68k-linux-gnu";
+return "m68k-linux-" + EnvName;
 
   case llvm::Triple::mips:
-return IsMipsR6 ? "mipsisa32r6-linux-gnu" : "mips-linux-gnu";
+return (IsMipsR6 ? "mipsisa32r6-linux-" : "mips-linux-") + EnvName;
   case llvm::Triple::mipsel:
 if (IsAndroid)
   return "mipsel-linux-android";
-return IsMipsR6 ? "mipsisa32r6el-linux-gnu" : "mipsel-linux-gnu";
+return (IsMipsR6 ? "mipsisa32r6el-linux-" : "mipsel-linux-") + EnvName;
   case llvm::Triple::mips64: {
 std::string MT = std::string(IsMipsR6 ? "mipsisa64r6" : "mips64") +
  "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
@@ -117,21 +116,21 @@
   case llvm::Triple::ppc:
 if (D.getVFS().exists(concat(SysRoot, "/lib/powerpc-linux-gnuspe")))
   return "powerpc-linux-gnuspe";
-return "powerpc-linux-gnu";
+return "powerpc-linux-" + EnvName;
   case llvm::Triple::ppcle:
-return "powerpcle-linux-gnu";
+return "powerpcle-linux-" + EnvName;
   case llvm::Triple::ppc64:
-return "powerpc64-linux-gnu";
+return "powerpc64-linux-" + EnvName;
   case llvm::Triple::ppc64le:
-return "powerpc64le-linux-gnu";
+return "powerpc64le-linux-" + EnvName;
   case llvm::Triple::riscv64:
-return "riscv64-linux-gnu";
+return "riscv64-linux-" + EnvName;
   case llvm::Triple::sparc:
-return "sparc-linux-gnu";
+return "sparc-linux-" + EnvName;
   case llvm::Triple::sparcv9:
-return "sparc64-linux-gnu";
+return "sparc64-linux-" + EnvName;
   case llvm::Triple::systemz:
-return "s390x-linux-gnu";
+return "s390x-linux-" + EnvName;
   }
   return TargetTriple.str();
 }


Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -42,6 +42,15 @@
   StringRef SysRoot) const {
   llvm::Triple::EnvironmentType TargetEnvironment =
   TargetTriple.getEnvironment();
+  // Fall back to "-gnu" on unknown environment to preserve the historical
+  // behavior.
+  std::string EnvName =
+  TargetTriple
+  .getEnvironmentTypeName(TargetEnvironment !=
+  llvm::Triple::UnknownEnvironment
+  ? TargetEnvironment
+  : llvm::Triple::GNU)
+  .st

[PATCH] D131563: [clang] Fix clang multiarch isssue with musl

2022-08-31 Thread Brahmajit via Phabricator via cfe-commits
listout added a comment.

Hey everyone, it would be very helpful if someone looked at this and help me 
merge this patch, python3.11 is failing without these modifications


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

https://reviews.llvm.org/D131563

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


[clang] 0f95b2b - [clang] update pr27699 test to make headers different (NFC)

2022-08-31 Thread Mikhail Goncharov via cfe-commits

Author: Mikhail Goncharov
Date: 2022-08-31T13:12:28+02:00
New Revision: 0f95b2b0606317ba048ff39da7a1d65c3bdc8fb5

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

LOG: [clang] update pr27699 test to make headers different (NFC)

some build systems treat those headers as identical, causing a warning

Added: 


Modified: 
clang/test/Modules/Inputs/PR27699/Subdir/b.h

Removed: 




diff  --git a/clang/test/Modules/Inputs/PR27699/Subdir/b.h 
b/clang/test/Modules/Inputs/PR27699/Subdir/b.h
index 6c36a1a100be7..76e62a61a5234 100644
--- a/clang/test/Modules/Inputs/PR27699/Subdir/b.h
+++ b/clang/test/Modules/Inputs/PR27699/Subdir/b.h
@@ -1 +1,2 @@
+// Identical to a.h.
 #include "streambuf"



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


[clang] ce4c7a9 - [clang] Silence a false positive GCC -Wunused-but-set-parameter warning with constexpr

2022-08-31 Thread Martin Storsjö via cfe-commits

Author: Martin Storsjö
Date: 2022-08-31T14:55:44+03:00
New Revision: ce4c7a987fa3f255fa49570da4be1b9739815369

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

LOG: [clang] Silence a false positive GCC -Wunused-but-set-parameter warning 
with constexpr

This fixes the following warning:

In file included from 
../tools/clang/lib/Tooling/Transformer/Transformer.cpp:9:
../tools/clang/include/clang/Tooling/Transformer/Transformer.h: In 
instantiation of ‘llvm::Error clang::tooling::detail::populateMetadata(const 
clang::transformer::RewriteRuleWith&, size_t, const 
clang::ast_matchers::MatchFinder::MatchResult&, 
clang::tooling::TransformerResult&) [with T = void; size_t = long unsigned 
int]’:
../tools/clang/include/clang/Tooling/Transformer/Transformer.h:179:34:   
required from ‘void 
clang::tooling::detail::WithMetadataImpl::onMatchImpl(const 
clang::ast_matchers::MatchFinder::MatchResult&) [with T = void]’
../tools/clang/include/clang/Tooling/Transformer/Transformer.h:156:8:   
required from here
../tools/clang/include/clang/Tooling/Transformer/Transformer.h:120:25: 
warning: parameter ‘SelectedCase’ set but not used [-Wunused-but-set-parameter]
  120 |  size_t SelectedCase,
  |  ~~~^~~~

The issue is fixed in GCC 10 and later, but this silences the noisy
warning in older versions. See 
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85827
for more details about the bug.

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

Added: 


Modified: 
clang/include/clang/Tooling/Transformer/Transformer.h

Removed: 




diff  --git a/clang/include/clang/Tooling/Transformer/Transformer.h 
b/clang/include/clang/Tooling/Transformer/Transformer.h
index 23683bfb8603..71b1fe81b951 100644
--- a/clang/include/clang/Tooling/Transformer/Transformer.h
+++ b/clang/include/clang/Tooling/Transformer/Transformer.h
@@ -120,6 +120,11 @@ populateMetadata(const transformer::RewriteRuleWith 
&Rule,
  size_t SelectedCase,
  const ast_matchers::MatchFinder::MatchResult &Match,
  TransformerResult &Result) {
+  // Silence a false positive GCC -Wunused-but-set-parameter warning in 
constexpr
+  // cases, by marking SelectedCase as used. See
+  // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85827 for details. The issue 
is
+  // fixed in GCC 10.
+  (void)SelectedCase;
   if constexpr (!std::is_void_v) {
 auto Metadata = Rule.Metadata[SelectedCase]->eval(Match);
 if (!Metadata)



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


[PATCH] D132920: [clang] Silence a false positive GCC -Wunused-but-set-parameter warning with constexpr

2022-08-31 Thread Martin Storsjö 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 rGce4c7a987fa3: [clang] Silence a false positive GCC 
-Wunused-but-set-parameter warning with… (authored by mstorsjo).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132920

Files:
  clang/include/clang/Tooling/Transformer/Transformer.h


Index: clang/include/clang/Tooling/Transformer/Transformer.h
===
--- clang/include/clang/Tooling/Transformer/Transformer.h
+++ clang/include/clang/Tooling/Transformer/Transformer.h
@@ -120,6 +120,11 @@
  size_t SelectedCase,
  const ast_matchers::MatchFinder::MatchResult &Match,
  TransformerResult &Result) {
+  // Silence a false positive GCC -Wunused-but-set-parameter warning in 
constexpr
+  // cases, by marking SelectedCase as used. See
+  // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85827 for details. The issue 
is
+  // fixed in GCC 10.
+  (void)SelectedCase;
   if constexpr (!std::is_void_v) {
 auto Metadata = Rule.Metadata[SelectedCase]->eval(Match);
 if (!Metadata)


Index: clang/include/clang/Tooling/Transformer/Transformer.h
===
--- clang/include/clang/Tooling/Transformer/Transformer.h
+++ clang/include/clang/Tooling/Transformer/Transformer.h
@@ -120,6 +120,11 @@
  size_t SelectedCase,
  const ast_matchers::MatchFinder::MatchResult &Match,
  TransformerResult &Result) {
+  // Silence a false positive GCC -Wunused-but-set-parameter warning in constexpr
+  // cases, by marking SelectedCase as used. See
+  // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85827 for details. The issue is
+  // fixed in GCC 10.
+  (void)SelectedCase;
   if constexpr (!std::is_void_v) {
 auto Metadata = Rule.Metadata[SelectedCase]->eval(Match);
 if (!Metadata)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 5b86174 - Clarifying the documentation for diagnostic formats; NFC

2022-08-31 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-08-31T08:32:58-04:00
New Revision: 5b861743539aa9a1184589647f6e9ce96da8b620

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

LOG: Clarifying the documentation for diagnostic formats; NFC

While discussing diagnostic format strings with a GSoC mentee, it
became clear there was some confusion regarding how to use them.
Specifically, the documentation for %select caused confunsion because
it was using %select{}2 and talking about how the integer value must
be in the range [0..2], which made it seem like the positional argument
was actually specifying the range of acceptable values.

I clarified several of the examples similarly, moved some documentation
to a more appropriate place, and added some additional information to
the %s modifier to point out that %plural exists.

Added: 


Modified: 
clang/docs/InternalsManual.rst

Removed: 




diff  --git a/clang/docs/InternalsManual.rst b/clang/docs/InternalsManual.rst
index 8d18ff01be04..a20fe623a5c8 100644
--- a/clang/docs/InternalsManual.rst
+++ b/clang/docs/InternalsManual.rst
@@ -192,13 +192,18 @@ This gives the ``DiagnosticConsumer`` information about 
what the argument means
 without requiring it to use a specific presentation (consider this MVC for
 Clang :).
 
+It is really easy to add format specifiers to the Clang diagnostics system, but
+they should be discussed before they are added.  If you are creating a lot of
+repetitive diagnostics and/or have an idea for a useful formatter, please bring
+it up on the cfe-dev mailing list.
+
 Here are the 
diff erent diagnostic argument formats currently supported by
 Clang:
 
 **"s" format**
 
 Example:
-  ``"requires %1 parameter%s1"``
+  ``"requires %0 parameter%s0"``
 Class:
   Integers
 Description:
@@ -206,12 +211,15 @@ Description:
   diagnostics.  When the integer is 1, it prints as nothing.  When the integer
   is not 1, it prints as "``s``".  This allows some simple grammatical forms to
   be to be handled correctly, and eliminates the need to use gross things like
-  ``"requires %1 parameter(s)"``.
+  ``"requires %1 parameter(s)"``. Note, this only handles adding a simple
+  "``s``" character, it will not handle situations where pluralization is more
+  complicated such as turning ``fancy`` into ``fancies`` or ``mouse`` into
+  ``mice``. You can use the "plural" format specifier to handle such 
situations.
 
 **"select" format**
 
 Example:
-  ``"must be a %select{unary|binary|unary or binary}2 operator"``
+  ``"must be a %select{unary|binary|unary or binary}0 operator"``
 Class:
   Integers
 Description:
@@ -219,7 +227,7 @@ Description:
   into one common one, without requiring the 
diff erence to be specified as an
   English string argument.  Instead of specifying the string, the diagnostic
   gets an integer argument and the format string selects the numbered option.
-  In this case, the "``%2``" value must be an integer in the range [0..2].  If
+  In this case, the "``%0``" value must be an integer in the range [0..2].  If
   it is 0, it prints "unary", if it is 1 it prints "binary" if it is 2, it
   prints "unary or binary".  This allows other language translations to
   substitute reasonable words (or entire phrases) based on the semantics of the
@@ -229,11 +237,11 @@ Description:
 **"plural" format**
 
 Example:
-  ``"you have %1 %plural{1:mouse|:mice}1 connected to your computer"``
+  ``"you have %0 %plural{1:mouse|:mice}0 connected to your computer"``
 Class:
   Integers
 Description:
-  This is a formatter for complex plural forms.  It is designed to handle even
+  This is a formatter for complex plural forms. It is designed to handle even
   the requirements of languages with very complex plural forms, as many Baltic
   languages have.  The argument consists of a series of expression/form pairs,
   separated by ":", where the first form whose expression evaluates to true is
@@ -245,10 +253,10 @@ Description:
   numeric condition can take one of three forms.
 
   * number: A simple decimal number matches if the argument is the same as the
-number.  Example: ``"%plural{1:mouse|:mice}4"``
+number.  Example: ``"%plural{1:mouse|:mice}0"``
   * range: A range in square brackets matches if the argument is within the
 range.  Then range is inclusive on both ends.  Example:
-``"%plural{0:none|1:one|[2,5]:some|:many}2"``
+``"%plural{0:none|1:one|[2,5]:some|:many}0"``
   * modulo: A modulo operator is followed by a number, and equals sign and
 either a number or a range.  The tests are the same as for plain numbers
 and ranges, but the argument is taken modulo the number first.  Example:
@@ -314,11 +322,6 @@ Description:
   If tree printing is on, the text after the pipe is printed and a type tree is
   printed 

[PATCH] D133009: [libclang] Fix conversion from `StringRef` to `CXString`

2022-08-31 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan updated this revision to Diff 456942.
egorzhdan added a comment.

XFAIL a test that was accidentally passing because of incorrect behavior


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133009

Files:
  clang/test/Index/comment-lots-of-unknown-commands.c
  clang/test/Index/comment-to-html-xml-conversion.cpp
  clang/tools/libclang/CXString.cpp


Index: clang/tools/libclang/CXString.cpp
===
--- clang/tools/libclang/CXString.cpp
+++ clang/tools/libclang/CXString.cpp
@@ -78,13 +78,22 @@
 }
 
 CXString createRef(StringRef String) {
+  if (!String.data())
+return createNull();
+
+  // If the string is empty, it might point to a position in another string
+  // while having zero length. Make sure we don't create a reference to the
+  // larger string.
+  if (String.empty())
+return createEmpty();
+
   // If the string is not nul-terminated, we have to make a copy.
 
   // FIXME: This is doing a one past end read, and should be removed! For 
memory
   // we don't manage, the API string can become unterminated at any time 
outside
   // our control.
 
-  if (!String.empty() && String.data()[String.size()] != 0)
+  if (String.data()[String.size()] != 0)
 return createDup(String);
 
   CXString Result;
Index: clang/test/Index/comment-to-html-xml-conversion.cpp
===
--- clang/test/Index/comment-to-html-xml-conversion.cpp
+++ clang/test/Index/comment-to-html-xml-conversion.cpp
@@ -744,6 +744,15 @@
 // CHECK-NEXT: (CXComment_Text Text=[ ] IsWhitespace)
 // CHECK-NEXT: (CXComment_InlineCommand CommandName=[anchor] 
RenderAnchor Arg[0]=A)))]
 
+/// Aaa ccc
+void comment_to_html_conversion_40();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: 
FunctionDecl=comment_to_html_conversion_40:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_40c:@F@comment_to_html_conversion_40#void
 comment_to_html_conversion_40() Aaa 
ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=)
 
 /// Aaa.
 class comment_to_xml_conversion_01 {
Index: clang/test/Index/comment-lots-of-unknown-commands.c
===
--- clang/test/Index/comment-lots-of-unknown-commands.c
+++ clang/test/Index/comment-lots-of-unknown-commands.c
@@ -1,5 +1,7 @@
 // RUN: c-index-test -test-load-source-reparse 1 local %s | FileCheck %s
 
+// XFAIL: *
+
 // See PR 21254. We had too few bits to encode command IDs so if you created
 // enough of them the ID codes would wrap around. This test creates commands up
 // to an ID of 258. Ideally we should check for large numbers, but that would


Index: clang/tools/libclang/CXString.cpp
===
--- clang/tools/libclang/CXString.cpp
+++ clang/tools/libclang/CXString.cpp
@@ -78,13 +78,22 @@
 }
 
 CXString createRef(StringRef String) {
+  if (!String.data())
+return createNull();
+
+  // If the string is empty, it might point to a position in another string
+  // while having zero length. Make sure we don't create a reference to the
+  // larger string.
+  if (String.empty())
+return createEmpty();
+
   // If the string is not nul-terminated, we have to make a copy.
 
   // FIXME: This is doing a one past end read, and should be removed! For memory
   // we don't manage, the API string can become unterminated at any time outside
   // our control.
 
-  if (!String.empty() && String.data()[String.size()] != 0)
+  if (String.data()[String.size()] != 0)
 return createDup(String);
 
   CXString Result;
Index: clang/test/Index/comment-to-html-xml-conversion.cpp
===
--- clang/test/Index/comment-to-html-xml-conversion.cpp
+++ clang/test/Index/comment-to-html-xml-conversion.cpp
@@ -744,6 +744,15 @@
 // CHECK-NEXT: (CXComment_Text Text=[ ] IsWhitespace)
 // CHECK-NEXT: (CXComment_InlineCommand CommandName=[anchor] RenderAnchor Arg[0]=A)))]
 
+/// Aaa ccc
+void comment_to_html_conversion_40();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_40:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_40c:@F@comment_to_html_conversion_40#void comment_to_html_conversion_40() Aaa ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=)
 
 /// Aaa.
 class comment_to_xml_conversion_01 {
Index: clang/

[PATCH] D129488: [Sema] Delay evaluation of std::source_location::current() in default arguments

2022-08-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

@aaron.ballman, that's my reading of the standard as well. Do you think we 
should proceed with the current approach or is there another direction worth 
pursuing to make source_location work?

In D129488#3760178 , @ChuanqiXu wrote:

> There is another example we shouldn't make this specific for 
> std::source_location::current(): 
> https://github.com/llvm/llvm-project/issues/57459. I guess we can solve the 
> issue too if we evaluate default argument at the caller position.

I think you're right and it would probably work automatically if we were to 
recreate the default argument expression on every call where it appears.
However, going this route for the particular purpose of checking module 
visibility looks like an overkill. FWIW, see my attempt at this to fix 
`source_location::current()` with immediate invocations D132941 
.
It's complicated, makes default arguments slower and encounters new failures 
modes, e.g. there new errors with lambdas in default arguments.

I suspect this could be done relatively cheaply and simply inside the 
`MarkDeclarationsReferencedInExpr` call at the bottom of 
`Sema::CheckCXXDefaultArgExpr`.
I tried prototyping this and it seems to fit nicely with the current design. We 
just need to add a few notes to link between the locations of parameter 
initializers and calls involving default arguments.
(It is still tricky to get right in all cases since we need to enumerate all 
positions where complete types are required, but certainly does not look 
impossible).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129488

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


[PATCH] D133009: [libclang] Fix conversion from `StringRef` to `CXString`

2022-08-31 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan added inline comments.



Comment at: clang/test/Index/comment-lots-of-unknown-commands.c:3
 
+// XFAIL: *
+

This test was never properly passing. Because of the bug in string conversion, 
the printed comments contained the entire source file and not just the 
comments' text, which was enough to cause `// CHECK`-s in the test to succeed.
```
// CHECK: (CXComment_InlineCommand CommandName=[tel] RenderNormal 
HasTrailingNewline)
// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
HasTrailingNewline))
// CHECK:   (CXComment_VerbatimLine 
Text=[\n@Lo\n@il\n@tle\n@axt\n@ba\n@ust\n@ac\n@tpe\n@tpl\n@ctG\n@ru\n@m\n@tG\n@it\n@rh\n@G\n@rpc\n@el\n@er\n@w\n@eo\n@tx\n@oo\n@dD\n@dD\n*/\nvoid
 f();\n\n// CHECK:  CommentAST=[\n// CHECK:(CXComment_FullComment\n// 
CHECK:   (CXComment_Paragraph\n// CHECK:  ...
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133009

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


[PATCH] D132997: [clang][Interp] Handle DeclRefExpr of reference types

2022-08-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 456944.

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

https://reviews.llvm.org/D132997

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/arrays.cpp
  clang/test/AST/Interp/references.cpp

Index: clang/test/AST/Interp/references.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/references.cpp
@@ -0,0 +1,73 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
+// RUN: %clang_cc1 -verify=ref %s
+
+
+// expected-no-diagnostics
+// ref-no-diagnostics
+
+constexpr int a = 10;
+constexpr const int &b = a;
+static_assert(a == b, "");
+
+constexpr int assignToReference() {
+  int a = 20;
+  int &b =a;
+
+  b = 100;
+  return a;
+}
+static_assert(assignToReference() == 100, "");
+
+
+constexpr void setValue(int &dest, int val) {
+  dest = val;
+}
+
+constexpr int checkSetValue() {
+  int l = 100;
+  setValue(l, 200);
+  return l;
+}
+static_assert(checkSetValue() == 200, "");
+
+constexpr int readLocalRef() {
+  int a = 20;
+  int &b = a;
+  return b;
+}
+static_assert(readLocalRef() == 20, "");
+
+constexpr int incRef() {
+  int a = 0;
+  int &b = a;
+
+  b = b + 1;
+
+  return a;
+}
+static_assert(incRef() == 1, "");
+
+
+template
+constexpr void Plus3(int &A) {
+  A = V + 3;
+}
+constexpr int foo = 4;
+
+constexpr int callTemplate() {
+  int a = 3;
+  Plus3(a);
+  return a;
+}
+static_assert(callTemplate() == 7, "");
+
+
+constexpr int& getValue(int *array, int index) {
+  return array[index];
+}
+constexpr int testGetValue() {
+  int values[] = {1, 2, 3, 4};
+  getValue(values, 2) = 30;
+  return values[2];
+}
+static_assert(testGetValue() == 30, "");
Index: clang/test/AST/Interp/arrays.cpp
===
--- clang/test/AST/Interp/arrays.cpp
+++ clang/test/AST/Interp/arrays.cpp
@@ -45,6 +45,13 @@
 static_assert(getElementOf(foo[0], 1) == &m, "");
 
 
+template 
+constexpr T& getElementOfArray(T (&array)[N], int I) {
+  return array[I];
+}
+static_assert(getElementOfArray(foo[2], 3) == &m, "");
+
+
 constexpr int data[] = {5, 4, 3, 2, 1};
 static_assert(data[0] == 4, ""); // expected-error{{failed}} \
  // expected-note{{5 == 4}} \
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -845,15 +845,38 @@
 template 
 bool ByteCodeExprGen::VisitDeclRefExpr(const DeclRefExpr *E) {
   const auto *Decl = E->getDecl();
+  bool IsReference = Decl->getType()->isReferenceType();
+  bool FoundDecl = false;
 
   if (auto It = Locals.find(Decl); It != Locals.end()) {
 const unsigned Offset = It->second.Offset;
-return this->emitGetPtrLocal(Offset, E);
+if (!this->emitGetPtrLocal(Offset, E))
+  return false;
+
+FoundDecl = true;
   } else if (auto GlobalIndex = P.getGlobal(Decl)) {
-return this->emitGetPtrGlobal(*GlobalIndex, E);
+if (!this->emitGetPtrGlobal(*GlobalIndex, E))
+  return false;
+
+FoundDecl = true;
   } else if (const auto *PVD = dyn_cast(Decl)) {
-if (auto It = this->Params.find(PVD); It != this->Params.end())
-  return this->emitGetPtrParam(It->second, E);
+if (auto It = this->Params.find(PVD); It != this->Params.end()) {
+  if (!this->emitGetPtrParam(It->second, E))
+return false;
+
+  FoundDecl = true;
+}
+  }
+
+  // References are implemented using pointers, so when we get here,
+  // we have a pointer to a pointer, which we need to de-reference once.
+  if (FoundDecl) {
+if (IsReference) {
+  if (!this->emitLoadPop(PT_Ptr, E))
+return false;
+}
+
+return true;
   }
 
   return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132727: [clang][Interp] Implement array initializers and subscript expressions

2022-08-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder marked an inline comment as done.
tbaeder added inline comments.



Comment at: clang/test/AST/Interp/arrays.cpp:41-44
+template
+constexpr T getElementOf(T* array, int i) {
+  return array[i];
+}

aaron.ballman wrote:
> A similar test we might want to add (whenever we get around to references):
> ```
> template 
> constexpr T& getElementOf(T (&array)[N], int I) {
>   return array[I];
> }
> static_assert(getElementOf(foo[2], 3) == &m, "");
> ```
I added that to https://reviews.llvm.org/D132997


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

https://reviews.llvm.org/D132727

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


Re: [clang] b58ed43 - Revert "[clang] Fix a crash in constant evaluation"

2022-08-31 Thread Aaron Ballman via cfe-commits
On Wed, Aug 31, 2022 at 4:13 AM Kadir Cetinkaya via cfe-commits
 wrote:
>
>
> Author: Kadir Cetinkaya
> Date: 2022-08-31T10:12:52+02:00
> New Revision: b58ed43a7f6b67bdb03ab746b654c823f54c261f
>
> URL: 
> https://github.com/llvm/llvm-project/commit/b58ed43a7f6b67bdb03ab746b654c823f54c261f
> DIFF: 
> https://github.com/llvm/llvm-project/commit/b58ed43a7f6b67bdb03ab746b654c823f54c261f.diff
>
> LOG: Revert "[clang] Fix a crash in constant evaluation"
>
> This reverts commit a5ab650714d05c2e49ec158dc99156118a893027.

Thank you for the revert, but next time, can you please add
information to the commit message as to why the revert is happening?
That helps us out a bunch when we're doing git blames to see how
changes made it into or out of the project. Thanks!

~Aaron

>
> Added:
>
>
> Modified:
> clang/lib/AST/ExprConstant.cpp
>
> Removed:
>
>
>
> 
> diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
> index 2b1a30f8354fb..3df0e4292b6ca 100644
> --- a/clang/lib/AST/ExprConstant.cpp
> +++ b/clang/lib/AST/ExprConstant.cpp
> @@ -4794,11 +4794,6 @@ static bool getDefaultInitValue(QualType T, APValue 
> &Result) {
>Result = APValue((const FieldDecl *)nullptr);
>return true;
>  }
> -// Can't access properties of an incomplete type.
> -if (!RD->hasDefinition()) {
> -  Result = APValue();
> -  return false;
> -}
>  Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
>   std::distance(RD->field_begin(), RD->field_end()));
>
>
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132131: [clang-format] Adds a formatter for aligning trailing comments over empty lines

2022-08-31 Thread Yusuke Kadowaki via Phabricator via cfe-commits
yusuke-kadowaki updated this revision to Diff 456945.
yusuke-kadowaki marked 4 inline comments as done.
yusuke-kadowaki added a comment.

- Remove trailing whitespace
- Update document


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132131

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

Index: clang/unittests/Format/FormatTestComments.cpp
===
--- clang/unittests/Format/FormatTestComments.cpp
+++ clang/unittests/Format/FormatTestComments.cpp
@@ -2858,6 +2858,106 @@
"int a; //\n");
 }
 
+TEST_F(FormatTestComments, AlignTrailingCommentsAcrossEmptyLines) {
+  FormatStyle Style = getLLVMStyle();
+  Style.AlignConsecutiveTrailingComments.AcrossEmptyLines = true;
+  verifyFormat("#include \"a.h\"  // simple\n"
+   "\n"
+   "#include \"aa.h\" // example case\n",
+   Style);
+
+  verifyFormat("#include \"a.h\"   // align across\n"
+   "\n"
+   "#include \"aa.h\"  // two empty lines\n"
+   "\n"
+   "#include \"aaa.h\" // in a row\n",
+   Style);
+
+  verifyFormat("#include \"a.h\"  // align\n"
+   "#include \"aa.h\" // comment\n"
+   "#include \"aaa.h\"// blocks\n"
+   "\n"
+   "#include \".h\"   // across\n"
+   "#include \"a.h\"  // one\n"
+   "#include \"aa.h\" // empty line\n",
+   Style);
+
+  verifyFormat("#include \"a.h\"  // align trailing comments\n"
+   "#include \"a.h\"\n"
+   "#include \"aa.h\" // across a line without comment\n",
+   Style);
+
+  verifyFormat("#include \"a.h\"   // align across\n"
+   "#include \"a.h\"\n"
+   "#include \"aa.h\"  // two lines without comment\n"
+   "#include \"a.h\"\n"
+   "#include \"aaa.h\" // in a row\n",
+   Style);
+
+  verifyFormat("#include \"a.h\"  // align\n"
+   "#include \"aa.h\" // comment\n"
+   "#include \"aaa.h\"// blocks\n"
+   "#include \"a.h\"\n"
+   "#include \".h\"   // across\n"
+   "#include \"a.h\"  // a line without\n"
+   "#include \"aa.h\" // comment\n",
+   Style);
+
+  verifyFormat("#include \"a.h\"  // Align these\n"
+   "\n"
+   "#include \"aa.h\" // two comments\n"
+   "#include \"aaa.h\"\n"
+   "#include \"aaa.h\"\n"
+   "#include \"aaa.h\" // But do not align this because there are two lines without comments above\n",
+   Style);
+
+  Style.ColumnLimit = 15;
+  EXPECT_EQ("int ab; // line\n"
+"int a;  // long\n"
+"// long\n"
+"\n"
+"// long",
+format("int ab; // line\n"
+   "int a; // long long\n"
+   "\n"
+   "// long",
+   Style));
+
+  Style.ColumnLimit = 15;
+  EXPECT_EQ("int ab; // line\n"
+"\n"
+"int a;  // long\n"
+"// long\n",
+format("int ab; // line\n"
+   "\n"
+   "int a; // long long\n",
+   Style));
+
+  Style.ColumnLimit = 80;
+  EXPECT_EQ("int a; // line about a\n"
+"\n"
+"// line about b\n"
+"long b;",
+format("int a; // line about a\n"
+   "\n"
+   "   // line about b\n"
+   "   long b;",
+   Style));
+
+  Style.ColumnLimit = 80;
+  EXPECT_EQ("int a; // line about a\n"
+"\n"
+"// line 1 about b\n"
+"// line 2 about b\n"
+"long b;",
+format("int a; // line about a\n"
+   "\n"
+   "   // line 1 about b\n"
+   "   // line 2 about b\n"
+   "   long b;",
+   Style));
+}
+
 TEST_F(FormatTestComments, AlignsBlockCommentDecorations) {
   EXPECT_EQ("/*\n"
 " */",
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -20041,7 +20041,6 @@
 TEST_F(FormatTest, ParsesConfigurationBools) {
   FormatStyle Style = {};
   Style.Language = FormatStyle::LK_Cpp;
-  CHECK_PARSE_BOOL(AlignTrailingComments);
   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
   CHECK_PARSE_BOOL(AllowShortCaseLab

[PATCH] D132131: [clang-format] Adds a formatter for aligning trailing comments over empty lines

2022-08-31 Thread Yusuke Kadowaki via Phabricator via cfe-commits
yusuke-kadowaki added inline comments.



Comment at: clang/docs/ClangFormatStyleOptions.rst:785
+  - Consecutive
+  - AcrossEmptyLines
+  - AcrossComments

HazardyKnusperkeks wrote:
> yusuke-kadowaki wrote:
> > MyDeveloperDay wrote:
> > > may be AcrossEmptyLines should be a number (to mean the number of empty 
> > > lines)
> > We need to introduce a new struct to do that since AlignConsecutiveStyle is 
> > shared with some options and not possible to be changed. Plus I think more 
> > than two empty lines are formatted to one empty line anyway.
> There `MaxEmptyLinesToKeep` which would allow to set it higher.
> 
> If we want to change the `bool` to an `unsigned`, then that should be a 
> different change.
Oh I didn't know `MaxEmptyLinesToKeep`. Thank you for sharing.
I can try to change it that way when we done with this patch. Test cases would 
be complicated tho.



Comment at: clang/unittests/Format/FormatTestComments.cpp:2863
+  FormatStyle Style = getLLVMStyle();
+  Style.AlignConsecutiveTrailingComments.AcrossEmptyLines = true;
+  verifyFormat("#include \"a.h\"  // simple\n"

HazardyKnusperkeks wrote:
> Interesting would be a comment which is split, do we continue to align, or 
> not?
Could you give me a specific example?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132131

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


[PATCH] D132918: [clang] Fix a crash in constant evaluation

2022-08-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:4797
 }
+// Can't access properties of an incomplete type.
+if (!RD->hasDefinition()) {

kadircet wrote:
> shafik wrote:
> > erichkeane wrote:
> > > It seems to me that we shouldn't GET to this function with an incomplete 
> > > type.  I suspect whoever calls this is doing so incorrectly.
> > Also note we only check in `ExprConstant.cpp` for `hasDefinition()` in one 
> > other place in `findCompleteObject` and that is around extern see: 
> > https://github.com/llvm/llvm-project/commit/c0d04a2567c22631595bed8092bc042bb91ea4ee#diff-255a21a02a8966766225831836d482547787baf9a770fbf67178ebb7d7347e27
> > It seems to me that we shouldn't GET to this function with an incomplete 
> > type. I suspect whoever calls this is doing so incorrectly.
> 
> Agreed, that's also my assumption. but we've been unable to get a minimal 
> crasher. i am not a fan of landing these changes without reproducers but this 
> was clearly fixing the issue we had (moreover, it's happening on invalid 
> code).
> 
> moreover we're checking for recorddecl being invalid up above, so it felt 
> quite likely to hit this code path with incomplete types as well (or there 
> were some changes up the callstack that forgot to update the implementation 
> here).
> Agreed, that's also my assumption. but we've been unable to get a minimal 
> crasher. i am not a fan of landing these changes without reproducers but this 
> was clearly fixing the issue we had (moreover, it's happening on invalid 
> code).

It's hard to say that it actually is fixing the issue instead of papering over 
the root cause elsewhere in the project. Having test coverage helps us to 
determine whether the fix is correct or incorrect.

> moreover we're checking for recorddecl being invalid up above, so it felt 
> quite likely to hit this code path with incomplete types as well (or there 
> were some changes up the callstack that forgot to update the implementation 
> here).

If the type is incomplete, why is the record not invalid? This smells like 
we're possibly missing a call to `RequireCompleteType()` somewhere else.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132918

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


[PATCH] D132918: [clang] Fix a crash in constant evaluation

2022-08-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: aaron.ballman, clang-language-wg.
aaron.ballman requested changes to this revision.
aaron.ballman added a comment.
This revision now requires changes to proceed.

Marking this as requesting changes so we don't have another accidental commit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132918

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


[PATCH] D132851: Further update -Wbitfield-constant-conversion for 1-bit bitfield

2022-08-31 Thread Aaron Ballman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3b00e486797c: Further update -Wbitfield-constant-conversion 
for 1-bit bitfield (authored by aaron.ballman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132851

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CXX/drs/dr6xx.cpp
  clang/test/Sema/constant-conversion.c
  clang/test/SemaCXX/constant-conversion.cpp

Index: clang/test/SemaCXX/constant-conversion.cpp
===
--- clang/test/SemaCXX/constant-conversion.cpp
+++ clang/test/SemaCXX/constant-conversion.cpp
@@ -22,3 +22,12 @@
   char ok3 = true ? 0 : 9 + 1;
   char ok4 = true ? 0 : nines() + 1;
 }
+
+void test_bitfield() {
+  struct S {
+int one_bit : 1;
+  } s;
+
+  s.one_bit = 1;// expected-warning {{implicit truncation from 'int' to a one-bit wide bit-field changes value from 1 to -1}}
+  s.one_bit = true; // no-warning
+}
Index: clang/test/Sema/constant-conversion.c
===
--- clang/test/Sema/constant-conversion.c
+++ clang/test/Sema/constant-conversion.c
@@ -1,4 +1,7 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -triple x86_64-apple-darwin %s
+// RUN: %clang_cc1 -fsyntax-only -ffreestanding -verify=expected,one-bit -triple x86_64-apple-darwin %s
+// RUN: %clang_cc1 -fsyntax-only -ffreestanding -Wno-single-bit-bitfield-constant-conversion -verify -triple x86_64-apple-darwin %s
+
+#include 
 
 // This file tests -Wconstant-conversion, a subcategory of -Wconversion
 // which is on by default.
@@ -19,12 +22,14 @@
 int b : 1;  // The only valid values are 0 and -1.
   } s;
 
-  s.b = -3; // expected-warning {{implicit truncation from 'int' to bit-field changes value from -3 to -1}}
-  s.b = -2; // expected-warning {{implicit truncation from 'int' to bit-field changes value from -2 to 0}}
-  s.b = -1; // no-warning
-  s.b = 0;  // no-warning
-  s.b = 1;  // expected-warning {{implicit truncation from 'int' to bit-field changes value from 1 to -1}}
-  s.b = 2;  // expected-warning {{implicit truncation from 'int' to bit-field changes value from 2 to 0}}
+  s.b = -3;// expected-warning {{implicit truncation from 'int' to bit-field changes value from -3 to -1}}
+  s.b = -2;// expected-warning {{implicit truncation from 'int' to bit-field changes value from -2 to 0}}
+  s.b = -1;// no-warning
+  s.b = 0; // no-warning
+  s.b = 1; // one-bit-warning {{implicit truncation from 'int' to a one-bit wide bit-field changes value from 1 to -1}}
+  s.b = true;  // no-warning (we suppress it manually to reduce false positives)
+  s.b = false; // no-warning
+  s.b = 2; // expected-warning {{implicit truncation from 'int' to bit-field changes value from 2 to 0}}
 }
 
 enum Test2 { K_zero, K_one };
Index: clang/test/CXX/drs/dr6xx.cpp
===
--- clang/test/CXX/drs/dr6xx.cpp
+++ clang/test/CXX/drs/dr6xx.cpp
@@ -911,9 +911,9 @@
 namespace dr675 { // dr675: dup 739
   template struct A { T n : 1; };
 #if __cplusplus >= 201103L
-  static_assert(A{1}.n < 0, ""); // expected-warning {{implicit truncation from 'int' to bit-field changes value from 1 to -1}}
-  static_assert(A{1}.n < 0, ""); // expected-warning {{implicit truncation from 'int' to bit-field changes value from 1 to -1}}
-  static_assert(A{1}.n < 0, ""); // expected-warning {{implicit truncation from 'int' to bit-field changes value from 1 to -1}}
+  static_assert(A{1}.n < 0, ""); // expected-warning {{implicit truncation from 'int' to a one-bit wide bit-field changes value from 1 to -1}}
+  static_assert(A{1}.n < 0, ""); // expected-warning {{implicit truncation from 'int' to a one-bit wide bit-field changes value from 1 to -1}}
+  static_assert(A{1}.n < 0, ""); // expected-warning {{implicit truncation from 'int' to a one-bit wide bit-field changes value from 1 to -1}}
 #endif
 }
 
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -13047,6 +13047,18 @@
 
   unsigned OriginalWidth = Value.getBitWidth();
 
+  // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
+  // false positives where the user is demonstrating they intend to use the
+  // bit-field as a Boolean, check to see if the value is 1 and we're assigning
+  // to a one-bit bit-field to see if the value came from a macro named 'true'.
+  bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
+  if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
+SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
+if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc)

[clang] 3b00e48 - Further update -Wbitfield-constant-conversion for 1-bit bitfield

2022-08-31 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-08-31T09:23:45-04:00
New Revision: 3b00e486797c0a28f0b5216ea507329d098ce573

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

LOG: Further update -Wbitfield-constant-conversion for 1-bit bitfield

https://reviews.llvm.org/D131255 (82afc9b169a67e8b8a1862fb9c41a2cd974d6691)
began warning about conversion causing data loss for a single-bit
bit-field. However, after landing the changes, there were reports about
significant false positives from some code bases.

This alters the approach taken in that patch by introducing a new
warning group (-Wsingle-bit-bitfield-constant-conversion) which is
grouped under -Wbitfield-constant-conversion to allow users to
selectively disable the single-bit warning without losing the other
constant conversion warnings.

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaChecking.cpp
clang/test/CXX/drs/dr6xx.cpp
clang/test/Sema/constant-conversion.c
clang/test/SemaCXX/constant-conversion.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 944d88d230171..2251993a7c72b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -106,9 +106,13 @@ Improvements to Clang's diagnostics
 - ``-Wformat`` now recognizes ``%b`` for the ``printf``/``scanf`` family of
   functions and ``%B`` for the ``printf`` family of functions. Fixes
   `Issue 56885: `_.
-- ``-Wbitfield-constant-conversion`` now diagnoses implicit truncation when 1 
is
-  assigned to a 1-bit signed integer bitfield. This fixes
-  `Issue 53253 `_.
+- Introduced ``-Wsingle-bit-bitfield-constant-conversion``, grouped under
+  ``-Wbitfield-constant-conversion``, which diagnoses implicit truncation when
+  ``1`` is assigned to a 1-bit signed integer bitfield. This fixes
+  `Issue 53253 `_. To reduce
+  potential false positives, this diagnostic will not diagnose use of the
+  ``true`` macro (from ``>`) in C language mode despite the macro
+  being defined to expand to ``1``.
 - ``-Wincompatible-function-pointer-types`` now defaults to an error in all C
   language modes. It may be downgraded to a warning with
   ``-Wno-error=incompatible-function-pointer-types`` or disabled entirely with

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index ba2fef2a80858..825092b34339c 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -47,7 +47,10 @@ def BinaryLiteral : DiagGroup<"binary-literal", 
[CXX14BinaryLiteral,
  CXXPre14CompatBinaryLiteral,
  GNUBinaryLiteral]>;
 def GNUCompoundLiteralInitializer : 
DiagGroup<"gnu-compound-literal-initializer">;
-def BitFieldConstantConversion : DiagGroup<"bitfield-constant-conversion">;
+def SingleBitBitFieldConstantConversion :
+  DiagGroup<"single-bit-bitfield-constant-conversion">;
+def BitFieldConstantConversion : DiagGroup<"bitfield-constant-conversion",
+   
[SingleBitBitFieldConstantConversion]>;
 def BitFieldEnumConversion : DiagGroup<"bitfield-enum-conversion">;
 def BitFieldWidth : DiagGroup<"bitfield-width">;
 def CompoundTokenSplitByMacro : DiagGroup<"compound-token-split-by-macro">;

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ae10b13c8c769..160b931007adf 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3846,6 +3846,9 @@ def warn_impcast_integer_64_32 : Warning<
 def warn_impcast_integer_precision_constant : Warning<
   "implicit conversion from %2 to %3 changes value from %0 to %1">,
   InGroup;
+def warn_impcast_single_bit_bitield_precision_constant : Warning<
+  "implicit truncation from %2 to a one-bit wide bit-field changes value from "
+  "%0 to %1">, InGroup;
 def warn_impcast_bitfield_precision_constant : Warning<
   "implicit truncation from %2 to bit-field changes value from %0 to %1">,
   InGroup;

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index e2e3d64fcade7..8073223116c29 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -13047,6 +13047,18 @@ static bool AnalyzeBitFieldAssignment(Sema &S, 
FieldDecl *Bitfield, Expr *Init,
 
   unsigned Orig

[PATCH] D130181: [clang-tidy] Add readability-use-early-exits check

2022-08-31 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability/use-early-exits.rst:63
+void Process(bool A, bool B) {
+  if (A && B) {
+// Long processing.

njames93 wrote:
> JonasToth wrote:
> > if this option is false, the transformation would be `if(!(A && B))`, right?
> > 
> > should demorgan rules be applied or at least be mentioned here? I think 
> > transforming to `if (!A || !B)` is at least a viable option for enough 
> > users.
> Once this is in, I plan to merge some common code with the 
> simplify-boolean-expr logic for things like demorgan processing. Right now 
> the transformation happens, the simplify boolean suggests a demorgan 
> transformation of you run the output through clang tidy.
a short reference to the `readability-simplify-boolean-expr` check in the user 
facing docs would be great.
i personally find it ok if the users "pipe" multiple checks together to reach a 
final transformation.

would this check then use the same settings as the 
`readability-simplify-boolean-expr` check? (that of course off topic and does 
not relate to this patch :) )


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130181

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


[PATCH] D131563: [clang] Fix clang multiarch isssue with musl

2022-08-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a reviewer: echristo.
aaron.ballman added a comment.

Adding another reviewer to try to get this unstuck.

Can you add test coverage for the changes (to clang\test\Driver)? Also, there 
should be a release note so users know about the fix (that can go into 
clang\docs\ReleaseNotes.rst).


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

https://reviews.llvm.org/D131563

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


[PATCH] D130096: [Clang][AMDGPU] Emit AMDGPU library control constants in clang

2022-08-31 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added inline comments.



Comment at: clang/lib/CodeGen/TargetInfo.cpp:9436
+CGM.getModule(), Type, true,
+llvm::GlobalValue::LinkageTypes::LinkOnceODRLinkage,
+llvm::ConstantInt::get(Type, Value), Name, nullptr,

jhuber6 wrote:
> yaxunl wrote:
> > jhuber6 wrote:
> > > yaxunl wrote:
> > > > yaxunl wrote:
> > > > > jhuber6 wrote:
> > > > > > yaxunl wrote:
> > > > > > > This does not support per-TU control variables. Probably should 
> > > > > > > use internal linkage.
> > > > > > The AMDGPU device libraries use `linkone_odr` so I figured it was 
> > > > > > the most appropriate here. It should mean that we can have multiple 
> > > > > > identical definitions and they don't clash. There's also no 
> > > > > > requirement for these to be emitted as symbols AFAIK.
> > > > > > The AMDGPU device libraries use `linkone_odr` so I figured it was 
> > > > > > the most appropriate here. It should mean that we can have multiple 
> > > > > > identical definitions and they don't clash. There's also no 
> > > > > > requirement for these to be emitted as symbols AFAIK.
> > > > > 
> > > > > clang uses  -mlink-builtin-bitcode to link these device libraries for 
> > > > > HIP and OpenCL. Then the linkage of these variables becomes internal 
> > > > > linkage. That's why it works for per-TU control.
> > > > > > The AMDGPU device libraries use `linkone_odr` so I figured it was 
> > > > > > the most appropriate here. It should mean that we can have multiple 
> > > > > > identical definitions and they don't clash. There's also no 
> > > > > > requirement for these to be emitted as symbols AFAIK.
> > > > > 
> > > > > clang uses  -mlink-builtin-bitcode to link these device libraries for 
> > > > > HIP and OpenCL. Then the linkage of these variables becomes internal 
> > > > > linkage. That's why it works for per-TU control.
> > > > 
> > > > You may let HIP and OpenCL use internal linkage and C/C++/OpenMP use 
> > > > linkonce_odr since only HIP and OpenCL toolchain use 
> > > > -mlink-builtin-bitcode to link these device libraries 
> > > I see, `linkonce_odr` implies that these should all have the same value 
> > > which isn't necessarily true after linking. I'll change it to use private 
> > > linkage.
> > > 
> > > OpenMP right now links everything late which means that we don't allow 
> > > these to be defined differently per-TU. This may be incorrect given this 
> > > new method as each TU will have different things set. I can change OpenMP 
> > > to use the `mlink` method after this patch which may be more strictly 
> > > correct.
> > > I see, `linkonce_odr` implies that these should all have the same value 
> > > which isn't necessarily true after linking. I'll change it to use private 
> > > linkage.
> > > 
> > > OpenMP right now links everything late which means that we don't allow 
> > > these to be defined differently per-TU. This may be incorrect given this 
> > > new method as each TU will have different things set. I can change OpenMP 
> > > to use the `mlink` method after this patch which may be more strictly 
> > > correct.
> > 
> > On second thoughts, the idea for letting clang to emit these control 
> > variables might not work for HIP and OpenCL. The reason is that to support 
> > per-TU control variables, these variables need to be internal or private 
> > linkage, however, that means they cannot be used by other device library 
> > functions which are expecting non-internal linkage for them. Those device 
> > library functions will end up using control variables from device library 
> > bitcode any way.
> > 
> > For OpenMP, it may be necessary to emit them as linkonce_odr, otherwise 
> > device library functions may not find them.
> > On second thoughts, the idea for letting clang to emit these control 
> > variables might not work for HIP and OpenCL. The reason is that to support 
> > per-TU control variables, these variables need to be internal or private 
> > linkage, however, that means they cannot be used by other device library 
> > functions which are expecting non-internal linkage for them. Those device 
> > library functions will end up using control variables from device library 
> > bitcode any way.
> 
> Right now we include each file per-TU using `-mlink-builtin-bitcode` which 
> converts `linkonce_odr` to `private` linkage. Shouldn't this be equivalent? 
> It may be possible to make some test showing a user of these constants to 
> verify they get picked up correctly. If you're worried about these getting 
> removed we may be able to stash them in `compiler.used`, that shouldn't 
> impede the necessary constant propagation.
> 
> Side note, OpenCL seems to optimize these out without `-disable-llvm-optzns` 
> while HIP will not. Does OpenCL use some mandatory passes to ensure that 
> these control variables get handled? This method of using control constants 
> in general is somewhat problematic as it hides invalid code behind some 
> mand

[PATCH] D122255: Meta directive runtime support

2022-08-31 Thread Abid via Phabricator via cfe-commits
abidmalikwaterloo marked 2 inline comments as done.
abidmalikwaterloo added a comment.

I will work on the patch in parts. I am planning to submit taking care of 
comments except for comments for SemaOpenMP and code generation.




Comment at: clang/lib/AST/OpenMPClause.cpp:1679
+  OS << ": ";
+}
+

jdoerfert wrote:
> abidmalikwaterloo wrote:
> > jdoerfert wrote:
> > > I'm assuming we already have a printer for trait selectors, no? Doesn't 
> > > `OMPTraitInfo::print` do this already and actually handle scores?
> > Looked into the function. `OMPTraitInfo::print` can be used. The function 
> > needs to be extended as well to take the other traits as well.
> > The function needs to be extended as well to take the other traits as well.
> 
> What traits are not handled there?
No. It handles everything in terms of printing. I have updated the code. Will 
upload it as well.



Comment at: clang/lib/Parse/ParseOpenMP.cpp:2607
+   // Parsing the OpenMP region which will take the
+   // metadirective
+   

jdoerfert wrote:
> This seems to be copied from somewhere. It is unclear why a metadirective 
> needs to have an associated openmp region. 
correcrted.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:7439
+  }
+}
+

jdoerfert wrote:
> abidmalikwaterloo wrote:
> > abidmalikwaterloo wrote:
> > > jdoerfert wrote:
> > > > Why does this perform partial trait matching? We should have code for 
> > > > this. Also, the logic for device_arch and vendor (which is most what 
> > > > there is), is not what we want. Reuse the existing matching logic 
> > > > instead.
> > > Ok. What do you mean by `existing matching logic`? 
> > @jdoerfert I agree that the implementation is incomplete in terms of trait 
> > matching. It can be completed. However, I am not clear about your comments 
> > about the `existing matching logic`.  I checked OMPContext.CPP and other 
> > files. There are functions that can be used to match the traits. But, I 
> > could not find any existing logic that can be used here.
> I mean `getBestVariantMatchForContext` and similar functions in 
> `llvm/lib/Frontend/OpenMP/OMPContext.cpp`.
> 
> 
OK.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122255

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


[PATCH] D132727: [clang][Interp] Implement array initializers and subscript expressions

2022-08-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 456953.
tbaeder marked an inline comment as done.

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

https://reviews.llvm.org/D132727

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/ByteCodeStmtGen.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/Pointer.cpp
  clang/lib/AST/Interp/Program.cpp
  clang/test/AST/Interp/arrays.cpp

Index: clang/test/AST/Interp/arrays.cpp
===
--- clang/test/AST/Interp/arrays.cpp
+++ clang/test/AST/Interp/arrays.cpp
@@ -1,13 +1,85 @@
 // RUN: %clang_cc1 -fexperimental-new-constant-interpreter -verify %s
 // RUN: %clang_cc1 -verify=ref %s
 
+constexpr int m = 3;
+constexpr const int *foo[][5] = {
+  {nullptr, &m, nullptr, nullptr, nullptr},
+  {nullptr, nullptr, &m, nullptr, nullptr},
+  {nullptr, nullptr, nullptr, &m, nullptr},
+};
+
+static_assert(foo[0][0] == nullptr, "");
+static_assert(foo[0][1] == &m, "");
+static_assert(foo[0][2] == nullptr, "");
+static_assert(foo[0][3] == nullptr, "");
+static_assert(foo[0][4] == nullptr, "");
+static_assert(foo[1][0] == nullptr, "");
+static_assert(foo[1][1] == nullptr, "");
+static_assert(foo[1][2] == &m, "");
+static_assert(foo[1][3] == nullptr, "");
+static_assert(foo[1][4] == nullptr, "");
+static_assert(foo[2][0] == nullptr, "");
+static_assert(foo[2][1] == nullptr, "");
+static_assert(foo[2][2] == nullptr, "");
+static_assert(foo[2][3] == &m, "");
+static_assert(foo[2][4] == nullptr, "");
+
+
+/// A init list for a primitive value.
+constexpr int f{5};
+static_assert(f == 5, "");
+
+
+constexpr int getElement(int i) {
+  int values[] = {1, 4, 9, 16, 25, 36};
+  return values[i];
+}
+static_assert(getElement(1) == 4, "");
+static_assert(getElement(5) == 36, "");
+
+
+template
+constexpr T getElementOf(T* array, int i) {
+  return array[i];
+}
+static_assert(getElementOf(foo[0], 1) == &m, "");
+
 
-/// expected-no-diagnostics
-/// ref-no-diagnostics
+constexpr int data[] = {5, 4, 3, 2, 1};
+static_assert(data[0] == 4, ""); // expected-error{{failed}} \
+ // expected-note{{5 == 4}} \
+ // ref-error{{failed}} \
+ // ref-note{{5 == 4}}
+
+
+constexpr int dynamic[] = {
+  f, 3, 2 + 5, data[3], *getElementOf(foo[2], 3)
+};
+static_assert(dynamic[0] == f, "");
+static_assert(dynamic[3] == 2, "");
+
+
+constexpr int dependent[4] = {
+  0, 1, dependent[0], dependent[1]
+};
+static_assert(dependent[2] == dependent[0], "");
+static_assert(dependent[3] == dependent[1], "");
 
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wc99-extensions"
 #pragma clang diagnostic ignored "-Winitializer-overrides"
+constexpr int DI[] = {
+  [0] = 10,
+  [1] = 20,
+  30,
+  40,
+  [1] = 50
+};
+static_assert(DI[0] == 10, "");
+static_assert(DI[1] == 50, "");
+static_assert(DI[2] == 30, "");
+static_assert(DI[3] == 40, "");
+
 /// FIXME: The example below tests ImplicitValueInitExprs, but we can't
 ///   currently evaluate other parts of it.
 #if 0
Index: clang/lib/AST/Interp/Program.cpp
===
--- clang/lib/AST/Interp/Program.cpp
+++ clang/lib/AST/Interp/Program.cpp
@@ -334,14 +334,15 @@
   } else {
 // Arrays of composites. In this case, the array is a list of pointers,
 // followed by the actual elements.
-Descriptor *Desc =
+Descriptor *ElemDesc =
 createDescriptor(D, ElemTy.getTypePtr(), IsConst, IsTemporary);
-if (!Desc)
+if (!ElemDesc)
   return nullptr;
-InterpSize ElemSize = Desc->getAllocSize() + sizeof(InlineDescriptor);
+InterpSize ElemSize =
+ElemDesc->getAllocSize() + sizeof(InlineDescriptor);
 if (std::numeric_limits::max() / ElemSize <= NumElems)
   return {};
-return allocateDescriptor(D, Desc, NumElems, IsConst, IsTemporary,
+return allocateDescriptor(D, ElemDesc, NumElems, IsConst, IsTemporary,
   IsMutable);
   }
 }
Index: clang/lib/AST/Interp/Pointer.cpp
===
--- clang/lib/AST/Interp/Pointer.cpp
+++ clang/lib/AST/Interp/Pointer.cpp
@@ -106,7 +106,7 @@
 
   // Build the path into the object.
   Pointer Ptr = *this;
-  while (Ptr.isField()) {
+  while (Ptr.isField() || Ptr.isArrayElement()) {
 if (Ptr.isArrayElement()) {
   Path.push_back(APValue::LValuePathEntry::ArrayIndex(Ptr.getIndex()));
   Ptr = Ptr.getArray();
@@ -154,7 +154,8 @@
 void Pointer::initialize() const {
   assert(Pointee && "Cannot initialize null pointer");
   Descriptor *Desc = getFieldDesc();
-  if (Desc->isPrimitiveArray()) {
+
+  if (Desc->isArray() || Desc->isPrimitiveArray()) {
 if (!Pointee->IsStatic) {
   // Primitive arra

[PATCH] D132801: [driver] Additional ignoring of module-map related flags, if modules are disabled

2022-08-31 Thread Argyrios Kyrtzidis via Phabricator via cfe-commits
akyrtzi added a comment.

In D132801#3760014 , @rsmith wrote:

> This doesn't look right to me -- we still use module maps when modules are 
> disabled to enforce layering checking, and when 
> `-fmodules-local-submodule-visibility` is enabled but `-fmodules` is disabled 
> we'll use them to provide modular semantics without pre-building modules. I'm 
> going to revert.

Sorry, I wasn't aware of that. Could `-fmodule-map-file=` be pruned out when 
`-fmodules-local-submodule-visibility` or `-fmodules-decluse` are not enabled?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132801

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


[PATCH] D133029: [Sema] Allow to diagnose the references to std::vector with incomplete T

2022-08-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
Herald added a project: All.
ilya-biryukov requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Add a warning `-Waccess-vector-incomplete-member`.

Inspired by recent changes to libc++ that make some uses actually fail
in C++20 mode, e.g. calls to `size()` started producing errors in cases
that were fine before.

These accesses are explicitly forbidden by the standard, but end up
working in existing implementations.

The warning is disabled by default, it is intended to be enabled for
finding instances of the code that can potentially break. We intend to
use it to find candidates for cleanup before the C++20 transition.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133029

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/warn-vector-of-incomplete-access.cpp


Index: clang/test/Sema/warn-vector-of-incomplete-access.cpp
===
--- /dev/null
+++ clang/test/Sema/warn-vector-of-incomplete-access.cpp
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 %s -verify -Waccess-vector-incomplete-member
+
+namespace std {
+template  struct vector {
+  using size_type = unsigned;
+
+  vector();
+  ~vector();
+
+  unsigned size();
+};
+}
+
+struct Incomplete;
+std::vector::size_type x; // expected-warning{{ISO C++ forbids 
access to member 'size_type' of 'std::vector' with incomplete type 
'Incomplete'}}
+std::vector y; // expected-warning{{ISO C++ forbids access to 
member 'vector' of 'std::vector' with incomplete type 'Incomplete'}} \
+  expected-warning{{ISO C++ forbids access to 
member '~vector' of 'std::vector' with incomplete type 'Incomplete'}} \
+
+// Some tricky usages that should be ok.
+struct Recursive {
+  std::vector x;
+};
+
+struct WithSubtype {
+  struct Subtype {
+std::vector x;
+  };
+  Subtype y;
+  unsigned count = y.x.size();
+
+};
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -206,6 +206,24 @@
   }
 }
 
+namespace {
+bool IsStdVector(Decl *D) {
+  auto *ND = dyn_cast_or_null(D);
+  auto *Name = ND ? ND->getIdentifier() : nullptr;
+  auto *Parent = ND ? ND->getDeclContext() : nullptr;
+  return Name && Name->isStr("vector") && Parent && Parent->isStdNamespace();
+}
+
+QualType ExtractStdVectorTemplateArg(Decl* D) {
+  auto *SD = dyn_cast(D);
+  if (!SD) return QualType();
+  if (SD->getTemplateArgs().size() < 1) return QualType();
+  auto &A = SD->getTemplateArgs().get(0);
+  if (A.getKind() != TemplateArgument::Type) return QualType();
+  return A.getAsType();
+}
+} // namespace
+
 /// Determine whether the use of this declaration is valid, and
 /// emit any corresponding diagnostics.
 ///
@@ -392,6 +410,18 @@
 return true;
   }
 
+  // Diagnose access to members of `vector` with incomplete `T`.
+  // [vector.overview]p4
+  // An incomplete type T may be used when instantiating vector if the 
allocator meets the allocator completeness
+  // requirements (16.5.3.5.1). T shall be complete before any member of the 
resulting specialization of vector is
+  // referenced.
+  if (auto *Parent = dyn_cast(D->getDeclContext()); IsStdVector(Parent)) 
{
+auto T = ExtractStdVectorTemplateArg(Parent);
+if (!T.isNull() && T->isIncompleteType())
+  Diag(Loc, diag::warn_access_member_of_vector_of_incomplete_type)
+  << D << T;
+  }
+
   return false;
 }
 
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -8743,6 +8743,10 @@
 def note_inequality_comparison_to_or_assign : Note<
   "use '|=' to turn this inequality comparison into an or-assignment">;
 
+def warn_access_member_of_vector_of_incomplete_type : Warning<
+  "ISO C++ forbids access to member %0 of 'std::vector' with incomplete type 
%1">,
+  InGroup>, DefaultIgnore;
+
 def err_incomplete_type_used_in_type_trait_expr : Error<
   "incomplete type %0 used in type trait expression">;
 


Index: clang/test/Sema/warn-vector-of-incomplete-access.cpp
===
--- /dev/null
+++ clang/test/Sema/warn-vector-of-incomplete-access.cpp
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 %s -verify -Waccess-vector-incomplete-member
+
+namespace std {
+template  struct vector {
+  using size_type = unsigned;
+
+  vector();
+  ~vector();
+
+  unsigned size();
+};
+}
+
+struct Incomplete;
+std::vector::size_type x; // expected-warning{{ISO C++ forbids access to member 'size_type' of 'std::vector' with incomplete type 'Incomplete'}}
+std::vector y; // expected-warning{{ISO C++ forbids access to member 'vector' of 'std::vector' with incomplete type 'Incomplete'}} \
+ 

[PATCH] D132944: [clang] cleanup -fstrict-flex-arrays implementation

2022-08-31 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 456971.
serge-sans-paille edited the summary of this revision.

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

https://reviews.llvm.org/D132944

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/bounds-checking-fam.c
  clang/test/CodeGen/object-size-flex-array.c

Index: clang/test/CodeGen/object-size-flex-array.c
===
--- clang/test/CodeGen/object-size-flex-array.c
+++ clang/test/CodeGen/object-size-flex-array.c
@@ -24,7 +24,7 @@
   double c[2];
 } foo2_t;
 
-// CHECK-LABEL: @bar
+// CHECK-LABEL: @bar(
 unsigned bar(foo_t *f) {
   // CHECK-STRICT-0: ret i32 %
   // CHECK-STRICT-1: ret i32 %
@@ -32,7 +32,7 @@
   return OBJECT_SIZE_BUILTIN(f->c, 1);
 }
 
-// CHECK-LABEL: @bar0
+// CHECK-LABEL: @bar0(
 unsigned bar0(foo0_t *f) {
   // CHECK-STRICT-0: ret i32 %
   // CHECK-STRICT-1: ret i32 %
@@ -40,7 +40,7 @@
   return OBJECT_SIZE_BUILTIN(f->c, 1);
 }
 
-// CHECK-LABEL: @bar1
+// CHECK-LABEL: @bar1(
 unsigned bar1(foo1_t *f) {
   // CHECK-STRICT-0: ret i32 %
   // CHECK-STRICT-1: ret i32 %
@@ -48,7 +48,7 @@
   return OBJECT_SIZE_BUILTIN(f->c, 1);
 }
 
-// CHECK-LABEL: @bar2
+// CHECK-LABEL: @bar2(
 unsigned bar2(foo2_t *f) {
   // CHECK-STRICT-0: ret i32 %
   // CHECK-STRICT-1: ret i32 16
@@ -73,7 +73,7 @@
   float f;
 } foofoo2_t;
 
-// CHECK-LABEL: @babar0
+// CHECK-LABEL: @babar0(
 unsigned babar0(foofoo0_t *f) {
   // CHECK-STRICT-0: ret i32 0
   // CHECK-STRICT-1: ret i32 0
@@ -81,7 +81,7 @@
   return OBJECT_SIZE_BUILTIN(f->c, 1);
 }
 
-// CHECK-LABEL: @babar1
+// CHECK-LABEL: @babar1(
 unsigned babar1(foofoo1_t *f) {
   // CHECK-STRICT-0: ret i32 8
   // CHECK-STRICT-1: ret i32 8
@@ -89,7 +89,7 @@
   return OBJECT_SIZE_BUILTIN(f->c, 1);
 }
 
-// CHECK-LABEL: @babar2
+// CHECK-LABEL: @babar2(
 unsigned babar2(foofoo2_t *f) {
   // CHECK-STRICT-0: ret i32 16
   // CHECK-STRICT-1: ret i32 16
Index: clang/test/CodeGen/bounds-checking-fam.c
===
--- clang/test/CodeGen/bounds-checking-fam.c
+++ clang/test/CodeGen/bounds-checking-fam.c
@@ -35,6 +35,51 @@
   return p->a[i] + (p->a)[i];
 }
 
+union uZero {
+  int a[0];
+};
+union uOne {
+  int a[1];
+};
+union uTwo {
+  int a[2];
+};
+union uThree {
+  int a[3];
+};
+
+// CHECK-LABEL: define {{.*}} @{{.*}}test_uzero{{.*}}(
+int test_uzero(union uZero *p, int i) {
+  // CHECK-STRICT-0-NOT: @__ubsan
+  // CHECK-STRICT-1-NOT: @__ubsan
+  // CHECK-STRICT-2-NOT: @__ubsan
+  return p->a[i] + (p->a)[i];
+}
+
+// CHECK-LABEL: define {{.*}} @{{.*}}test_uone{{.*}}(
+int test_uone(union uOne *p, int i) {
+  // CHECK-STRICT-0-NOT: @__ubsan
+  // CHECK-STRICT-1-NOT: @__ubsan
+  // CHECK-STRICT-2: @__ubsan
+  return p->a[i] + (p->a)[i];
+}
+
+// CHECK-LABEL: define {{.*}} @{{.*}}test_utwo{{.*}}(
+int test_utwo(union uTwo *p, int i) {
+  // CHECK-STRICT-0: @__ubsan
+  // CHECK-STRICT-1: @__ubsan
+  // CHECK-STRICT-2: @__ubsan
+  return p->a[i] + (p->a)[i];
+}
+
+// CHECK-LABEL: define {{.*}} @{{.*}}test_uthree{{.*}}(
+int test_uthree(union uThree *p, int i) {
+  // CHECK-STRICT-0: @__ubsan
+  // CHECK-STRICT-1: @__ubsan
+  // CHECK-STRICT-2: @__ubsan
+  return p->a[i] + (p->a)[i];
+}
+
 // CHECK-LABEL: define {{.*}} @{{.*}}test_three{{.*}}(
 int test_three(struct Three *p, int i) {
   // CHECK-STRICT-0: call void @__ubsan_handle_out_of_bounds_abort(
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -15849,16 +15849,10 @@
   if (!ND)
 return false;
 
-  if (StrictFlexArraysLevel >= 2 && Size != 0)
-return false;
-
-  if (StrictFlexArraysLevel == 1 && Size.uge(2))
-return false;
-
   // FIXME: While the default -fstrict-flex-arrays=0 permits Size>1 trailing
   // arrays to be treated as flexible-array-members, we still emit diagnostics
   // as if they are not. Pending further discussion...
-  if (StrictFlexArraysLevel == 0 && Size != 1)
+  if (StrictFlexArraysLevel >= 2 || Size.uge(2))
 return false;
 
   const FieldDecl *FD = dyn_cast(ND);
@@ -16026,8 +16020,8 @@
 if (BaseType->isIncompleteType())
   return;
 
-// FIXME: this check should belong to the IsTailPaddedMemberArray call
-// below.
+// FIXME: this check should be used to set IsUnboundedArray from the
+// beginning.
 llvm::APInt size = ArrayTy->getSize();
 if (!size.isStrictlyPositive())
   return;
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -906,10 +906,8 @@
 if (const auto *FD = dyn_cast(ME->getMemberDecl())) {
   // FIXME: Sema doesn't treat a T[1] union member as a flexible array
   // member, only a T[0] or T[] member 

[PATCH] D133029: [Sema] Allow to diagnose the references to std::vector with incomplete T

2022-08-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

This warning might be a little verbose and pedantic for Clang, but I still 
wanted to share the code.
I would be more comfortable doing this a `clang-tidy` check, but I don't think 
there is an easy way to write it outside `Sema` and `Sema` is not readily 
available for `clang-tidy`.

I will try to find ways to patch this in locally for my use-case, but also 
happy to submit this if others think it is useful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133029

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


[PATCH] D131879: [clang][analyzer] Errno modeling code refactor (NFC).

2022-08-31 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
Herald added a subscriber: rnkovacs.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131879

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


[PATCH] D132147: [clang][dataflow] Refactor `TestingSupport.h`

2022-08-31 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456978.
wyt added a comment.
Herald added subscribers: llvm-commits, mgrang, mgorny.
Herald added a project: LLVM.

Remove use of designated initializers which are only allowed on C++20. Instead, 
introduce a constructor that sets required fields, and `withFieldName` methods 
that sets optional fields when constructing an `AnalysisInputs` struct.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132147

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
  llvm/include/llvm/ADT/StringMapEntry.h
  llvm/include/llvm/Testing/ADT/StringMap.h
  llvm/include/llvm/Testing/ADT/StringMapEntry.h
  llvm/unittests/Testing/ADT/CMakeLists.txt
  llvm/unittests/Testing/ADT/StringMapEntryTest.cpp
  llvm/unittests/Testing/ADT/StringMapTest.cpp
  llvm/unittests/Testing/CMakeLists.txt
  utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
  utils/bazel/llvm-project-overlay/llvm/unittests/BUILD.bazel

Index: utils/bazel/llvm-project-overlay/llvm/unittests/BUILD.bazel
===
--- utils/bazel/llvm-project-overlay/llvm/unittests/BUILD.bazel
+++ utils/bazel/llvm-project-overlay/llvm/unittests/BUILD.bazel
@@ -644,6 +644,23 @@
 ],
 )
 
+cc_test(
+name = "testing_adt_tests",
+size = "small",
+srcs = glob(
+[
+"Testing/ADT/*.cpp",
+],
+allow_empty = False,
+),
+deps = [
+"//llvm:Support",
+"//llvm:TestingADT",
+"//llvm:gtest",
+"//llvm:gtest_main",
+],
+)
+
 cc_test(
 name = "transforms_tests",
 size = "small",
Index: utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
===
--- utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
+++ utils/bazel/llvm-project-overlay/llvm/BUILD.bazel
@@ -4181,6 +4181,19 @@
 srcs = ["utils/lit/lit.py"] + glob(["utils/lit/lit/**/*.py"]),
 )
 
+cc_library(
+name = "TestingADT",
+testonly = True,
+hdrs = glob([
+"include/llvm/Testing/ADT/*.h",
+]),
+copts = llvm_copts,
+deps = [
+":Support",
+":gmock",
+],
+)
+
 cc_library(
 name = "TestingSupport",
 testonly = True,
Index: llvm/unittests/Testing/CMakeLists.txt
===
--- llvm/unittests/Testing/CMakeLists.txt
+++ llvm/unittests/Testing/CMakeLists.txt
@@ -1 +1,2 @@
+add_subdirectory(ADT)
 add_subdirectory(Support)
Index: llvm/unittests/Testing/ADT/StringMapTest.cpp
===
--- /dev/null
+++ llvm/unittests/Testing/ADT/StringMapTest.cpp
@@ -0,0 +1,55 @@
+//===- StringMapTest.cpp --===//
+//
+// 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 "llvm/Testing/ADT/StringMap.h"
+#include "llvm/ADT/StringMap.h"
+
+#include "gtest/gtest.h"
+#include 
+
+namespace llvm {
+namespace {
+
+TEST(StringMapTest, StringMapStream) {
+  std::ostringstream OS;
+  StringMap Map;
+  Map["A"] = 42;
+  Map["Z"] = 35;
+  Map["B"] = 7;
+  OS << Map;
+
+  EXPECT_EQ(OS.str(), R"({
+{"A": 42},
+{"B": 7},
+{"Z": 35},
+})");
+}
+
+TEST(StringMapTest, NestedStringMapStream) {
+  std::ostringstream OS;
+  StringMap> Map;
+  Map["Z"];
+  Map["A"]["Apple"] = 5;
+  Map["B"]["Bee"] = 3;
+  Map["A"]["Axe"] = 3;
+  OS << Map;
+
+  EXPECT_EQ(OS.str(), R"({
+{"A": {
+{"Apple": 5},
+{"Axe": 3},
+}},
+{"B": {
+{"Bee": 3},
+}},
+{"Z": { }},
+})");
+}
+
+} // namespace
+} // namespace llvm
Index: llvm/unittests/Testing/ADT/StringMapEntryTest.cpp
===
--- /dev/null
+++ llvm/unittests/Testing/ADT/StringMapEntryTest.cpp
@@ -0,0 +1,88 @@
+//===- StringMapEntryTest.cpp -===//
+//
+// 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 "llvm/Testing/ADT/StringMapEntry.h"
+#include "llvm/ADT/StringMap.h"
+
+#include "gtest/gtest.h"
+#include 
+
+namespace llvm {
+namespace {
+
+using testing::Gt;
+using testing::Matcher;
+using testing::StrCaseEq;
+using testing::StringMatchResultListener;
+using testing::UnorderedElementsAre;
+
+template  std::string Desc

[PATCH] D133009: [libclang] Fix conversion from `StringRef` to `CXString`

2022-08-31 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/test/Index/comment-lots-of-unknown-commands.c:3
 
+// XFAIL: *
+

egorzhdan wrote:
> This test was never properly passing. Because of the bug in string 
> conversion, the printed comments contained the entire source file and not 
> just the comments' text, which was enough to cause `// CHECK`-s in the test 
> to succeed.
> ```
> // CHECK: (CXComment_InlineCommand CommandName=[tel] RenderNormal 
> HasTrailingNewline)
> // CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> HasTrailingNewline))
> // CHECK:   (CXComment_VerbatimLine 
> Text=[\n@Lo\n@il\n@tle\n@axt\n@ba\n@ust\n@ac\n@tpe\n@tpl\n@ctG\n@ru\n@m\n@tG\n@it\n@rh\n@G\n@rpc\n@el\n@er\n@w\n@eo\n@tx\n@oo\n@dD\n@dD\n*/\nvoid
>  f();\n\n// CHECK:  CommentAST=[\n// CHECK:(CXComment_FullComment\n// 
> CHECK:   (CXComment_Paragraph\n// CHECK:  ...
> ```
Please update the test to pass then. Here's the diff:

```
diff --git a/clang/test/Index/comment-lots-of-unknown-commands.c 
b/clang/test/Index/comment-lots-of-unknown-commands.c
index 41a03d394488..e1adcc150b1e 100644
--- a/clang/test/Index/comment-lots-of-unknown-commands.c
+++ b/clang/test/Index/comment-lots-of-unknown-commands.c
@@ -1,6 +1,5 @@
 // RUN: c-index-test -test-load-source-reparse 1 local %s | FileCheck %s

-// XFAIL: *

 // See PR 21254. We had too few bits to encode command IDs so if you created
 // enough of them the ID codes would wrap around. This test creates commands up
@@ -183,7 +182,7 @@ void f();
 // CHECK: (CXComment_InlineCommand CommandName=[ei] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[oun] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[ou] RenderNormal 
HasTrailingNewline)
-// CHECK: (CXComment_InlineCommand CommandName=[nl] RenderNormal 
HasTrailingNewline)
+// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[ien] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[fr] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[en] RenderNormal 
HasTrailingNewline)
@@ -204,7 +203,7 @@ void f();
 // CHECK: (CXComment_InlineCommand CommandName=[fro] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[ast] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[ae] RenderNormal 
HasTrailingNewline)
-// CHECK: (CXComment_InlineCommand CommandName=[nN] RenderNormal 
HasTrailingNewline)
+// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[pc] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[tae] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[ws] RenderNormal 
HasTrailingNewline)
@@ -268,10 +267,8 @@ void f();
 // CHECK: (CXComment_InlineCommand CommandName=[an] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[de] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[tel] RenderNormal 
HasTrailingNewline)
-// CHECK: (CXComment_InlineCommand CommandName=[nd] RenderNormal 
HasTrailingNewline)
-// CHECK: (CXComment_InlineCommand CommandName=[dic] RenderNormal 
HasTrailingNewline)
+// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[Lo] RenderNormal 
HasTrailingNewline)
-// CHECK: (CXComment_InlineCommand CommandName=[il] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[tle] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[axt] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[ba] RenderNormal 
HasTrailingNewline)
@@ -283,7 +280,6 @@ void f();
 // CHECK: (CXComment_InlineCommand CommandName=[ru] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[m] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[tG] RenderNormal 
HasTrailingNewline)
-// CHECK: (CXComment_InlineCommand CommandName=[it] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[rh] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[G] RenderNormal 
HasTrailingNewline)
 // CHECK: (CXComment_InlineCommand CommandName=[rpc] RenderNormal 
HasTrailingNewline)
```



Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D1

[PATCH] D132944: [clang] cleanup -fstrict-flex-arrays implementation

2022-08-31 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

  #include 
  #include 
  
  
  consteval int fn(std::source_location sl = std::source_location::current()) {
return sl.line();
  }
  
  consteval int fn2(int line = fn()) {
return line;
  }
  
  int main() {
printf("fn=%d fn2=%d\n", fn(), fn2());
  }

I believe this should print `fn=14 fn2=14`. I don't see how we can get that by 
special-casing calls to `std::source_location::current`, and indeed, with this 
version of the patch, the program instead prints `fn=14 fn2=9`.


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

https://reviews.llvm.org/D132944

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


[PATCH] D129488: [Sema] Delay evaluation of std::source_location::current() in default arguments

2022-08-31 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

  #include 
  #include 
  
  
  consteval int fn(std::source_location sl = std::source_location::current()) {
return sl.line();
  }
  
  consteval int fn2(int line = fn()) {
return line;
  }
  
  int main() {
printf("fn=%d fn2=%d\n", fn(), fn2());
  }

I believe this should print `fn=14 fn2=14`. I don't see how we can get that by 
special-casing calls to `std::source_location::current`, and indeed, with this 
version of the patch, the program instead prints `fn=14 fn2=9`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129488

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


[PATCH] D133029: [Sema] Allow to diagnose the references to std::vector with incomplete T

2022-08-31 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added a comment.

In D133029#3761344 , @ilya-biryukov 
wrote:

> [...] I don't think there is an easy way to write it outside `Sema` and 
> `Sema` is not readily available for `clang-tidy`.

What information is missing, exactly?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133029

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


[PATCH] D133009: [libclang] Fix conversion from `StringRef` to `CXString`

2022-08-31 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan added inline comments.



Comment at: clang/test/Index/comment-lots-of-unknown-commands.c:3
 
+// XFAIL: *
+

gribozavr2 wrote:
> egorzhdan wrote:
> > This test was never properly passing. Because of the bug in string 
> > conversion, the printed comments contained the entire source file and not 
> > just the comments' text, which was enough to cause `// CHECK`-s in the test 
> > to succeed.
> > ```
> > // CHECK: (CXComment_InlineCommand CommandName=[tel] RenderNormal 
> > HasTrailingNewline)
> > // CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> > HasTrailingNewline))
> > // CHECK:   (CXComment_VerbatimLine 
> > Text=[\n@Lo\n@il\n@tle\n@axt\n@ba\n@ust\n@ac\n@tpe\n@tpl\n@ctG\n@ru\n@m\n@tG\n@it\n@rh\n@G\n@rpc\n@el\n@er\n@w\n@eo\n@tx\n@oo\n@dD\n@dD\n*/\nvoid
> >  f();\n\n// CHECK:  CommentAST=[\n// CHECK:(CXComment_FullComment\n// 
> > CHECK:   (CXComment_Paragraph\n// CHECK:  ...
> > ```
> Please update the test to pass then. Here's the diff:
> 
> ```
> diff --git a/clang/test/Index/comment-lots-of-unknown-commands.c 
> b/clang/test/Index/comment-lots-of-unknown-commands.c
> index 41a03d394488..e1adcc150b1e 100644
> --- a/clang/test/Index/comment-lots-of-unknown-commands.c
> +++ b/clang/test/Index/comment-lots-of-unknown-commands.c
> @@ -1,6 +1,5 @@
>  // RUN: c-index-test -test-load-source-reparse 1 local %s | FileCheck %s
> 
> -// XFAIL: *
> 
>  // See PR 21254. We had too few bits to encode command IDs so if you created
>  // enough of them the ID codes would wrap around. This test creates commands 
> up
> @@ -183,7 +182,7 @@ void f();
>  // CHECK: (CXComment_InlineCommand CommandName=[ei] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[oun] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[ou] RenderNormal 
> HasTrailingNewline)
> -// CHECK: (CXComment_InlineCommand CommandName=[nl] RenderNormal 
> HasTrailingNewline)
> +// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[ien] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[fr] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[en] RenderNormal 
> HasTrailingNewline)
> @@ -204,7 +203,7 @@ void f();
>  // CHECK: (CXComment_InlineCommand CommandName=[fro] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[ast] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[ae] RenderNormal 
> HasTrailingNewline)
> -// CHECK: (CXComment_InlineCommand CommandName=[nN] RenderNormal 
> HasTrailingNewline)
> +// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[pc] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[tae] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[ws] RenderNormal 
> HasTrailingNewline)
> @@ -268,10 +267,8 @@ void f();
>  // CHECK: (CXComment_InlineCommand CommandName=[an] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[de] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[tel] RenderNormal 
> HasTrailingNewline)
> -// CHECK: (CXComment_InlineCommand CommandName=[nd] RenderNormal 
> HasTrailingNewline)
> -// CHECK: (CXComment_InlineCommand CommandName=[dic] RenderNormal 
> HasTrailingNewline)
> +// CHECK: (CXComment_InlineCommand CommandName=[n] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[Lo] RenderNormal 
> HasTrailingNewline)
> -// CHECK: (CXComment_InlineCommand CommandName=[il] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[tle] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[axt] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[ba] RenderNormal 
> HasTrailingNewline)
> @@ -283,7 +280,6 @@ void f();
>  // CHECK: (CXComment_InlineCommand CommandName=[ru] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[m] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[tG] RenderNormal 
> HasTrailingNewline)
> -// CHECK: (CXComment_InlineCommand CommandName=[it] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[rh] RenderNormal 
> HasTrailingNewline)
>  // CHECK: (CXComment_InlineCommand CommandName=[G] RenderNormal 

[PATCH] D132147: [clang][dataflow] Refactor `TestingSupport.h`

2022-08-31 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456980.
wyt added a comment.

This is a re-update of a previous update which uploaded the wrong diff.
Remove use of designated initializers which are only allowed on C++20. Instead, 
introduce a constructor that sets required fields, and withFieldName methods 
that sets optional fields when constructing an AnalysisInputs struct.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132147

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -1234,49 +1234,48 @@
   template 
   T Make();
 )");
-const tooling::FileContentMappings FileContents(Headers.begin(),
-Headers.end());
 UncheckedOptionalAccessModelOptions Options{
 /*IgnoreSmartPointerDereference=*/true};
 std::vector Diagnostics;
 llvm::Error Error = checkDataflow(
-SourceCode, FuncMatcher,
-[Options](ASTContext &Ctx, Environment &) {
-  return UncheckedOptionalAccessModel(Ctx, Options);
-},
-[&Diagnostics, Diagnoser = UncheckedOptionalAccessDiagnoser(Options)](
-ASTContext &Ctx, const CFGStmt &Stmt,
-const TypeErasedDataflowAnalysisState &State) mutable {
-  auto StmtDiagnostics =
-  Diagnoser.diagnose(Ctx, Stmt.getStmt(), State.Env);
-  llvm::move(StmtDiagnostics, std::back_inserter(Diagnostics));
-},
-[&Diagnostics](AnalysisData AnalysisData) {
-  auto &SrcMgr = AnalysisData.ASTCtx.getSourceManager();
-
+AnalysisInputs(
+SourceCode, std::move(FuncMatcher),
+[Options](ASTContext &Ctx, Environment &) {
+  return UncheckedOptionalAccessModel(Ctx, Options);
+})
+.withPostVisitCFG(
+[&Diagnostics,
+ Diagnoser = UncheckedOptionalAccessDiagnoser(Options)](
+ASTContext &Ctx, const CFGElement &Elt,
+const TypeErasedDataflowAnalysisState &State) mutable {
+  auto Stmt = Elt.getAs();
+  if (!Stmt) {
+return;
+  }
+  auto StmtDiagnostics =
+  Diagnoser.diagnose(Ctx, Stmt->getStmt(), State.Env);
+  llvm::move(StmtDiagnostics, std::back_inserter(Diagnostics));
+})
+.withASTBuildArgs(
+{"-fsyntax-only", "-std=c++17", "-Wno-undefined-inline"})
+.withASTBuildVirtualMappedFiles(
+tooling::FileContentMappings(Headers.begin(), Headers.end())),
+/*VerifyResults=*/[&Diagnostics](
+  const llvm::DenseMap
+  &Annotations,
+  const AnalysisOutputs &AO) {
   llvm::DenseSet AnnotationLines;
-  for (const auto &Pair : AnalysisData.Annotations) {
-auto *Stmt = Pair.getFirst();
-AnnotationLines.insert(
-SrcMgr.getPresumedLineNumber(Stmt->getBeginLoc()));
-// We add both the begin and end locations, so that if the
-// statement spans multiple lines then the test will fail.
-//
-// FIXME: Going forward, we should change this to instead just
-// get the single line number from the annotation itself, rather
-// than looking at the statement it's attached to.
-AnnotationLines.insert(
-SrcMgr.getPresumedLineNumber(Stmt->getEndLoc()));
+  for (const auto &[Line, _] : Annotations) {
+AnnotationLines.insert(Line);
   }
-
+  auto &SrcMgr = AO.ASTCtx.getSourceManager();
   llvm::DenseSet DiagnosticLines;
   for (SourceLocation &Loc : Diagnostics) {
 DiagnosticLines.insert(SrcMgr.getPresumedLineNumber(Loc));
   }
 
   EXPECT_THAT(DiagnosticLines, ContainerEq(AnnotationLines));
-},
-{"-fsyntax-only", "-std=c++17", "-Wno-undefined-inline"}, FileContents);
+});
 if (Error)
   FAIL() << llvm::toString(std::move(Error));
   }
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -56,47 +56,160 @@
 
 namespace test {
 
-// Returns assertions based

[PATCH] D133029: [Sema] Allow to diagnose the references to std::vector with incomplete T

2022-08-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

In D133029#3761400 , @gribozavr2 
wrote:

> In D133029#3761344 , @ilya-biryukov 
> wrote:
>
>> [...] I don't think there is an easy way to write it outside `Sema` and 
>> `Sema` is not readily available for `clang-tidy`.
>
> What information is missing, exactly?

Whether a type was incomplete at a certain point in code.

  struct IncompleteAtUse;
  std::vector x; // want to catch this, not visible in the 
resulting AST.
  struct IncompleteAtUse {};


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133029

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


[PATCH] D132944: [clang] cleanup -fstrict-flex-arrays implementation

2022-08-31 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

(please ignore the last comment, I sent it to the wrong review thread)


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

https://reviews.llvm.org/D132944

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


[PATCH] D132377: [clang][dataflow] Add `SetupTest` parameter for `AnalysisInputs`.

2022-08-31 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456982.
wyt added a comment.

Update according to change in parent patch to replace designated initialisers 
when constructing `AnalysisInputs`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132377

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h

Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -96,6 +96,11 @@
 
   /// Optional fields can be set with methods of the form `withFieldName(...)`.
   AnalysisInputs &&
+  withSetupTest(std::function Arg) && {
+SetupTest = std::move(Arg);
+return std::move(*this);
+  }
+  AnalysisInputs &&
   withPostVisitCFG(std::function
Arg) && {
@@ -120,6 +125,11 @@
   /// takes as argument the AST generated from the code being analyzed and the
   /// initial state from which the analysis starts with.
   std::function MakeAnalysis;
+  /// Optional. If provided, this function is executed immediately before
+  /// running the dataflow analysis to allow for additional setup. All fields in
+  /// the `AnalysisOutputs` argument will be initialized except for the
+  /// `BlockStates` field which is only computed later during the analysis.
+  std::function SetupTest = nullptr;
   /// Optional. If provided, this function is applied on each CFG element after
   /// the analysis has been run.
   std::function
-getAnnotationLinesAndContent(const AnalysisOutputs &AO);
-
-// FIXME: Return a string map instead of a vector of pairs.
-//
-/// Returns the analysis states at each annotated statement in `AO.Code`.
-template 
-llvm::Expected>>>
-getAnnotationStates(const AnalysisOutputs &AO) {
-  using StateT = DataflowAnalysisState;
-  // FIXME: Extend to annotations on non-statement constructs.
-  // Get annotated statements.
-  llvm::Expected>
-  MaybeStmtToAnnotations =
-  buildStatementToAnnotationMapping(AO.Target, AO.Code);
-  if (!MaybeStmtToAnnotations)
-return MaybeStmtToAnnotations.takeError();
-  auto &StmtToAnnotations = *MaybeStmtToAnnotations;
-
-  // Compute a map from statement annotations to the state computed
-  // for the program point immediately after the annotated statement.
-  std::vector> Results;
-  for (const CFGBlock *Block : AO.CFCtx.getCFG()) {
-// Skip blocks that were not evaluated.
-if (!AO.BlockStates[Block->getBlockID()])
-  continue;
-
-transferBlock(
-AO.CFCtx, AO.BlockStates, *Block, AO.InitEnv, AO.Analysis,
-[&Results,
- &StmtToAnnotations](const clang::CFGElement &Element,
- const TypeErasedDataflowAnalysisState &State) {
-  auto Stmt = Element.getAs();
-  if (!Stmt)
-return;
-  auto It = StmtToAnnotations.find(Stmt->getStmt());
-  if (It == StmtToAnnotations.end())
-return;
-  auto *Lattice =
-  llvm::any_cast(&State.Lattice.Value);
-  Results.emplace_back(It->second, StateT{*Lattice, State.Env});
-});
-  }
-
-  return Results;
-}
+buildLineToAnnotationMapping(SourceManager &SM,
+ llvm::Annotations AnnotatedCode);
 
 /// Runs dataflow specified from `AI.MakeAnalysis` and `AI.PostVisitCFG` on the
 /// body of the function that matches `AI.TargetFuncMatcher` in `AI.Code`.
@@ -200,9 +166,9 @@
 ///
 ///   `VerifyResults` must be provided.
 template 
-llvm::Error checkDataflow(
-AnalysisInputs AI,
-std::function VerifyResults) {
+llvm::Error
+checkDataflow(AnalysisInputs AI,
+  std::function VerifyResults) {
   // Build AST context from code.
   llvm::Annotations AnnotatedCode(AI.Code);
   auto Unit = tooling::buildASTFromCodeWithArgs(
@@ -236,7 +202,7 @@
 return MaybeCFCtx.takeError();
   auto &CFCtx = *MaybeCFCtx;
 
-  // Initialize states and run dataflow analysis.
+  // Initialize states for running dataflow analysis.
   DataflowAnalysisContext DACtx(std::make_unique());
   Environment InitEnv(DACtx, *Target);
   auto Analysis = AI.MakeAnalysis(Context, InitEnv);
@@ -251,19 +217,26 @@
 };
   }
 
-  // If successful, the run returns a mapping from block IDs to the
-  // post-analysis states for the CFG blocks that have been evaluated.
+  // Additional test setup.
+  AnalysisOutputs AO{AnnotatedCode, Context, Target, CFCtx,
+ Analysis,  InitEnv, {}};
+  if (AI.SetupTest) {
+if (auto Error = AI.SetupTest(AO))
+  return Error;
+  }
+
+  // If successful, the dataflow analysis returns a mapping from block IDs to
+  // the post-analysis states for the CFG blocks that have been evaluated.
   llvm::Expected>>
   MaybeBlockStates = runTypeErasedDataflowAnalysis(CFCtx, An

[PATCH] D129664: [Clang] Adjust extension warnings for delimited sequences

2022-08-31 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added a comment.

> While accepting all these inside of string and character literals in C and 
> C++20 and older is fine, accepting them inside of identifiers can change 
> meaning of valid programs.

Thank you for reporting this impact, @jakubjelinek! I'll copy you on an email 
to WG21 that discussed the impact, specifically with regard to the glibc header 
for which Joseph reported failures.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129664

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


[PATCH] D132763: [clang][dataflow] Use `StringMap` for storing analysis states at annotated points instead of `vector>`.

2022-08-31 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456983.
wyt added a comment.

Propagate change from parent patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132763

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -426,12 +426,12 @@
std::pair>>
Results,
ASTContext &ASTCtx) {
-ASSERT_THAT(Results, ElementsAre(Pair("p4", _), Pair("p3", _),
- Pair("p2", _), Pair("p1", _)));
-const Environment &Env1 = Results[3].second.Env;
-const Environment &Env2 = Results[2].second.Env;
-const Environment &Env3 = Results[1].second.Env;
-const Environment &Env4 = Results[0].second.Env;
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _),
+ Pair("p3", _), Pair("p4", _)));
+const Environment &Env1 = Results[0].second.Env;
+const Environment &Env2 = Results[1].second.Env;
+const Environment &Env3 = Results[2].second.Env;
+const Environment &Env4 = Results[3].second.Env;
 
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
@@ -579,10 +579,10 @@
  Results,
  ASTContext &ASTCtx) {
 ASSERT_THAT(Results,
-ElementsAre(Pair("p3", _), Pair("p2", _), Pair("p1", _)));
-const Environment &Env1 = Results[2].second.Env;
+ElementsAre(Pair("p1", _), Pair("p2", _), Pair("p3", _)));
+const Environment &Env1 = Results[0].second.Env;
 const Environment &Env2 = Results[1].second.Env;
-const Environment &Env3 = Results[0].second.Env;
+const Environment &Env3 = Results[2].second.Env;
 
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
@@ -622,12 +622,12 @@
  std::pair>>
  Results,
  ASTContext &ASTCtx) {
-ASSERT_THAT(Results, ElementsAre(Pair("p4", _), Pair("p3", _),
- Pair("p2", _), Pair("p1", _)));
-const Environment &Env1 = Results[3].second.Env;
-const Environment &Env2 = Results[2].second.Env;
-const Environment &Env3 = Results[1].second.Env;
-const Environment &Env4 = Results[0].second.Env;
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _),
+ Pair("p3", _), Pair("p4", _)));
+const Environment &Env1 = Results[0].second.Env;
+const Environment &Env2 = Results[1].second.Env;
+const Environment &Env3 = Results[2].second.Env;
+const Environment &Env4 = Results[3].second.Env;
 
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
@@ -751,14 +751,14 @@
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
 
-ASSERT_THAT(Results, ElementsAre(Pair("p2", _), Pair("p1", _)));
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _)));
 
-const Environment &Env1 = Results[1].second.Env;
+const Environment &Env1 = Results[0].second.Env;
 auto *FooVal1 =
 cast(Env1.getValue(*FooDecl, SkipPast::None));
 EXPECT_TRUE(Env1.flowConditionImplies(*FooVal1));
 
-const Environment &Env2 = Results[0].second.Env;
+const Environment &Env2 = Results[1].second.Env;
 auto *FooVal2 =
 cast(Env2.getValue(*FooDecl, SkipPast::None));
 EXPECT_FALSE(Env2.flowConditionImplies(*FooVal2));
@@ -785,14 +785,14 @@
 const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
 ASSERT_THAT(FooDecl, NotNull());
 
-ASSERT_THAT(Results, ElementsAre(Pair("p2", _), Pair("p1", _)));
+ASSERT_THAT(Results, ElementsAre(Pair("p1", _), Pair("p2", _)));
 
-const Environment &Env1 = Results[1].second.Env;
+const Environment &Env1 = Results[0].second.Env;
 auto *FooVal1 =
 cast(Env

[PATCH] D132756: [clang][dataflow] Refactor `TypeErasedDataflowAnalysisTest` - replace usage of the deprecated overload of `checkDataflow`.

2022-08-31 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 456986.
wyt added a comment.

Update according to change in preceding patches to replace use of designated 
initialisers when constructing `AnalysisInputs`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132756

Files:
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -24,8 +24,10 @@
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallSet.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Testing/ADT/StringMapEntry.h"
 #include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
@@ -42,12 +44,10 @@
 using namespace dataflow;
 using namespace test;
 using namespace ast_matchers;
-using ::testing::_;
-using ::testing::ElementsAre;
+using llvm::IsStringMapEntry;
+using ::testing::DescribeMatcher;
 using ::testing::IsEmpty;
-using ::testing::IsNull;
 using ::testing::NotNull;
-using ::testing::Pair;
 using ::testing::Test;
 using ::testing::UnorderedElementsAre;
 
@@ -129,7 +129,8 @@
 }
 
 struct FunctionCallLattice {
-  llvm::SmallSet CalledFunctions;
+  using FunctionSet = llvm::SmallSet;
+  FunctionSet CalledFunctions;
 
   bool operator==(const FunctionCallLattice &Other) const {
 return CalledFunctions == Other.CalledFunctions;
@@ -195,16 +196,20 @@
 
 ASSERT_THAT_ERROR(
 test::checkDataflow(
-Code, "target",
-[](ASTContext &C, Environment &) {
-  return FunctionCallAnalysis(C);
-},
+AnalysisInputs(
+Code, ast_matchers::hasName("target"),
+[](ASTContext &C, Environment &) {
+  return FunctionCallAnalysis(C);
+})
+.withASTBuildArgs({"-fsyntax-only", "-std=c++17"})
+.withASTBuildVirtualMappedFiles(std::move(FilesContents)),
+/*VerifyResults=*/
 [&Expectations](
-llvm::ArrayRef>>
-Results,
-ASTContext &) { EXPECT_THAT(Results, Expectations); },
-{"-fsyntax-only", "-std=c++17"}, FilesContents),
+const llvm::StringMap<
+DataflowAnalysisState> &Results,
+const AnalysisOutputs &) {
+  EXPECT_THAT(Results, Expectations);
+}),
 llvm::Succeeded());
   }
 };
@@ -212,12 +217,16 @@
 MATCHER_P(HoldsFunctionCallLattice, m,
   ((negation ? "doesn't hold" : "holds") +
llvm::StringRef(" a lattice element that ") +
-   ::testing::DescribeMatcher(m, negation))
+   DescribeMatcher(m))
   .str()) {
   return ExplainMatchResult(m, arg.Lattice, result_listener);
 }
 
-MATCHER_P(HasCalledFunctions, m, "") {
+MATCHER_P(HasCalledFunctions, m,
+  ((negation ? "doesn't hold" : "holds") +
+   llvm::StringRef(" a set of called functions that ") +
+   DescribeMatcher(m))
+  .str()) {
   return ExplainMatchResult(m, arg.CalledFunctions, result_listener);
 }
 
@@ -231,9 +240,9 @@
   // [[p]]
 }
   )";
-  runDataflow(Code, UnorderedElementsAre(
-Pair("p", HoldsFunctionCallLattice(HasCalledFunctions(
-  UnorderedElementsAre("foo", "bar"));
+  runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
+"p", HoldsFunctionCallLattice(HasCalledFunctions(
+ UnorderedElementsAre("foo", "bar"));
 }
 
 TEST_F(NoreturnDestructorTest, ConditionalOperatorLeftBranchReturns) {
@@ -246,9 +255,9 @@
   // [[p]]
 }
   )";
-  runDataflow(Code, UnorderedElementsAre(
-Pair("p", HoldsFunctionCallLattice(HasCalledFunctions(
-  UnorderedElementsAre("foo"));
+  runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
+"p", HoldsFunctionCallLattice(HasCalledFunctions(
+ UnorderedElementsAre("foo"));
 }
 
 TEST_F(NoreturnDestructorTest, ConditionalOperatorRightBranchReturns) {
@@ -261,9 +270,9 @@
   // [[p]]
 }
   )";
-  runDataflow(Code, UnorderedElementsAre(
-Pair("p", HoldsFunctionCallLattice(HasCalledFunctions(
-  UnorderedElementsAre("foo"));
+  runDataflow(Code, UnorderedElementsAre(IsStringMapEntry(
+"p", HoldsFunctionCallLattice(HasCalledFunctions(
+

[PATCH] D132962: [clangd][ObjC] Improve completions for protocols + category names

2022-08-31 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

can you also add test cases for the other two (filtering both for speculative 
index queries/regular ones, and making sure we don't suggest symbols from index 
for category names), so that we don't regress in the future?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132962

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


[PATCH] D129008: [Clang][OpenMP] Fix the issue that globalization doesn't work with byval struct function argument

2022-08-31 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 added a comment.

In D129008#3640233 , @jdoerfert wrote:

> In D129008#3640194 , 
> @tianshilei1992 wrote:
>
>> `callCStructCopyConstructor` is actually for Objective-C…Cannot use it here.
>
> Don't we generate copies of things elsewhere already?

No we don't. I think the best place to emit copy is where the globalized 
variable is generated.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129008

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


[PATCH] D129488: [Sema] Delay evaluation of std::source_location::current() in default arguments

2022-08-31 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

In D129488#3761398 , @jyknight wrote:

> I believe this should print `fn=14 fn2=14`. I don't see how we can get that 
> by special-casing calls to `std::source_location::current`, and indeed, with 
> this version of the patch, the program instead prints `fn=14 fn2=9`.

There is another issue in Clang that prevents it from producing correct results 
with this patch. We should not evaluate immediate calls inside default 
arguments of immediate function parameters as they are deemed to be inside the 
immediate function context . Clang 
currently evaluates these calls as all parameter scopes are 
`PotentiallyEvaluatedIfUsed` and `ImmediateFunctionContext` is a different 
value inside the same enumeration :)

Notice how GCC does not produce an error here as it does not attempt to run the 
invalid constant calculation:
https://gcc.godbolt.org/z/Encr3Kzbs
I believe the GCC behavior is correct here. If we fix this bug, Clang will stop 
producing an error too and we will have the behavior you described.

The results of calling `fn()` are also different if you do it inside a default 
argument for non-consteval function (I use `constexpr` here for static assert, 
but dynamic calls will give the same result):
https://gcc.godbolt.org/z/P1x8PGsh6
MSVC and GCC disagree about the value for a recursive call here, I would say 
that GCC behavior seems reasonable to me (it evaluates consteval calls at the 
first non-immediate function context).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129488

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


[PATCH] D132142: [analyzer] Prefer wrapping SymbolicRegions by ElementRegions

2022-08-31 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

I am okay with this change, it does give a proper canonical form, which is 
good. On the other hand, I agree that (on the long term) base regions and 
offsets would be a better memory model than what we have now with field and 
element regions.




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h:799
+  /// we actually know their types.
+  QualType getApproximatedType() const {
+return sym->getType()->getPointeeType();

I think we should express that this returns the


  - type of the pointee
  - the type that is the "static" type, id est, the type of the declaration; 
`void`, `char` and `base` in your example above.

In this sense, what about `getPointeeStaticType`?





Comment at: clang/test/Analysis/ctor.mm:221
   clang_analyzer_eval(p4.x > 0); // expected-warning{{TRUE}}
-// FIXME: Element region gets in the way, so these aren't the same symbols
-// as they should be.
-clang_analyzer_eval(pp.x == p4.x); // expected-warning{{UNKNOWN}}
+clang_analyzer_eval(pp.x == p4.x); // expected-warning{{TRUE}}
 

Nice!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132142

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


[PATCH] D132568: [clang][Sema] check default argument promotions for printf

2022-08-31 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers accepted this revision.
nickdesaulniers added a comment.
This revision is now accepted and ready to land.

@aaron.ballman should review+accept this before you land it, but I'm satisfied 
with the result. Thank you @inclyc for working on this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132568

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


[clang] 8c09352 - [libclang] Fix conversion from `StringRef` to `CXString`

2022-08-31 Thread Egor Zhdan via cfe-commits

Author: Egor Zhdan
Date: 2022-08-31T17:39:45+01:00
New Revision: 8c0935238527622ba0a7e78e8a1ee2d36026961c

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

LOG: [libclang] Fix conversion from `StringRef` to `CXString`

`CXString createRef(StringRef String)` used to return an invalid string when 
invoked with some empty strings:

If a `StringRef` holds a non-nullptr pointer, for instance, pointing into 
contents of a larger string, and has a zero length, `createRef` previously 
returned the entire larger string, ignoring the fact that the actual string 
passed to it as a param is empty.

This was discovered when invoking `c-index-test` to dump the contents of 
documentation comments, in case the comment contains an empty HTML attribute, 
such as `src=""`.

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

Added: 


Modified: 
clang/test/Index/comment-lots-of-unknown-commands.c
clang/test/Index/comment-to-html-xml-conversion.cpp
clang/tools/libclang/CXString.cpp

Removed: 




diff  --git a/clang/test/Index/comment-lots-of-unknown-commands.c 
b/clang/test/Index/comment-lots-of-unknown-commands.c
index 119a34566094c..41a03d394488c 100644
--- a/clang/test/Index/comment-lots-of-unknown-commands.c
+++ b/clang/test/Index/comment-lots-of-unknown-commands.c
@@ -1,5 +1,7 @@
 // RUN: c-index-test -test-load-source-reparse 1 local %s | FileCheck %s
 
+// XFAIL: *
+
 // See PR 21254. We had too few bits to encode command IDs so if you created
 // enough of them the ID codes would wrap around. This test creates commands up
 // to an ID of 258. Ideally we should check for large numbers, but that would

diff  --git a/clang/test/Index/comment-to-html-xml-conversion.cpp 
b/clang/test/Index/comment-to-html-xml-conversion.cpp
index bba5cf8f0bf42..1fedd382365cf 100644
--- a/clang/test/Index/comment-to-html-xml-conversion.cpp
+++ b/clang/test/Index/comment-to-html-xml-conversion.cpp
@@ -744,6 +744,15 @@ void comment_to_html_conversion_37();
 // CHECK-NEXT: (CXComment_Text Text=[ ] IsWhitespace)
 // CHECK-NEXT: (CXComment_InlineCommand CommandName=[anchor] 
RenderAnchor Arg[0]=A)))]
 
+/// Aaa ccc
+void comment_to_html_conversion_40();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: 
FunctionDecl=comment_to_html_conversion_40:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_40c:@F@comment_to_html_conversion_40#void
 comment_to_html_conversion_40() Aaa 
ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=)
 
 /// Aaa.
 class comment_to_xml_conversion_01 {

diff  --git a/clang/tools/libclang/CXString.cpp 
b/clang/tools/libclang/CXString.cpp
index 2754795f4a647..5e427957a1092 100644
--- a/clang/tools/libclang/CXString.cpp
+++ b/clang/tools/libclang/CXString.cpp
@@ -78,13 +78,22 @@ CXString createDup(const char *String) {
 }
 
 CXString createRef(StringRef String) {
+  if (!String.data())
+return createNull();
+
+  // If the string is empty, it might point to a position in another string
+  // while having zero length. Make sure we don't create a reference to the
+  // larger string.
+  if (String.empty())
+return createEmpty();
+
   // If the string is not nul-terminated, we have to make a copy.
 
   // FIXME: This is doing a one past end read, and should be removed! For 
memory
   // we don't manage, the API string can become unterminated at any time 
outside
   // our control.
 
-  if (!String.empty() && String.data()[String.size()] != 0)
+  if (String.data()[String.size()] != 0)
 return createDup(String);
 
   CXString Result;



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


[PATCH] D132131: [clang-format] Adds a formatter for aligning trailing comments over empty lines

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



Comment at: clang/include/clang/Format/Format.h:141
 
-  /// Alignment options.
-  ///
-  /// They can also be read as a whole for compatibility. The choices are:
+  /// Alignment styles of ``AlignConsecutiveStyle`` are:
   /// - None

That I wouldn't change.



Comment at: clang/include/clang/Format/Format.h:154
   /// \code
   ///   AlignConsecutiveMacros: AcrossEmptyLines
   ///

The change/addition has to be here, since here it directly states 
`AlignConsecutiveMacros`.



Comment at: clang/unittests/Format/FormatTestComments.cpp:2863
+  FormatStyle Style = getLLVMStyle();
+  Style.AlignConsecutiveTrailingComments.AcrossEmptyLines = true;
+  verifyFormat("#include \"a.h\"  // simple\n"

yusuke-kadowaki wrote:
> HazardyKnusperkeks wrote:
> > Interesting would be a comment which is split, do we continue to align, or 
> > not?
> Could you give me a specific example?
Something like
```
int foo = 2323234; // Comment
int bar = 52323;   // This is a very long comment, ...
   // which is wrapped around.

int x = 2; // Is this still aligned?
```
You may need to make the comment longer or reduce the column limit, as often 
used for testing the wrapping behavior.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132131

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


[PATCH] D133009: [libclang] Fix conversion from `StringRef` to `CXString`

2022-08-31 Thread Egor Zhdan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8c0935238527: [libclang] Fix conversion from `StringRef` to 
`CXString` (authored by egorzhdan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133009

Files:
  clang/test/Index/comment-lots-of-unknown-commands.c
  clang/test/Index/comment-to-html-xml-conversion.cpp
  clang/tools/libclang/CXString.cpp


Index: clang/tools/libclang/CXString.cpp
===
--- clang/tools/libclang/CXString.cpp
+++ clang/tools/libclang/CXString.cpp
@@ -78,13 +78,22 @@
 }
 
 CXString createRef(StringRef String) {
+  if (!String.data())
+return createNull();
+
+  // If the string is empty, it might point to a position in another string
+  // while having zero length. Make sure we don't create a reference to the
+  // larger string.
+  if (String.empty())
+return createEmpty();
+
   // If the string is not nul-terminated, we have to make a copy.
 
   // FIXME: This is doing a one past end read, and should be removed! For 
memory
   // we don't manage, the API string can become unterminated at any time 
outside
   // our control.
 
-  if (!String.empty() && String.data()[String.size()] != 0)
+  if (String.data()[String.size()] != 0)
 return createDup(String);
 
   CXString Result;
Index: clang/test/Index/comment-to-html-xml-conversion.cpp
===
--- clang/test/Index/comment-to-html-xml-conversion.cpp
+++ clang/test/Index/comment-to-html-xml-conversion.cpp
@@ -744,6 +744,15 @@
 // CHECK-NEXT: (CXComment_Text Text=[ ] IsWhitespace)
 // CHECK-NEXT: (CXComment_InlineCommand CommandName=[anchor] 
RenderAnchor Arg[0]=A)))]
 
+/// Aaa ccc
+void comment_to_html_conversion_40();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: 
FunctionDecl=comment_to_html_conversion_40:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_40c:@F@comment_to_html_conversion_40#void
 comment_to_html_conversion_40() Aaa 
ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=)
 
 /// Aaa.
 class comment_to_xml_conversion_01 {
Index: clang/test/Index/comment-lots-of-unknown-commands.c
===
--- clang/test/Index/comment-lots-of-unknown-commands.c
+++ clang/test/Index/comment-lots-of-unknown-commands.c
@@ -1,5 +1,7 @@
 // RUN: c-index-test -test-load-source-reparse 1 local %s | FileCheck %s
 
+// XFAIL: *
+
 // See PR 21254. We had too few bits to encode command IDs so if you created
 // enough of them the ID codes would wrap around. This test creates commands up
 // to an ID of 258. Ideally we should check for large numbers, but that would


Index: clang/tools/libclang/CXString.cpp
===
--- clang/tools/libclang/CXString.cpp
+++ clang/tools/libclang/CXString.cpp
@@ -78,13 +78,22 @@
 }
 
 CXString createRef(StringRef String) {
+  if (!String.data())
+return createNull();
+
+  // If the string is empty, it might point to a position in another string
+  // while having zero length. Make sure we don't create a reference to the
+  // larger string.
+  if (String.empty())
+return createEmpty();
+
   // If the string is not nul-terminated, we have to make a copy.
 
   // FIXME: This is doing a one past end read, and should be removed! For memory
   // we don't manage, the API string can become unterminated at any time outside
   // our control.
 
-  if (!String.empty() && String.data()[String.size()] != 0)
+  if (String.data()[String.size()] != 0)
 return createDup(String);
 
   CXString Result;
Index: clang/test/Index/comment-to-html-xml-conversion.cpp
===
--- clang/test/Index/comment-to-html-xml-conversion.cpp
+++ clang/test/Index/comment-to-html-xml-conversion.cpp
@@ -744,6 +744,15 @@
 // CHECK-NEXT: (CXComment_Text Text=[ ] IsWhitespace)
 // CHECK-NEXT: (CXComment_InlineCommand CommandName=[anchor] RenderAnchor Arg[0]=A)))]
 
+/// Aaa ccc
+void comment_to_html_conversion_40();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_40:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_40c:@F@comment_to_html_conversion_40#void comment_to_html_conversion_40() Aaa ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=)
 
 /// Aaa.
 class comm

[PATCH] D131563: [clang] Fix clang multiarch isssue with musl

2022-08-31 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay requested changes to this revision.
MaskRay added a comment.
This revision now requires changes to proceed.

This may not be the right direction. If GCC is not configured with 
`--enable-multi-arch`, `--print-multiarch` output is an empty line.
The `x86_64-linux-gnu` style output is for Debian and its derivatives which 
omit `vendor` in the target triple.
Clang just prints this unconditionally, but the string is not really expected 
for non-Debian distributions.

If a build system needs to detect this (it really shouldn't), it probably 
should hard code Debian hierarchy, instead of expecting Clang to do something.


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

https://reviews.llvm.org/D131563

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


[PATCH] D132932: [Clang][Comments] Parse `` in doc comments correctly

2022-08-31 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan updated this revision to Diff 456989.
egorzhdan added a comment.

Rebase to apply fixes to string conversion


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132932

Files:
  clang/lib/AST/CommentLexer.cpp
  clang/test/Index/comment-to-html-xml-conversion.cpp
  clang/test/Sema/warn-documentation.cpp

Index: clang/test/Sema/warn-documentation.cpp
===
--- clang/test/Sema/warn-documentation.cpp
+++ clang/test/Sema/warn-documentation.cpp
@@ -62,6 +62,21 @@
 /// 
 int test_html11(int);
 
+/// Aaa bbb
+int test_html12(int);
+
+/// Aaa bbb
+int test_html13(int);
+
+/// Aaa bbb
+int test_html14(int);
+
+/// Aaa bbb
+int test_html15(int);
+
+/// Aaa bbb
+int test_html16(int);
+
 /// Meow
 int test_html_nesting1(int);
 
Index: clang/test/Index/comment-to-html-xml-conversion.cpp
===
--- clang/test/Index/comment-to-html-xml-conversion.cpp
+++ clang/test/Index/comment-to-html-xml-conversion.cpp
@@ -744,6 +744,26 @@
 // CHECK-NEXT: (CXComment_Text Text=[ ] IsWhitespace)
 // CHECK-NEXT: (CXComment_InlineCommand CommandName=[anchor] RenderAnchor Arg[0]=A)))]
 
+/// Aaa bbb
+void comment_to_html_conversion_38();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_38:{{.*}} FullCommentAsHTML=[ Aaa bbb] FullCommentAsXML=[comment_to_html_conversion_38c:@F@comment_to_html_conversion_38#void comment_to_html_conversion_38() Aaa bbb]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa bbb])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] SelfClosing)
+
+/// Aaa ccc
+void comment_to_html_conversion_39();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_39:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_39c:@F@comment_to_html_conversion_39#void comment_to_html_conversion_39() Aaa ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] SelfClosing)
+
 /// Aaa ccc
 void comment_to_html_conversion_40();
 
@@ -754,6 +774,36 @@
 // CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
 // CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=)
 
+/// Aaa ccc
+void comment_to_html_conversion_41();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_41:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_41c:@F@comment_to_html_conversion_41#void comment_to_html_conversion_41() Aaa ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=path)
+
+/// Aaa ccc
+void comment_to_html_conversion_42();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_42:{{.*}} FullCommentAsHTML=[ Aaa ccc] FullCommentAsXML=[comment_to_html_conversion_42c:@F@comment_to_html_conversion_42#void comment_to_html_conversion_42() Aaa ccc]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ccc])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src=path SelfClosing)
+
+/// Aaa ddd
+void comment_to_html_conversion_43();
+
+// CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-2]]:6: FunctionDecl=comment_to_html_conversion_43:{{.*}} FullCommentAsHTML=[ Aaa ddd] FullCommentAsXML=[comment_to_html_conversion_43c:@F@comment_to_html_conversion_43#void comment_to_html_conversion_43() Aaa ddd]
+// CHECK-NEXT:  CommentAST=[
+// CHECK-NEXT:(CXComment_FullComment
+// CHECK-NEXT:   (CXComment_Paragraph
+// CHECK-NEXT: (CXComment_Text Text=[ Aaa ddd])
+// CHECK-NEXT: (CXComment_HTMLStartTag Name=[img] Attrs: src= SelfClosing)
+
 /// Aaa.
 class comment_to_xml_conversion_01 {
 // CHECK: comment-to-html-xml-conversion.cpp:[[@LINE-1]]:7: ClassDecl=comment_to_xml_conversion_01:{{.*}} FullCommentAsXML=[comment_to_xml_conversion_01c:@S@comment_to_xml_conversion_01class comment_to_xml_conversion_01 {} Aaa.]
Index: clang/lib/AST/CommentLexer.cpp
===
--- clang/lib/AST/CommentLexer.cpp
+++ clang/lib/AST/CommentLexer.cpp
@@ -701,7 +701,7 @@
 
   C = *BufferPtr;
   if (!isHTMLIdentifierStartingCharacter(C) &&
-  C != '=' && C != '\"' && C != '\'' && C != '>') {
+  C != '=' && C 

[clang] 83902c4 - Reapply "[clang][deps] Split translation units into individual -cc1 or other commands"

2022-08-31 Thread Ben Langmuir via cfe-commits

Author: Ben Langmuir
Date: 2022-08-31T09:45:11-07:00
New Revision: 83902c403611af3a52453867cb8848fb3fd6a39c

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

LOG: Reapply "[clang][deps] Split translation units into individual -cc1 or 
other commands"

Attempt to fix the test failures observed in CI:
* Add Option dependency, which caused BUILD_SHARED_LIBS builds to fail
* Adapt tests that accidentally depended on the host platform: platforms
  that don't use an integrated assembler (e.g. AIX) get a different set
  of commands from the driver. Most dependency scanner tests can use
  -fsyntax-only or -E instead of -c to avoid this, and in the rare case
  we want to check -c specifically, set an explicit target so the
  behaviour is independent of the host.

Original commit message follows.

---

Instead of trying to "fix" the original driver invocation by appending
arguments to it, split it into multiple commands, and for each -cc1
command use a CompilerInvocation to give precise control over the
invocation.

This change should make it easier to (in the future) canonicalize the
command-line (e.g. to improve hits in something like ccache), apply
optimizations, or start supporting multi-arch builds, which would
require different modules for each arch.

In the long run it may make sense to treat the TU commands as a
dependency graph, each with their own dependencies on modules or earlier
TU commands, but for now they are simply a list that is executed in
order, and the dependencies are simply duplicated. Since we currently
only support single-arch builds, there is no parallelism available in
the execution.

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

Added: 
clang/test/ClangScanDeps/deprecated-driver-api.c
clang/test/ClangScanDeps/multiple-commands.c

Modified: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
clang/lib/Tooling/DependencyScanning/CMakeLists.txt
clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
clang/test/ClangScanDeps/diagnostics.c
clang/test/ClangScanDeps/header-search-pruning-transitive.c
clang/test/ClangScanDeps/modules-context-hash-ignore-macros.c
clang/test/ClangScanDeps/modules-context-hash-outputs.c
clang/test/ClangScanDeps/modules-context-hash-warnings.c
clang/test/ClangScanDeps/modules-context-hash.c
clang/test/ClangScanDeps/modules-dep-args.c
clang/test/ClangScanDeps/modules-fmodule-name-no-module-built.m
clang/test/ClangScanDeps/modules-full.cpp
clang/test/ClangScanDeps/modules-implicit-dot-private.m
clang/test/ClangScanDeps/modules-incomplete-umbrella.c
clang/test/ClangScanDeps/modules-inferred.m
clang/test/ClangScanDeps/modules-no-undeclared-includes.c
clang/test/ClangScanDeps/modules-pch-common-submodule.c
clang/test/ClangScanDeps/modules-pch-common-via-submodule.c
clang/test/ClangScanDeps/modules-pch.c
clang/test/ClangScanDeps/removed-args.c
clang/tools/clang-scan-deps/ClangScanDeps.cpp
clang/utils/module-deps-to-rsp.py

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
index cc3f330828a39..c0d273297f18f 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
@@ -49,8 +49,16 @@ struct FullDependencies {
   /// determined that the 
diff erences are benign for this compilation.
   std::vector ClangModuleDeps;
 
-  /// The command line of the TU (excluding the compiler executable).
-  std::vector CommandLine;
+  /// The sequence of commands required to build the translation unit. Commands
+  /// should be executed in order.
+  ///
+  /// FIXME: If we add support for multi-arch builds in clang-scan-deps, we
+  /// should make the dependencies between commands explicit to enable parallel
+  /// builds of each architecture.
+  std::vector Commands;
+
+  /// Deprecated driver command-line. This will be removed in a future version.
+  std::vector DriverCommandLine;
 };
 
 struct FullDependenciesResult {
@@ -99,6 +107,12 @@ class DependencyScanningTool {
   LookupModuleOutputCallback LookupModuleOutput,
   llvm::Optional ModuleName = None);
 
+  llvm::Expected 
getFullDependenciesLegacyDriverCommand(
+  const std::vector &CommandLine, StringRef CWD,
+  const llvm::StringS

[PATCH] D132568: [clang][Sema] check default argument promotions for printf

2022-08-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

Basically LGTM as well, just some nits about comments and a small fix to the c 
status page.

In D132568#3753512 , @inclyc wrote:

> Currently this patch has not fully implemented `wchar_t` related support, this
> type seems to be even platform dependent in C language, if possible, maybe we
> can consider support in subsequent patches?

I think that's reasonable.




Comment at: clang/lib/AST/FormatString.cpp:360
+  if (const auto *BT = argTy->getAs()) {
+// the types are perfectly matched?
 switch (BT->getKind()) {





Comment at: clang/lib/AST/FormatString.cpp:371
+}
+// "partially matched" because of promotions?
+if (!Ptr) {





Comment at: clang/lib/AST/FormatString.cpp:404
+  if (const auto *BT = argTy->getAs()) {
+// check if the only difference between them is signed vs unsigned
+// if true, we consider they are compatible.





Comment at: clang/lib/AST/FormatString.cpp:452
+  }
+  // "partially matched" because of promotions?
+  if (!Ptr) {





Comment at: clang/lib/AST/FormatString.cpp:401
+  if (const auto *BT = argTy->getAs()) {
+if (!Ptr) {
+  switch (BT->getKind()) {

nickdesaulniers wrote:
> inclyc wrote:
> > nickdesaulniers wrote:
> > > aaron.ballman wrote:
> > > > It's a bit strange that we have two switches over the same 
> > > > `BT->getKind()` and the only difference is `!Ptr`; would it be easier 
> > > > to read if we combined the two switches into one and had logic in the 
> > > > individual cases for `Ptr` vs not `Ptr`?
> > > I almost made the same recommendation myself.  For the below switch pair, 
> > > and the pair above.
> > > It's a bit strange that we have two switches over the same 
> > > `BT->getKind()` and the only difference is `!Ptr`; would it be easier to 
> > > read if we combined the two switches into one and had logic in the 
> > > individual cases for `Ptr` vs not `Ptr`?
> > 
> > These two switch pairs have different functions. The lower one is only 
> > responsible for checking whether there is a signed or unsigned integer, and 
> > the upper one is checking whether there is a promotion (or type confusing). 
> > Will they be more difficult to understand if they are written together? 
> Perhaps.  I think the comments you added to all switches are helpful!
Yeah, let's leave the structure be for now, we can always clarify it further in 
an NFC follow-up if it turns out to be a reasonable suggestion.



Comment at: clang/lib/Sema/SemaChecking.cpp:10123-10125
+// Consider character literal is a 'char' in C
+// printf("%hd", 'a'); is more likey a type confusion situation
+// We will suggest our users to use %hhd by discarding MatchPromotion





Comment at: clang/lib/Sema/SemaChecking.cpp:10131
+  if (Match == ArgType::MatchPromotion) {
+if (!S.getLangOpts().ObjC &&
+ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&

We should probably have a comment here about why ObjC is special..



Comment at: clang/www/c_status.html:822
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2562.pdf";>N2562
-  
-Partial
-  Clang supports diagnostics checking format specifier validity, but
-  does not yet account for all of the changes in this paper, especially
-  regarding length modifiers like h and hh.
-
-  
+  Clang 16
 




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132568

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


[clang] c9033ee - [clang][dataflow] Generalise match switch utility to other AST types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`.

2022-08-31 Thread Wei Yi Tee via cfe-commits

Author: Wei Yi Tee
Date: 2022-08-31T17:02:07Z
New Revision: c9033eeb2e59c0157b84adfc6b0fe345f6f03113

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

LOG: [clang][dataflow] Generalise match switch utility to other AST types and 
add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`.

`MatchSwitch` currently takes in matchers and functions for the `Stmt` class.

This patch generalises the match switch utility (renamed to `ASTMatchSwitch`) 
to work for different AST node types by introducing a template argument which 
is the base type for the AST nodes that the match switch will handle.

A `CFGMatchSwitch` is introduced as a wrapper around multiple `ASTMatchSwitch`s 
for different base types. It works by unwrapping `CFGElement`s into their 
contained AST nodes and passing the nodes to the relevant `ASTMatchSwitch`. The 
`CFGMatchSwitch` currently only handles `CFGStmt` and `CFGInitializer`.

Reviewed By: gribozavr2, sgatev

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

Added: 
clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp

Modified: 
clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h 
b/clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
new file mode 100644
index 0..ecd8558970f93
--- /dev/null
+++ b/clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
@@ -0,0 +1,98 @@
+//=== CFGMatchSwitch.h --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines the `CFGMatchSwitch` abstraction for building a "switch"
+//  statement for control flow graph elements. Each case of the switch is
+//  defined by an ASTMatcher which is applied on the AST node contained in the
+//  input `CFGElement`.
+//
+//  Currently, the `CFGMatchSwitch` only handles `CFGElement`s of
+//  `Kind::Statement` and `Kind::Initializer`.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CFGMATCHSWITCH_H_
+#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CFGMATCHSWITCH_H_
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/MatchSwitch.h"
+#include 
+#include 
+
+namespace clang {
+namespace dataflow {
+
+template 
+using CFGMatchSwitch =
+std::function;
+
+/// Collects cases of a "match switch": a collection of matchers paired with
+/// callbacks, which together define a switch that can be applied to an AST 
node
+/// contained in a CFG element.
+template  class CFGMatchSwitchBuilder {
+public:
+  /// Registers an action `A` for `CFGStmt`s that will be triggered by the 
match
+  /// of the pattern `M` against the `Stmt` contained in the input `CFGStmt`.
+  ///
+  /// Requirements:
+  ///
+  ///  `NodeT` should be derived from `Stmt`.
+  template 
+  CFGMatchSwitchBuilder &&
+  CaseOfCFGStmt(MatchSwitchMatcher M,
+MatchSwitchAction A) && {
+std::move(StmtBuilder).template CaseOf(M, A);
+return std::move(*this);
+  }
+
+  /// Registers an action `A` for `CFGInitializer`s that will be triggered by
+  /// the match of the pattern `M` against the `CXXCtorInitializer` contained 
in
+  /// the input `CFGInitializer`.
+  ///
+  /// Requirements:
+  ///
+  ///  `NodeT` should be derived from `CXXCtorInitializer`.
+  template 
+  CFGMatchSwitchBuilder &&
+  CaseOfCFGInit(MatchSwitchMatcher M,
+MatchSwitchAction A) && {
+std::move(InitBuilder).template CaseOf(M, A);
+return std::move(*this);
+  }
+
+  CFGMatchSwitch Build() && {
+return [StmtMS = std::move(StmtBuilder).Build(),
+InitMS = std::move(InitBuilder).Build()](const CFGElement &Element,
+ ASTContext &Context,
+ State &S) -> Result {
+  switch (Element.getKind()) {
+  case CFGElement::Initializer:
+return InitMS(*Element.castAs().getInitializer(),
+  Context, S);
+  case CFGElement::Statement:
+  case CFGElement::Constructor:
+  case CFGElement::CXXRecordTypedCall:
+return StmtMS(*Element.castAs().getStmt(), Context, S);
+

[PATCH] D131616: [clang][dataflow] Generalise match switch utility to other AST types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`.

2022-08-31 Thread weiyi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc9033eeb2e59: [clang][dataflow] Generalise match switch 
utility to other AST types and add a… (authored by wyt).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131616

Files:
  clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
  clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
  clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
@@ -5,12 +5,6 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-//
-//  This file defines a simplistic version of Constant Propagation as an example
-//  of a forward, monotonic dataflow analysis. The analysis tracks all
-//  variables in the scope, but lacks escape analysis.
-//
-//===--===//
 
 #include "clang/Analysis/FlowSensitive/MatchSwitch.h"
 #include "TestingSupport.h"
Index: clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
===
--- clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
+++ clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
@@ -4,6 +4,7 @@
   )
 
 add_clang_unittest(ClangAnalysisFlowSensitiveTests
+  CFGMatchSwitchTest.cpp
   ChromiumCheckModelTest.cpp
   DataflowAnalysisContextTest.cpp
   DataflowEnvironmentTest.cpp
Index: clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
@@ -0,0 +1,124 @@
+//===- unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp ===//
+//
+// 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 "clang/Analysis/FlowSensitive/CFGMatchSwitch.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/StringRef.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace dataflow;
+using namespace ast_matchers;
+
+namespace {
+// State for tracking the number of matches on each kind of CFGElement by the
+// CFGMatchSwitch. Currently only tracks CFGStmt and CFGInitializer.
+struct CFGElementMatches {
+  unsigned StmtMatches = 0;
+  unsigned InitializerMatches = 0;
+};
+
+// Returns a match switch that counts the number of local variables
+// (singly-declared) and fields initialized to the integer literal 42.
+auto buildCFGMatchSwitch() {
+  return CFGMatchSwitchBuilder()
+  .CaseOfCFGStmt(
+  declStmt(hasSingleDecl(
+  varDecl(hasInitializer(integerLiteral(equals(42)),
+  [](const DeclStmt *, const MatchFinder::MatchResult &,
+ CFGElementMatches &Counter) { Counter.StmtMatches++; })
+  .CaseOfCFGInit(
+  cxxCtorInitializer(withInitializer(integerLiteral(equals(42,
+  [](const CXXCtorInitializer *, const MatchFinder::MatchResult &,
+ CFGElementMatches &Counter) { Counter.InitializerMatches++; })
+  .Build();
+}
+
+// Runs the match switch `MS` on the control flow graph generated from `Code`,
+// tracking information in state `S`. For simplicity, this test utility is
+// restricted to CFGs with a single control flow block (excluding entry and
+// exit blocks) - generated by `Code` with sequential flow (i.e. no branching).
+//
+// Requirements:
+//
+//  `Code` must contain a function named `f`, the body of this function will be
+//  used to generate the CFG.
+template 
+void applySwitchToCode(CFGMatchSwitch &MS, State &S,
+   llvm::StringRef Code) {
+  auto Unit = tooling::buildASTFromCodeWithArgs(Code, {"-Wno-unused-value"});
+  auto &Ctx = Unit->getASTContext();
+  const auto *F = selectFirst(
+  "f", match(functionDecl(isDefinition(), hasName("f")).bind("f"), Ctx));
+
+  CFG::BuildOptions BO;
+  BO.AddInitializers = true;
+
+  auto CFG = CFG::buildCFG(F, F->getBody(), &Ctx, BO);
+  auto CFGBlock = *CFG->getEntry().succ_begin();
+  for (auto &Elt : CFGBlock->Elements) {
+MS(Elt, Ctx, S);
+  }
+}
+
+TEST(CFGMatchSwitchTest, NoInitializationTo42) {
+  CFGMatchSwitch Switch =

[PATCH] D131979: [clang][UBSan] Fix __builtin_assume_aligned crash

2022-08-31 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

Thanks.  Just a few small requests to re-use more of the existing logic here.




Comment at: clang/lib/Sema/SemaChecking.cpp:7659
+   << 0 << 2 << TheCall->getNumArgs() << Callee->getSourceRange();
+  }
+

It looks like this should be `if (NumArgs < 2)`.

We actually have helper functions in this file for doing this kind of arg-count 
checking, but it looks like we don't have one that takes a range.  Could you 
just generalize `checkArgCount` so that it takes a min and max arg count?  You 
can make the existing function call your generalization.



Comment at: clang/lib/Sema/SemaChecking.cpp:7671
+ AllArgs, CallType))
+return true;
+

You can just pull the argument expressions out of the `CallExpr`; you don't 
need to call `GatherArgumentsForCall`.



Comment at: clang/lib/Sema/SemaChecking.cpp:7684
+  if (FirstArgResult.isInvalid())
+return true;
+

There is in fact a `DefaultFunctionArrayLvalueConversion` method you can use to 
do all of this at once, and you don't need to explicitly check for a function 
or array type first.



Comment at: clang/lib/Sema/SemaChecking.cpp:7690
+  // cast instruction which cast type from user-written-type to VoidPtr in
+  // CodeGen.
+  AllArgs[0] = FirstArgResult.get();

This comment doesn't mean anything in the context of the current 
implementation.  If you want to keep something like it (you really don't need 
to), you could have a comment at the top explaining that we use custom 
type-checking because it accepts an arbitrary pointer type as the first 
argument.



Comment at: clang/lib/Sema/SemaChecking.cpp:7695
+TheCall->setArg(i, AllArgs[i]);
+  TheCall->computeDependence();
+

This is really just `TheCall->setArg(i, FirstArgResult.get())`.



Comment at: clang/lib/Sema/SemaChecking.cpp:7701
   // We can't check the value of a dependent argument.
-  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
+  if (!SecondArg->isTypeDependent() && !SecondArg->isValueDependent()) {
 llvm::APSInt Result;

Type-dependence implies value-dependence, so you can just check for the latter.

You should call `convertArgumentToType` with `size_t` in this block, just in 
case the argument is something like an l-value reference to a `const` integer 
variable.



Comment at: clang/lib/Sema/SemaChecking.cpp:7719
+Context, Context.getSizeType(), false);
+ThirdArg = PerformCopyInitialization(Entity, SourceLocation(), ThirdArg);
+if (ThirdArg.isInvalid())

You can use `convertArgumentToType` here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131979

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


[PATCH] D132568: [clang][Sema] check default argument promotions for printf

2022-08-31 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:141
 
+- Implemented `WG14 N2562 
`_.
+  Clang will now consider default argument promotions in printf, and remove 
unnecessary warnings.

It seems a little weird to say we "implemented" this.  The standard doesn't 
require any warnings for misuse of printf etc., and clang doesn't actually 
implement printf, so we don't need to do anything to be standard-compliant.  
I'd just say that we adjusted -Wformat warnings to avoid false positives.



Comment at: clang/lib/Sema/SemaChecking.cpp:10124
+// Consider character literal is a 'char' in C
+// printf("%hd", 'a'); is more likey a type confusion situation
+// We will suggest our users to use %hhd by discarding MatchPromotion

*likely


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132568

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


[PATCH] D132991: [Clang] Give error message for invalid profile path when compiling IR

2022-08-31 Thread Rong Xu via Phabricator via cfe-commits
xur added a comment.

I'm fine with this change.




Comment at: clang/lib/Frontend/CompilerInvocation.cpp:1301
+unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
+"Could not read profile %0: %1");
+llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {

Should we use "Error in reading profile ..."?
Reader still can return error even if the profile can be read.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132991

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


[clang] 66f3e90 - [Driver][test] Test -dumpmachine

2022-08-31 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-08-31T10:31:45-07:00
New Revision: 66f3e90cf8225333273bfaddc1a7f832fe0c263d

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

LOG: [Driver][test] Test -dumpmachine

Added: 
clang/test/Driver/dumpmachine.c

Modified: 


Removed: 




diff  --git a/clang/test/Driver/dumpmachine.c b/clang/test/Driver/dumpmachine.c
new file mode 100644
index 0..41dda5590eb82
--- /dev/null
+++ b/clang/test/Driver/dumpmachine.c
@@ -0,0 +1,12 @@
+/// Test that -dumpmachine prints the target triple.
+
+/// Note: Debian GCC may omit "unknown-".
+// RUN: %clang --target=x86_64-linux-gnu -dumpmachine | FileCheck %s 
--check-prefix=X86_64
+// X86_64: x86_64-unknown-linux-gnu
+
+/// Note: GCC doesn't convert -dumpmachine output for multilib -m32/-mx32/-m64.
+// RUN: %clang --target=x86_64-redhat-linux -m32 -dumpmachine | FileCheck %s 
--check-prefix=X86_64_M32
+// X86_64_M32: i386-redhat-linux
+
+// RUN: %clang --target=xxx-pc-freebsd -dumpmachine | FileCheck %s 
--check-prefix=FREEBSD
+// FREEBSD: xxx-pc-freebsd



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


[PATCH] D131979: [clang][UBSan] Fix __builtin_assume_aligned crash

2022-08-31 Thread Wang Yihan via Phabricator via cfe-commits
yihanaa added a comment.

Thanks for your review John, I'll try to fix these problem later which you 
point out.




Comment at: clang/lib/Sema/SemaChecking.cpp:7659
+   << 0 << 2 << TheCall->getNumArgs() << Callee->getSourceRange();
+  }
+

rjmccall wrote:
> It looks like this should be `if (NumArgs < 2)`.
> 
> We actually have helper functions in this file for doing this kind of 
> arg-count checking, but it looks like we don't have one that takes a range.  
> Could you just generalize `checkArgCount` so that it takes a min and max arg 
> count?  You can make the existing function call your generalization.
It's my fault, I'll fix it, thanks!



Comment at: clang/lib/Sema/SemaChecking.cpp:7671
+ AllArgs, CallType))
+return true;
+

rjmccall wrote:
> You can just pull the argument expressions out of the `CallExpr`; you don't 
> need to call `GatherArgumentsForCall`.
> You can just pull the argument expressions out of the `CallExpr`; you don't 
> need to call `GatherArgumentsForCall`.

This GatherArgumentsForCall  was used to do the common sema checking and emit 
warning, like './main.cpp:5:40: warning: passing 'volatile char *' to parameter 
of type 'const void *' discards qualifiers 
[-Wincompatible-pointer-types-discards-qualifiers]' hahaha, for this is a 
common case, I also think  GatherArgumentsForCall is not a good choice
, so I try to find a replacement, e.g. ImpCastExprToType or other ways, what do 
you think about?



Comment at: clang/lib/Sema/SemaChecking.cpp:7690
+  // cast instruction which cast type from user-written-type to VoidPtr in
+  // CodeGen.
+  AllArgs[0] = FirstArgResult.get();

rjmccall wrote:
> This comment doesn't mean anything in the context of the current 
> implementation.  If you want to keep something like it (you really don't need 
> to), you could have a comment at the top explaining that we use custom 
> type-checking because it accepts an arbitrary pointer type as the first 
> argument.
+1



Comment at: clang/lib/Sema/SemaChecking.cpp:7695
+TheCall->setArg(i, AllArgs[i]);
+  TheCall->computeDependence();
+

rjmccall wrote:
> This is really just `TheCall->setArg(i, FirstArgResult.get())`.
+1



Comment at: clang/lib/Sema/SemaChecking.cpp:7701
   // We can't check the value of a dependent argument.
-  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
+  if (!SecondArg->isTypeDependent() && !SecondArg->isValueDependent()) {
 llvm::APSInt Result;

rjmccall wrote:
> Type-dependence implies value-dependence, so you can just check for the 
> latter.
> 
> You should call `convertArgumentToType` with `size_t` in this block, just in 
> case the argument is something like an l-value reference to a `const` integer 
> variable.
+1



Comment at: clang/lib/Sema/SemaChecking.cpp:7719
+Context, Context.getSizeType(), false);
+ThirdArg = PerformCopyInitialization(Entity, SourceLocation(), ThirdArg);
+if (ThirdArg.isInvalid())

rjmccall wrote:
> You can use `convertArgumentToType` here.
+1


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131979

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


[PATCH] D132952: [Sema] disable -Wvla for function array parameters

2022-08-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D132952#3759731 , @efriedma wrote:

> As a practical matter, there isn't any reason to force variably modified 
> parameters to make a function variably modified.  The types of parameters 
> aren't visible in the caller of a function; we only check the compatibility 
> for calls.

There are constraints in C based on whether something is or isn't a variably 
modified type, so I think there is a reason to make sure we're correct here. 
For example:

  // All at file scope
  int n = 100;
  void func(int array[n++]);
  typedef typeof(func) other_func;

C2x 6.7.8p2: "If a typedef name specifies a variably modified type then it 
shall have block scope." Even more interesting is C2x 6.7.2.5p4 (typeof, which 
is new in C2x): "If the type of the operand is a variably modified type, the 
operand is evaluated; otherwise the operand is not evaluated."

> Trying to treat `void (*)(int, int *)` as variably modified would have 
> additional complications, in that clang would internally need to have two 
> canonical types for `void (*)(int, int *)`: one variably modified, one not 
> variably modified.
>
> So if there's a disagreement between clang and the standard, I'd rather just 
> try to fix the standard.

I'll ask on the WG14 reflectors to see if I'm interpreting the variably 
modified type specification wrong or not.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132952

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


[clang] 74c8d9d - Revert "[clang][dataflow] Generalise match switch utility to other AST types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`."

2022-08-31 Thread Wei Yi Tee via cfe-commits

Author: Wei Yi Tee
Date: 2022-08-31T18:49:56Z
New Revision: 74c8d9d5fc83868977d497c4376296bc27319622

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

LOG: Revert "[clang][dataflow] Generalise match switch utility to other AST 
types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and 
`CFGInitializer`."

This reverts commit c9033eeb2e59c0157b84adfc6b0fe345f6f03113.
https://lab.llvm.org/buildbot#builders/57/builds/21618
Build failure due to comparison between unsigned int and const int
originating from EXPECT_EQ.

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp

Removed: 
clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp



diff  --git a/clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h 
b/clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
deleted file mode 100644
index ecd8558970f93..0
--- a/clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
+++ /dev/null
@@ -1,98 +0,0 @@
-//=== CFGMatchSwitch.h --*- C++ 
-*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-//  This file defines the `CFGMatchSwitch` abstraction for building a "switch"
-//  statement for control flow graph elements. Each case of the switch is
-//  defined by an ASTMatcher which is applied on the AST node contained in the
-//  input `CFGElement`.
-//
-//  Currently, the `CFGMatchSwitch` only handles `CFGElement`s of
-//  `Kind::Statement` and `Kind::Initializer`.
-//
-//===--===//
-
-#ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CFGMATCHSWITCH_H_
-#define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CFGMATCHSWITCH_H_
-
-#include "clang/AST/ASTContext.h"
-#include "clang/AST/Stmt.h"
-#include "clang/Analysis/CFG.h"
-#include "clang/Analysis/FlowSensitive/MatchSwitch.h"
-#include 
-#include 
-
-namespace clang {
-namespace dataflow {
-
-template 
-using CFGMatchSwitch =
-std::function;
-
-/// Collects cases of a "match switch": a collection of matchers paired with
-/// callbacks, which together define a switch that can be applied to an AST 
node
-/// contained in a CFG element.
-template  class CFGMatchSwitchBuilder {
-public:
-  /// Registers an action `A` for `CFGStmt`s that will be triggered by the 
match
-  /// of the pattern `M` against the `Stmt` contained in the input `CFGStmt`.
-  ///
-  /// Requirements:
-  ///
-  ///  `NodeT` should be derived from `Stmt`.
-  template 
-  CFGMatchSwitchBuilder &&
-  CaseOfCFGStmt(MatchSwitchMatcher M,
-MatchSwitchAction A) && {
-std::move(StmtBuilder).template CaseOf(M, A);
-return std::move(*this);
-  }
-
-  /// Registers an action `A` for `CFGInitializer`s that will be triggered by
-  /// the match of the pattern `M` against the `CXXCtorInitializer` contained 
in
-  /// the input `CFGInitializer`.
-  ///
-  /// Requirements:
-  ///
-  ///  `NodeT` should be derived from `CXXCtorInitializer`.
-  template 
-  CFGMatchSwitchBuilder &&
-  CaseOfCFGInit(MatchSwitchMatcher M,
-MatchSwitchAction A) && {
-std::move(InitBuilder).template CaseOf(M, A);
-return std::move(*this);
-  }
-
-  CFGMatchSwitch Build() && {
-return [StmtMS = std::move(StmtBuilder).Build(),
-InitMS = std::move(InitBuilder).Build()](const CFGElement &Element,
- ASTContext &Context,
- State &S) -> Result {
-  switch (Element.getKind()) {
-  case CFGElement::Initializer:
-return InitMS(*Element.castAs().getInitializer(),
-  Context, S);
-  case CFGElement::Statement:
-  case CFGElement::Constructor:
-  case CFGElement::CXXRecordTypedCall:
-return StmtMS(*Element.castAs().getStmt(), Context, S);
-  default:
-// FIXME: Handle other kinds of CFGElement.
-return Result();
-  }
-};
-  }
-
-private:
-  ASTMatchSwitchBuilder StmtBuilder;
-  ASTMatchSwitchBuilder InitBuilder;
-};
-
-} // namespace dataflow
-} // namespace clang
-
-#endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_CFGMATCHSWITCH_H_

diff  --git a/clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h 
b/clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
index 76d18c1d24463..927aec

[PATCH] D131979: [clang][UBSan] Fix __builtin_assume_aligned crash

2022-08-31 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:7671
+ AllArgs, CallType))
+return true;
+

yihanaa wrote:
> rjmccall wrote:
> > You can just pull the argument expressions out of the `CallExpr`; you don't 
> > need to call `GatherArgumentsForCall`.
> > You can just pull the argument expressions out of the `CallExpr`; you don't 
> > need to call `GatherArgumentsForCall`.
> 
> This GatherArgumentsForCall  was used to do the common sema checking and emit 
> warning, like './main.cpp:5:40: warning: passing 'volatile char *' to 
> parameter of type 'const void *' discards qualifiers 
> [-Wincompatible-pointer-types-discards-qualifiers]' hahaha, for this is a 
> common case, I also think  GatherArgumentsForCall is not a good choice
> , so I try to find a replacement, e.g. ImpCastExprToType or other ways, what 
> do you think about?
`convertArgumentToType` should trigger any useful warnings in the second and 
third arguments.  For the first, I don't actually think there are any warnings 
we care about.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131979

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


[PATCH] D132962: [clangd][ObjC] Improve completions for protocols + category names

2022-08-31 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 457049.
dgoldman added a comment.

Add tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132962

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/TestIndex.cpp
  clang-tools-extra/clangd/unittests/TestIndex.h

Index: clang-tools-extra/clangd/unittests/TestIndex.h
===
--- clang-tools-extra/clangd/unittests/TestIndex.h
+++ clang-tools-extra/clangd/unittests/TestIndex.h
@@ -39,6 +39,8 @@
llvm::StringRef USRPrefix);
 // Create an @interface or @implementation.
 Symbol objcClass(llvm::StringRef Name);
+// Create an @interface or @implementation category.
+Symbol objcCategory(llvm::StringRef Name, llvm::StringRef CategoryName);
 // Create an @protocol.
 Symbol objcProtocol(llvm::StringRef Name);
 
Index: clang-tools-extra/clangd/unittests/TestIndex.cpp
===
--- clang-tools-extra/clangd/unittests/TestIndex.cpp
+++ clang-tools-extra/clangd/unittests/TestIndex.cpp
@@ -99,6 +99,11 @@
   return objcSym(Name, index::SymbolKind::Class, "objc(cs)");
 }
 
+Symbol objcCategory(llvm::StringRef Name, llvm::StringRef CategoryName) {
+  std::string USRPrefix = ("objc(cy)" + Name + "@").str();
+  return objcSym(CategoryName, index::SymbolKind::Extension, USRPrefix);
+}
+
 Symbol objcProtocol(llvm::StringRef Name) {
   return objcSym(Name, index::SymbolKind::Protocol, "objc(pl)");
 }
Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -1493,12 +1493,16 @@
 
 class IndexRequestCollector : public SymbolIndex {
 public:
+  IndexRequestCollector(std::vector Syms = {}) : Symbols(Syms) {}
+
   bool
   fuzzyFind(const FuzzyFindRequest &Req,
 llvm::function_ref Callback) const override {
 std::unique_lock Lock(Mut);
 Requests.push_back(Req);
 ReceivedRequestCV.notify_one();
+for (const auto &Sym : Symbols)
+  Callback(Sym);
 return true;
   }
 
@@ -1533,6 +1537,7 @@
   }
 
 private:
+  std::vector Symbols;
   // We need a mutex to handle async fuzzy find requests.
   mutable std::condition_variable ReceivedRequestCV;
   mutable std::mutex Mut;
@@ -3214,8 +3219,74 @@
  {SymFood, FoodClass, SymFooey},
  /*Opts=*/{}, "Foo.m");
 
-  auto C = Results.Completions;
-  EXPECT_THAT(C, UnorderedElementsAre(named("Food"), named("Fooey")));
+  // Should only give protocols for ObjC protocol completions.
+  EXPECT_THAT(Results.Completions,
+  UnorderedElementsAre(
+  AllOf(named("Food"), kind(CompletionItemKind::Interface)),
+  AllOf(named("Fooey"), kind(CompletionItemKind::Interface;
+
+  Results = completions(R"objc(
+  Fo^
+)objc",
+{SymFood, FoodClass, SymFooey},
+/*Opts=*/{}, "Foo.m");
+  // Shouldn't give protocols for non protocol completions.
+  EXPECT_THAT(Results.Completions,
+  ElementsAre(
+  AllOf(named("FoodClass"), kind(CompletionItemKind::Class;
+}
+
+TEST(CompletionTest, ObjectiveCProtocolFromIndexSpeculation) {
+  MockFS FS;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
+
+  auto File = testPath("Foo.m");
+  Annotations Test(R"cpp(
+  @protocol Food
+  @end
+  id foo;
+  )cpp");
+  runAddDocument(Server, File, Test.code());
+  clangd::CodeCompleteOptions Opts = {};
+
+  Symbol FoodClass = objcClass("FoodClass");
+  IndexRequestCollector Requests({FoodClass});
+  Opts.Index = &Requests;
+
+  auto CompleteAtPoint = [&](StringRef P) {
+return cantFail(runCodeComplete(Server, File, Test.point(P), Opts)).Completions;
+  };
+
+  auto C = CompleteAtPoint("1");
+  auto Reqs1 = Requests.consumeRequests(1);
+  ASSERT_EQ(Reqs1.size(), 1u);
+  EXPECT_THAT(C,
+  ElementsAre(
+  AllOf(named("Food"), kind(CompletionItemKind::Interface;
+
+  C = CompleteAtPoint("1");
+  auto Reqs2 = Requests.consumeRequests(1);
+  // Speculation succeeded. Used speculative index result, keeping the same
+  // exact filtering as before to exclude the FoodClass result.
+  ASSERT_EQ(Reqs2.size(), 1u);
+  EXPECT_EQ(Reqs2[0], Reqs1[0]);
+  EXPECT_THAT(C,
+  ElementsAre(
+  AllOf(named("Food"), kind(CompletionItemKind::Interface;
+}
+
+TEST(CompletionTest, ObjectiveCCategoryFromIndexIgnored) {
+  Symbol FoodCategory = objcCategory("FoodClass", "Extension");
+  auto Results = completions(R"objc(
+  @interface Foo
+  @end
+  @interface Foo (^)
+ 

[PATCH] D132962: [clangd][ObjC] Improve completions for protocols + category names

2022-08-31 Thread David Goldman via Phabricator via cfe-commits
dgoldman added a comment.

In D132962#3761463 , @kadircet wrote:

> can you also add test cases for the other two (filtering both for speculative 
> index queries/regular ones, and making sure we don't suggest symbols from 
> index for category names), so that we don't regress in the future?

Done


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132962

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


[PATCH] D131616: [clang][dataflow] Generalise match switch utility to other AST types and add a `CFGMatchSwitch` which currently handles `CFGStmt` and `CFGInitializer`.

2022-08-31 Thread weiyi via Phabricator via cfe-commits
wyt updated this revision to Diff 457052.
wyt added a comment.

Use `u` suffix to declare constants as unsigned in `CFGMatchSwitchTest.cpp`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131616

Files:
  clang/include/clang/Analysis/FlowSensitive/CFGMatchSwitch.h
  clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
  clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
@@ -5,12 +5,6 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-//
-//  This file defines a simplistic version of Constant Propagation as an example
-//  of a forward, monotonic dataflow analysis. The analysis tracks all
-//  variables in the scope, but lacks escape analysis.
-//
-//===--===//
 
 #include "clang/Analysis/FlowSensitive/MatchSwitch.h"
 #include "TestingSupport.h"
Index: clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
===
--- clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
+++ clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
@@ -4,6 +4,7 @@
   )
 
 add_clang_unittest(ClangAnalysisFlowSensitiveTests
+  CFGMatchSwitchTest.cpp
   ChromiumCheckModelTest.cpp
   DataflowAnalysisContextTest.cpp
   DataflowEnvironmentTest.cpp
Index: clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp
@@ -0,0 +1,124 @@
+//===- unittests/Analysis/FlowSensitive/CFGMatchSwitchTest.cpp ===//
+//
+// 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 "clang/Analysis/FlowSensitive/CFGMatchSwitch.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/StringRef.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace dataflow;
+using namespace ast_matchers;
+
+namespace {
+// State for tracking the number of matches on each kind of CFGElement by the
+// CFGMatchSwitch. Currently only tracks CFGStmt and CFGInitializer.
+struct CFGElementMatches {
+  unsigned StmtMatches = 0;
+  unsigned InitializerMatches = 0;
+};
+
+// Returns a match switch that counts the number of local variables
+// (singly-declared) and fields initialized to the integer literal 42.
+auto buildCFGMatchSwitch() {
+  return CFGMatchSwitchBuilder()
+  .CaseOfCFGStmt(
+  declStmt(hasSingleDecl(
+  varDecl(hasInitializer(integerLiteral(equals(42)),
+  [](const DeclStmt *, const MatchFinder::MatchResult &,
+ CFGElementMatches &Counter) { Counter.StmtMatches++; })
+  .CaseOfCFGInit(
+  cxxCtorInitializer(withInitializer(integerLiteral(equals(42,
+  [](const CXXCtorInitializer *, const MatchFinder::MatchResult &,
+ CFGElementMatches &Counter) { Counter.InitializerMatches++; })
+  .Build();
+}
+
+// Runs the match switch `MS` on the control flow graph generated from `Code`,
+// tracking information in state `S`. For simplicity, this test utility is
+// restricted to CFGs with a single control flow block (excluding entry and
+// exit blocks) - generated by `Code` with sequential flow (i.e. no branching).
+//
+// Requirements:
+//
+//  `Code` must contain a function named `f`, the body of this function will be
+//  used to generate the CFG.
+template 
+void applySwitchToCode(CFGMatchSwitch &MS, State &S,
+   llvm::StringRef Code) {
+  auto Unit = tooling::buildASTFromCodeWithArgs(Code, {"-Wno-unused-value"});
+  auto &Ctx = Unit->getASTContext();
+  const auto *F = selectFirst(
+  "f", match(functionDecl(isDefinition(), hasName("f")).bind("f"), Ctx));
+
+  CFG::BuildOptions BO;
+  BO.AddInitializers = true;
+
+  auto CFG = CFG::buildCFG(F, F->getBody(), &Ctx, BO);
+  auto CFGBlock = *CFG->getEntry().succ_begin();
+  for (auto &Elt : CFGBlock->Elements) {
+MS(Elt, Ctx, S);
+  }
+}
+
+TEST(CFGMatchSwitchTest, NoInitializationTo42) {
+  CFGMatchSwitch Switch = buildCFGMatchSwitch();
+  CFGElementMatches Counter;
+  applySwi

[clang] cdf3de4 - [CodeGen] fix misnamed "not" operation; NFC

2022-08-31 Thread Sanjay Patel via cfe-commits

Author: Sanjay Patel
Date: 2022-08-31T15:11:48-04:00
New Revision: cdf3de45d282694290011a2949bdcc61cabb47ef

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

LOG: [CodeGen] fix misnamed "not" operation; NFC

Seeing the wrong instruction for this name in IR is confusing.
Most of the tests are not even checking a subsequent use of
the value, so I just deleted the over-specified CHECKs.

Added: 


Modified: 
clang/lib/CodeGen/CGExprScalar.cpp
clang/test/CodeGen/PowerPC/builtins-ppc-p10vector.c
clang/test/CodeGen/X86/avx512f-builtins.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 9def1285fbc1d..a724f8b6afd76 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -2904,7 +2904,7 @@ Value *ScalarExprEmitter::VisitMinus(const UnaryOperator 
*E,
 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
   TestAndClearIgnoreResultAssign();
   Value *Op = Visit(E->getSubExpr());
-  return Builder.CreateNot(Op, "neg");
+  return Builder.CreateNot(Op, "not");
 }
 
 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {

diff  --git a/clang/test/CodeGen/PowerPC/builtins-ppc-p10vector.c 
b/clang/test/CodeGen/PowerPC/builtins-ppc-p10vector.c
index 694d2795d335b..312b5fe1894ea 100644
--- a/clang/test/CodeGen/PowerPC/builtins-ppc-p10vector.c
+++ b/clang/test/CodeGen/PowerPC/builtins-ppc-p10vector.c
@@ -1863,15 +1863,15 @@ vector bool __int128 test_vec_cmpeq_bool_int128(void) {
 vector bool __int128 test_vec_cmpne_s128(void) {
   // CHECK-LABEL: @test_vec_cmpne_s128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpequq(<1 x i128>
-  // CHECK-NEXT: %neg.i = xor <1 x i128> %4, 
-  // CHECK-NEXT: ret <1 x i128> %neg.i
+  // CHECK-NEXT: %not.i = xor <1 x i128> %4, 
+  // CHECK-NEXT: ret <1 x i128> %not.i
   return vec_cmpne(vsi128a, vsi128b);
 }
 
 vector bool __int128 test_vec_cmpne_u128(void) {
   // CHECK-LABEL: @test_vec_cmpne_u128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpequq(<1 x i128>
-  // CHECK-NEXT: %neg.i = xor <1 x i128> %4, 
+  // CHECK-NEXT: xor <1 x i128> %4, 
   // CHECK-NEXT: ret <1 x i128>
   return vec_cmpne(vui128a, vui128b);
 }
@@ -1879,7 +1879,7 @@ vector bool __int128 test_vec_cmpne_u128(void) {
 vector bool __int128 test_vec_cmpne_bool_int128(void) {
   // CHECK-LABEL: @test_vec_cmpne_bool_int128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpequq(<1 x i128>
-  // CHECK-NEXT: %neg.i = xor <1 x i128> %4, 
+  // CHECK-NEXT: xor <1 x i128> %4, 
   // CHECK-NEXT: ret <1 x i128>
   return vec_cmpne(vbi128a, vbi128b);
 }
@@ -1915,7 +1915,7 @@ vector bool __int128 test_vec_cmplt_u128(void) {
 vector bool __int128 test_vec_cmpge_s128(void) {
   // CHECK-LABEL: @test_vec_cmpge_s128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpgtsq(<1 x i128>
-  // CHECK-NEXT: %neg.i = xor <1 x i128> %6, 
+  // CHECK-NEXT: xor <1 x i128> %6, 
   // CHECK-NEXT: ret <1 x i128>
   return vec_cmpge(vsi128a, vsi128b);
 }
@@ -1923,7 +1923,7 @@ vector bool __int128 test_vec_cmpge_s128(void) {
 vector bool __int128 test_vec_cmpge_u128(void) {
   // CHECK-LABEL: @test_vec_cmpge_u128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpgtuq(<1 x i128>
-  // CHECK-NEXT: %neg.i = xor <1 x i128> %6, 
+  // CHECK-NEXT: xor <1 x i128> %6, 
   // CHECK-NEXT: ret <1 x i128>
   return vec_cmpge(vui128a, vui128b);
 }
@@ -1931,7 +1931,7 @@ vector bool __int128 test_vec_cmpge_u128(void) {
 vector bool __int128 test_vec_cmple_s128(void) {
   // CHECK-LABEL: @test_vec_cmple_s128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpgtsq(<1 x i128>
-  // CHECK-NEXT: %neg.i.i = xor <1 x i128> %8, 
+  // CHECK-NEXT: xor <1 x i128> %8, 
   // CHECK-NEXT: ret <1 x i128>
   return vec_cmple(vsi128a, vsi128b);
 }
@@ -1939,7 +1939,7 @@ vector bool __int128 test_vec_cmple_s128(void) {
 vector bool __int128 test_vec_cmple_u128(void) {
   // CHECK-LABEL: @test_vec_cmple_u128(
   // CHECK: call <1 x i128> @llvm.ppc.altivec.vcmpgtuq(<1 x i128>
-  // CHECK-NEXT: %neg.i.i = xor <1 x i128> %8, 
+  // CHECK-NEXT: xor <1 x i128> %8, 
   // CHECK-NEXT: ret <1 x i128>
   return vec_cmple(vui128a, vui128b);
 }

diff  --git a/clang/test/CodeGen/X86/avx512f-builtins.c 
b/clang/test/CodeGen/X86/avx512f-builtins.c
index a803bcfff156c..8a0c273415275 100644
--- a/clang/test/CodeGen/X86/avx512f-builtins.c
+++ b/clang/test/CodeGen/X86/avx512f-builtins.c
@@ -2866,9 +2866,9 @@ __m512i test_mm512_andnot_si512(__m512i __A, __m512i __B)
 {
   //CHECK-LABEL: @test_mm512_andnot_si512
   //CHECK: load {{.*}}%__A.addr.i, align 64
-  //CHECK: %neg.i = xor{{.*}}, 
+  //CHECK: %not.i = xor{{.*}}, 
   //CHECK: load {{.*}}%__B.addr.i, align 64
-  //CHECK: and <8 x i64> %neg.i,{{.*}}
+  //CHECK: and <8 x i64> %not.i,{{

[PATCH] D132421: [HLSL] Support PCH for cc1 mode

2022-08-31 Thread Xiang Li via Phabricator via cfe-commits
python3kgae added inline comments.



Comment at: clang/lib/Sema/HLSLExternalSemaSource.cpp:297
+  }
+
   IdentifierInfo &HLSL = AST.Idents.get("hlsl", tok::TokenKind::identifier);

beanz wrote:
> I think the core of what you'e doing here is not far off, but I think this 
> pattern doesn't scale or cover all the use cases that matter.
> 
> The cases that come to my mind are:
> 1) PCH has a forward declaration, source doesn't use the type so we shouldn't 
> complete the type.
> 2) PCH has a forward declaration, source uses the type, so we need to 
> generate a complete decl.
> 3) PCH has a complete declaration, so we should re-use the declaration and 
> not need to do anything.
> 
> We also need to keep in mind that we're going to keep adding more and more 
> types, so this pattern where each new type needs to add code to lookup is 
> going to be a challenge. It is also going to be a challenge to manage the 
> complexity of PCH defines one thing but not another.
> 
> One thing you should look at is how clang handles the following C++ code:
> 
> ```
> template
> class Foo;
> 
> template
> class Foo {
>   T Val;
> };
> ```
> 
> This results in two decls. One for the forward decl and the second for the 
> definition. The definition lists the forward declaration as the previous 
> decl. We should do that here.
> 
> When we generate the HLSL namespace, we can do a lookup and if we find a 
> previous decl, set the previous decl.
> 
> When we generate any of the builtin types, we can lookup the previous decl, 
> and annotate as the previous decl. We'll can also handle the case where a 
> decl from the PCH is complete. If the PCH provides a complete decl, we can 
> skip generating any decls for it, and the lookups should just work.
Set previous decl not work.
It goes to "For most kinds of declaration, it doesn't really matter which one 
we pick." before checking PreviousDecl.


```
   // For most kinds of declaration, it doesn't really matter which one we pick.
  if (!isa(DUnderlying) && !isa(DUnderlying)) {
// If the existing declaration is hidden, prefer the new one. Otherwise,
// keep what we've got.
return !S.isVisible(Existing);
  }



  // Pick the newer declaration; it might have a more precise type.
  for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
   Prev = Prev->getPreviousDecl())
if (Prev == EUnderlying)
  return true;
  return false;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132421

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


[clang] 41b1c9f - Re-add the REQUIRES line to fix a failed build on builder llvm-clang-win-x-aarch64.

2022-08-31 Thread Ying Yi via cfe-commits

Author: Ying Yi
Date: 2022-08-31T20:22:18+01:00
New Revision: 41b1c9ff70142dc38a381517718cd3f95e8d62b7

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

LOG: Re-add the REQUIRES line to fix a failed build on builder 
llvm-clang-win-x-aarch64.

Added: 


Modified: 
clang/test/Driver/ps4-ps5-header-search.c

Removed: 




diff  --git a/clang/test/Driver/ps4-ps5-header-search.c 
b/clang/test/Driver/ps4-ps5-header-search.c
index 6762c707dde6..6848901df559 100644
--- a/clang/test/Driver/ps4-ps5-header-search.c
+++ b/clang/test/Driver/ps4-ps5-header-search.c
@@ -1,3 +1,5 @@
+// REQUIRES: x86-registered-target
+
 /// PS4 and PS5 use the same SDK layout, so use the same tree for both.
 // RUN: env SCE_ORBIS_SDK_DIR=%S/Inputs/scei-ps4_tree %clang -target 
x86_64-scei-ps4 -E -v %s 2>&1 | FileCheck %s --check-prefix=ENVPS4
 // RUN: env SCE_PROSPERO_SDK_DIR=%S/Inputs/scei-ps4_tree %clang -target 
x86_64-sie-ps5 -E -v %s 2>&1 | FileCheck %s --check-prefix=ENVPS4



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


[PATCH] D133043: [clangd] Fix tests for implicit C function declaration

2022-08-31 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX created this revision.
ArcsinX added reviewers: aaron.ballman, sammccall, kadircet.
Herald added a subscriber: arphaman.
Herald added a project: All.
ArcsinX requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

clangd code fixes at D122983  were not right.
We need to check that clangd provides IncludeFixer fixits for implicit function 
declaration even if this is not an error (e.g. implicit function declaration in 
C89).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133043

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


Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1465,11 +1465,12 @@
 TEST(IncludeFixerTest, HeaderNamedInDiag) {
   Annotations Test(R"cpp(
 $insert[[]]int main() {
-  [[printf]](""); // error-ok
+  [[printf]]("");
 }
   )cpp");
   auto TU = TestTU::withCode(Test.code());
-  TU.ExtraArgs = {"-xc"};
+  TU.ExtraArgs = {"-xc", "-std=c99",
+  "-Wno-error=implicit-function-declaration"};
   auto Index = buildIndexWithSymbol({});
   TU.ExternalIndex = Index.get();
 
@@ -1482,13 +1483,22 @@
  "declarations"),
   withFix(Fix(Test.range("insert"), "#include \n",
   "Include  for symbol printf");
+
+  TU.ExtraArgs = {"-xc", "-std=c89"};
+  EXPECT_THAT(
+  *TU.build().getDiagnostics(),
+  ElementsAre(AllOf(
+  Diag(Test.range(), "implicitly declaring library function 'printf' "
+ "with type 'int (const char *, ...)'"),
+  withFix(Fix(Test.range("insert"), "#include \n",
+  "Include  for symbol printf");
 }
 
 TEST(IncludeFixerTest, CImplicitFunctionDecl) {
-  Annotations Test("void x() { [[foo]](); /* error-ok */ }");
+  Annotations Test("void x() { [[foo]](); }");
   auto TU = TestTU::withCode(Test.code());
   TU.Filename = "test.c";
-  TU.ExtraArgs.push_back("-std=c99");
+  TU.ExtraArgs = {"-std=c99", "-Wno-error=implicit-function-declaration"};
 
   Symbol Sym = func("foo");
   Sym.Flags |= Symbol::IndexedForCodeCompletion;
@@ -1509,6 +1519,13 @@
"support implicit function declarations"),
   withFix(Fix(Range{}, "#include \"foo.h\"\n",
   "Include \"foo.h\" for symbol foo");
+
+  TU.ExtraArgs = {"-std=c89", "-Wall"};
+  EXPECT_THAT(*TU.build().getDiagnostics(),
+  ElementsAre(AllOf(
+  Diag(Test.range(), "implicit declaration of function 'foo'"),
+  withFix(Fix(Range{}, "#include \"foo.h\"\n",
+  "Include \"foo.h\" for symbol foo");
 }
 
 TEST(DiagsInHeaders, DiagInsideHeader) {
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -493,6 +493,7 @@
 // We restore the original severity in the level adjuster.
 // FIXME: It would be better to have a real API for this, but what?
 for (auto ID : {diag::ext_implicit_function_decl_c99,
+diag::ext_implicit_lib_function_decl,
 diag::ext_implicit_lib_function_decl_c99,
 diag::warn_implicit_function_decl}) {
   OverriddenSeverity.try_emplace(


Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1465,11 +1465,12 @@
 TEST(IncludeFixerTest, HeaderNamedInDiag) {
   Annotations Test(R"cpp(
 $insert[[]]int main() {
-  [[printf]](""); // error-ok
+  [[printf]]("");
 }
   )cpp");
   auto TU = TestTU::withCode(Test.code());
-  TU.ExtraArgs = {"-xc"};
+  TU.ExtraArgs = {"-xc", "-std=c99",
+  "-Wno-error=implicit-function-declaration"};
   auto Index = buildIndexWithSymbol({});
   TU.ExternalIndex = Index.get();
 
@@ -1482,13 +1483,22 @@
  "declarations"),
   withFix(Fix(Test.range("insert"), "#include \n",
   "Include  for symbol printf");
+
+  TU.ExtraArgs = {"-xc", "-std=c89"};
+  EXPECT_THAT(
+  *TU.build().getDiagnostics(),
+  ElementsAre(AllOf(
+  Diag(Test.range(), "implicitly declaring library function 'printf' "
+ "with type 'int (const char *, ...)'"),
+  withFix(Fix(Test.range("insert"), "#include \n",
+  "Include  for symbol printf");
 }
 
 TEST(IncludeFixerTest, CImplicitFu

[PATCH] D132998: [clang-tidy] Restrict use-equals-default to c++11-or-later

2022-08-31 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

In D132998#3760603 , 
@alexander-shaposhnikov wrote:

> My assumption was that a codebase needs to compile with c++11 in the first 
> place - otherwise the automatic fixit will break the build (as it happens 
> right now).
> I was looking at modernize/UseOverrideCheck.h - it requires c++11 and this 
> seemed to be quite natural.

There may be cases when the code needs to be "modernized" to compile in C++11 
mode. But I can only recall some uses of NULL and the corresponding 
modernize-use-nullptr check. In other cases one can switch compiler options 
first and then apply clang-tidy fixes. That has a benefit of being able to 
apply fixes incrementally and is probably a more convenient approach.

This patch would likely make it more convenient to use clang-tidy in codebases 
with mixed C++ standards. I'm not sure whether it's an important or even 
practical use case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132998

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


[PATCH] D133044: [Frontend] Restore Preprocessor::getPredefines()

2022-08-31 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson created this revision.
Herald added a subscriber: kristof.beyls.
Herald added a project: All.
royjacobson requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

A patch from May removed Preprocessor::getPredefines() from Clang's API, 
probably as a cleanup because
this method was unused in the LLVM codebase.

However, it was/is used by a small number of third-party tools and is pretty 
harmless, so this patch adds it back
and documents why it's here.

The issue was raised in https://github.com/llvm/llvm-project/issues/57483, it 
would be nice to be able to
land it into Clang 15 as it breaks those third-party tools and we can't easily 
add it back in bug fix releases.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D133044

Files:
  clang/include/clang/Lex/Preprocessor.h


Index: clang/include/clang/Lex/Preprocessor.h
===
--- clang/include/clang/Lex/Preprocessor.h
+++ clang/include/clang/Lex/Preprocessor.h
@@ -1375,6 +1375,10 @@
   StringRef getLastMacroWithSpelling(SourceLocation Loc,
  ArrayRef Tokens) const;
 
+  /// Get the predefines for this processor.
+  /// Used by some third-party tools to inspect and add predefines.
+  const std::string &getPredefines() const { return Predefines; }
+
   /// Set the predefines for this Preprocessor.
   ///
   /// These predefines are automatically injected when parsing the main file.


Index: clang/include/clang/Lex/Preprocessor.h
===
--- clang/include/clang/Lex/Preprocessor.h
+++ clang/include/clang/Lex/Preprocessor.h
@@ -1375,6 +1375,10 @@
   StringRef getLastMacroWithSpelling(SourceLocation Loc,
  ArrayRef Tokens) const;
 
+  /// Get the predefines for this processor.
+  /// Used by some third-party tools to inspect and add predefines.
+  const std::string &getPredefines() const { return Predefines; }
+
   /// Set the predefines for this Preprocessor.
   ///
   /// These predefines are automatically injected when parsing the main file.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133044: [Frontend] Restore Preprocessor::getPredefines()

2022-08-31 Thread Brad King via Phabricator via cfe-commits
brad.king accepted this revision.
brad.king added a comment.
This revision is now accepted and ready to land.

LGTM.  After applying this patch locally on top of the release/15.x branch, 
CastXML builds again.   Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133044

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


[PATCH] D133044: [Frontend] Restore Preprocessor::getPredefines()

2022-08-31 Thread Tobias Hieta via Phabricator via cfe-commits
thieta accepted this revision.
thieta added a comment.

LGTM and seems pretty safe so I am not opposed to merge it before 15 final.

I would maybe add a link to the GitHub issue in the comment, but that's a nit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133044

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


  1   2   >