[clang] 1d7b59c - [clang][dataflow] Fix two null pointer dereferences in `getMemberForAccessor()`. (#66742)

2023-09-19 Thread via cfe-commits

Author: martinboehme
Date: 2023-09-19T09:03:20+02:00
New Revision: 1d7b59ca8ddb0b189a036a8f7e26f7e6deb73038

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

LOG: [clang][dataflow] Fix two null pointer dereferences in 
`getMemberForAccessor()`. (#66742)

The additions to the test trigger crashes without the fixes.

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 26e097349057238..9dc528567038ac4 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -289,11 +289,14 @@ static void insertIfFunction(const Decl &D,
 }
 
 static MemberExpr *getMemberForAccessor(const CXXMemberCallExpr &C) {
+  if (!C.getMethodDecl())
+return nullptr;
   auto *Body = dyn_cast_or_null(C.getMethodDecl()->getBody());
   if (!Body || Body->size() != 1)
 return nullptr;
   if (auto *RS = dyn_cast(*Body->body_begin()))
-return dyn_cast(RS->getRetValue()->IgnoreParenImpCasts());
+if (auto *Return = RS->getRetValue())
+  return dyn_cast(Return->IgnoreParenImpCasts());
   return nullptr;
 }
 

diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index 14188f5acd5b36e..e8cbca756460369 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -1463,6 +1463,7 @@ TEST(TransferTest, StructModeledFieldsWithAccessor) {
   int getIntNotAccessed() const { return IntNotAccessed; }
   int getIntNoDefinition() const;
   int &getIntRef() { return IntRef; }
+  void returnVoid() const { return; }
 };
 
 void target() {
@@ -1473,6 +1474,14 @@ TEST(TransferTest, StructModeledFieldsWithAccessor) {
   int i2 = s.getWithInc(1);
   int i3 = s.getIntNoDefinition();
   int &iref = s.getIntRef();
+
+  // Regression test: Don't crash on an indirect call (which doesn't have
+  // an associated `CXXMethodDecl`).
+  auto ptr_to_member_fn = &S::getPtr;
+  p1 = (s.*ptr_to_member_fn)();
+
+  // Regression test: Don't crash on a return statement without a value.
+  s.returnVoid();
   // [[p]]
 }
   )";



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


[clang] [clang][dataflow] Fix two null pointer dereferences in `getMemberForAccessor()`. (PR #66742)

2023-09-19 Thread via cfe-commits

https://github.com/martinboehme closed 
https://github.com/llvm/llvm-project/pull/66742
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [InstCombine] Canonicalize `and(zext(A), B)` into `select A, B & 1, 0` (PR #66740)

2023-09-19 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

> We should use rebase instead of merge. And I recommend force push to change 
> the code before the review starts.

I am confused with the LLVM GitHub user guide. I witnessed someone mess up by 
doing rebase + force push.
Examples: #65853 #65543 #65535


https://github.com/llvm/llvm-project/pull/66740
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D159519: [clang][AST][ASTImporter] improve AST comparasion on VarDecl & GotoStmt

2023-09-19 Thread Qizhi Hu via Phabricator via cfe-commits
jcsxky added a comment.

ping~ @donat.nagy  @steakhal  @balazske


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159519

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


[clang] [NFC][Clang][Headers] Update refs to ACLE in comments (PR #66662)

2023-09-19 Thread Kristof Beyls via cfe-commits


@@ -20,8 +20,8 @@
 extern "C" {

kbeyls wrote:

Thanks, all of these updates look correct to me.
Since these all refer to sections in a document, I think it may be useful too 
to add a hyperlink at the top of the document to where the ACLE lives.
I think the correct hyperlink would be 
https://github.com/ARM-software/acle/releases/.

@vhscampos Do you think that would be a good idea too?

https://github.com/llvm/llvm-project/pull/2
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][Clang][Headers] Update refs to ACLE in comments (PR #66662)

2023-09-19 Thread Victor Campos via cfe-commits


@@ -20,8 +20,8 @@
 extern "C" {

vhscampos wrote:

Thanks @Blue-Dot for the patch. I agree with @kbeyls that it would be a good 
idea.

https://github.com/llvm/llvm-project/pull/2
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D117181: [PowerPC] Use IEEE long double in proper toolchain

2023-09-19 Thread Qiu Chaofan via Phabricator via cfe-commits
qiucf abandoned this revision.
qiucf added a comment.

Determining float ABI by system library without explicit options may cause 
confusion. Since Fedora has successfully switched using ieeelongdouble on 
ppc64le 
(https://developers.redhat.com/articles/2023/05/16/benefits-fedora-38-long-double-transition-ppc64le
 ), this patch is not so relevant.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117181

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


[PATCH] D116016: [Clang] [PowerPC] Emit module flag for current float abi

2023-09-19 Thread Qiu Chaofan via Phabricator via cfe-commits
qiucf added a comment.

Gentle ping?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116016

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


[clang] [clang][Driver] Obey -fuse-ld=... for -print-prog-name=ld output (PR #66698)

2023-09-19 Thread Petr Hosek via cfe-commits

petrhosek wrote:

To give you a concrete example, I recently encountered this issue when 
compiling [libffi](https://github.com/libffi/libffi).

https://github.com/llvm/llvm-project/pull/66698
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][Clang][Headers] Update refs to ACLE in comments (PR #66662)

2023-09-19 Thread David Spickett via cfe-commits

https://github.com/DavidSpickett edited 
https://github.com/llvm/llvm-project/pull/2
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][Clang][Headers] Update refs to ACLE in comments (PR #66662)

2023-09-19 Thread David Spickett via cfe-commits

https://github.com/DavidSpickett commented:

If these section refs weren't already here I'd suggest not adding numbers at 
all given that they will change later, and Firefox and Chrome seem hopeless at 
searching for them in the HTML document.

But we have them already so I won't suggest that :) Thanks for taking the time 
to do this.

https://github.com/llvm/llvm-project/pull/2
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][Clang][Headers] Update refs to ACLE in comments (PR #66662)

2023-09-19 Thread David Spickett via cfe-commits


@@ -32,7 +32,7 @@ extern "C" {
 #define __isb(i) __builtin_arm_isb(i)
 #endif
 
-/* 8.4 Hints */
+/* 7.4 Hints */

DavidSpickett wrote:

If we're matching the section titles then they should have the extra `.` on the 
end of the number, so here `7.4. Hints`. Just to make searching more obvious.

Though in Firefox and Chrome they struggled to find it but that's down to the 
HTML formatting I think. At least visually it'll match up.

https://github.com/llvm/llvm-project/pull/2
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [NFC][Clang][Headers] Update refs to ACLE in comments (PR #66662)

2023-09-19 Thread David Spickett via cfe-commits


@@ -20,8 +20,8 @@
 extern "C" {

DavidSpickett wrote:

You may want to note that section numbers were correct at time of writing, if 
they've changed then look for the section title.

https://github.com/llvm/llvm-project/pull/2
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][dataflow] Identify post-visit state changes in the HTML logger. (PR #66746)

2023-09-19 Thread via cfe-commits

https://github.com/martinboehme created 
https://github.com/llvm/llvm-project/pull/66746

Previously, post-visit state changes were indistinguishable from ordinary
iterations, which could give a confusing picture of how many iterations a block
needs to converge.

Now, post-visit state changes are marked with "post-visit" instead of an
iteration number (see attached screenshot for an example).


>From a1b224d2f2aabb6dd60946b442647c5edcebd15c Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Tue, 19 Sep 2023 07:54:22 +
Subject: [PATCH] [clang][dataflow] Identify post-visit state changes in the
 HTML logger.

Previously, post-visit state changes were indistinguishable from ordinary
iterations, which could give a confusing picture of how many iterations a block
needs to converge.

Now, post-visit state changes are marked with "post-visit" instead of an
iteration number (see attached screenshot for an example).
---
 .../clang/Analysis/FlowSensitive/Logger.h |  4 +-
 .../lib/Analysis/FlowSensitive/HTMLLogger.cpp | 41 ++-
 .../Analysis/FlowSensitive/HTMLLogger.html| 19 ++---
 clang/lib/Analysis/FlowSensitive/Logger.cpp   | 10 +++--
 .../TypeErasedDataflowAnalysis.cpp|  2 +-
 5 files changed, 55 insertions(+), 21 deletions(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/Logger.h 
b/clang/include/clang/Analysis/FlowSensitive/Logger.h
index 6836488003a97de..f4bd39f6ed49ef7 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Logger.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Logger.h
@@ -50,7 +50,9 @@ class Logger {
   /// Called when we start (re-)processing a block in the CFG.
   /// The target program point is the entry to the specified block.
   /// Calls to log() describe transferBranch(), join() etc.
-  virtual void enterBlock(const CFGBlock &) {}
+  /// `PostVisit` specifies whether we're processing the block for the
+  /// post-visit callback.
+  virtual void enterBlock(const CFGBlock &, bool PostVisit) {}
   /// Called when we start processing an element in the current CFG block.
   /// The target program point is after the specified element.
   /// Calls to log() describe the transfer() function.
diff --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
index a5f64021eb6ba4b..47915958750d1f4 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
@@ -146,15 +146,21 @@ class ModelDumper {
 };
 
 class HTMLLogger : public Logger {
+  struct Iteration {
+const CFGBlock *Block;
+unsigned Iter;
+bool PostVisit;
+  };
+
   StreamFactory Streams;
   std::unique_ptr OS;
   std::optional JOS;
 
   const ControlFlowContext *CFG;
   // Timeline of iterations of CFG block visitation.
-  std::vector> Iters;
+  std::vector Iters;
   // Number of times each CFG block has been seen.
-  llvm::DenseMap BlockIters;
+  llvm::DenseMap> BlockIters;
   // The messages logged in the current context but not yet written.
   std::string ContextLogs;
   // The number of elements we have visited within the current CFG block.
@@ -198,8 +204,9 @@ class HTMLLogger : public Logger {
 JOS->attributeArray("timeline", [&] {
   for (const auto &E : Iters) {
 JOS->object([&] {
-  JOS->attribute("block", blockID(E.first->getBlockID()));
-  JOS->attribute("iter", E.second);
+  JOS->attribute("block", blockID(E.Block->getBlockID()));
+  JOS->attribute("iter", E.Iter);
+  JOS->attribute("post_visit", E.PostVisit);
 });
   }
 });
@@ -214,8 +221,11 @@ class HTMLLogger : public Logger {
 *OS << llvm::StringRef(HTMLLogger_html).split("").second;
   }
 
-  void enterBlock(const CFGBlock &B) override {
-Iters.emplace_back(&B, ++BlockIters[&B]);
+  void enterBlock(const CFGBlock &B, bool PostVisit) override {
+llvm::SmallVector &BIter = BlockIters[&B];
+unsigned IterNum = BIter.size() + 1;
+BIter.push_back({&B, IterNum, PostVisit});
+Iters.push_back({&B, IterNum, PostVisit});
 ElementIndex = 0;
   }
   void enterElement(const CFGElement &E) override {
@@ -243,17 +253,19 @@ class HTMLLogger : public Logger {
   //  - meaningful names for values
   //  - which boolean values are implied true/false by the flow condition
   void recordState(TypeErasedDataflowAnalysisState &State) override {
-unsigned Block = Iters.back().first->getBlockID();
-unsigned Iter = Iters.back().second;
+unsigned Block = Iters.back().Block->getBlockID();
+unsigned Iter = Iters.back().Iter;
+bool PostVisit = Iters.back().PostVisit;
 JOS->attributeObject(elementIterID(Block, Iter, ElementIndex), [&] {
   JOS->attribute("block", blockID(Block));
   JOS->attribute("iter", Iter);
+  JOS->attribute("post_visit", PostVisit);
   JOS->attribute("element", ElementIndex);
 
   // If this state immediately follows an Expr, show its built-in model.
   if (Ele

[clang] [clang][dataflow] Identify post-visit state changes in the HTML logger. (PR #66746)

2023-09-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-analysis


Changes

Previously, post-visit state changes were indistinguishable from ordinary
iterations, which could give a confusing picture of how many iterations a block
needs to converge.

Now, post-visit state changes are marked with "post-visit" instead of an
iteration number (see attached screenshot for an example).


---
Full diff: https://github.com/llvm/llvm-project/pull/66746.diff


5 Files Affected:

- (modified) clang/include/clang/Analysis/FlowSensitive/Logger.h (+3-1) 
- (modified) clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp (+30-11) 
- (modified) clang/lib/Analysis/FlowSensitive/HTMLLogger.html (+14-5) 
- (modified) clang/lib/Analysis/FlowSensitive/Logger.cpp (+7-3) 
- (modified) clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp 
(+1-1) 


``diff
diff --git a/clang/include/clang/Analysis/FlowSensitive/Logger.h 
b/clang/include/clang/Analysis/FlowSensitive/Logger.h
index 6836488003a97de..f4bd39f6ed49ef7 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Logger.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Logger.h
@@ -50,7 +50,9 @@ class Logger {
   /// Called when we start (re-)processing a block in the CFG.
   /// The target program point is the entry to the specified block.
   /// Calls to log() describe transferBranch(), join() etc.
-  virtual void enterBlock(const CFGBlock &) {}
+  /// `PostVisit` specifies whether we're processing the block for the
+  /// post-visit callback.
+  virtual void enterBlock(const CFGBlock &, bool PostVisit) {}
   /// Called when we start processing an element in the current CFG block.
   /// The target program point is after the specified element.
   /// Calls to log() describe the transfer() function.
diff --git a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp 
b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
index a5f64021eb6ba4b..47915958750d1f4 100644
--- a/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
+++ b/clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
@@ -146,15 +146,21 @@ class ModelDumper {
 };
 
 class HTMLLogger : public Logger {
+  struct Iteration {
+const CFGBlock *Block;
+unsigned Iter;
+bool PostVisit;
+  };
+
   StreamFactory Streams;
   std::unique_ptr OS;
   std::optional JOS;
 
   const ControlFlowContext *CFG;
   // Timeline of iterations of CFG block visitation.
-  std::vector> Iters;
+  std::vector Iters;
   // Number of times each CFG block has been seen.
-  llvm::DenseMap BlockIters;
+  llvm::DenseMap> BlockIters;
   // The messages logged in the current context but not yet written.
   std::string ContextLogs;
   // The number of elements we have visited within the current CFG block.
@@ -198,8 +204,9 @@ class HTMLLogger : public Logger {
 JOS->attributeArray("timeline", [&] {
   for (const auto &E : Iters) {
 JOS->object([&] {
-  JOS->attribute("block", blockID(E.first->getBlockID()));
-  JOS->attribute("iter", E.second);
+  JOS->attribute("block", blockID(E.Block->getBlockID()));
+  JOS->attribute("iter", E.Iter);
+  JOS->attribute("post_visit", E.PostVisit);
 });
   }
 });
@@ -214,8 +221,11 @@ class HTMLLogger : public Logger {
 *OS << llvm::StringRef(HTMLLogger_html).split("").second;
   }
 
-  void enterBlock(const CFGBlock &B) override {
-Iters.emplace_back(&B, ++BlockIters[&B]);
+  void enterBlock(const CFGBlock &B, bool PostVisit) override {
+llvm::SmallVector &BIter = BlockIters[&B];
+unsigned IterNum = BIter.size() + 1;
+BIter.push_back({&B, IterNum, PostVisit});
+Iters.push_back({&B, IterNum, PostVisit});
 ElementIndex = 0;
   }
   void enterElement(const CFGElement &E) override {
@@ -243,17 +253,19 @@ class HTMLLogger : public Logger {
   //  - meaningful names for values
   //  - which boolean values are implied true/false by the flow condition
   void recordState(TypeErasedDataflowAnalysisState &State) override {
-unsigned Block = Iters.back().first->getBlockID();
-unsigned Iter = Iters.back().second;
+unsigned Block = Iters.back().Block->getBlockID();
+unsigned Iter = Iters.back().Iter;
+bool PostVisit = Iters.back().PostVisit;
 JOS->attributeObject(elementIterID(Block, Iter, ElementIndex), [&] {
   JOS->attribute("block", blockID(Block));
   JOS->attribute("iter", Iter);
+  JOS->attribute("post_visit", PostVisit);
   JOS->attribute("element", ElementIndex);
 
   // If this state immediately follows an Expr, show its built-in model.
   if (ElementIndex > 0) {
 auto S =
-Iters.back().first->Elements[ElementIndex - 1].getAs();
+Iters.back().Block->Elements[ElementIndex - 1].getAs();
 if (const Expr *E = S ? llvm::dyn_cast(S->getStmt()) : nullptr) {
   if (E->isPRValue()) {
 if (auto *V = State.Env.getValue(*E))
@@ -289,9 +301,16 @@ class HTMLLogger : public Logger {
   // Write the CFG block details.
   // Currently t

[clang] [clang][dataflow] Identify post-visit state changes in the HTML logger. (PR #66746)

2023-09-19 Thread via cfe-commits

https://github.com/martinboehme edited 
https://github.com/llvm/llvm-project/pull/66746
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Support target names with dots in more utilities (PR #65812)

2023-09-19 Thread James Henderson via cfe-commits

https://github.com/jh7370 edited https://github.com/llvm/llvm-project/pull/65812
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Support target names with dots in more utilities (PR #65812)

2023-09-19 Thread James Henderson via cfe-commits


@@ -1696,6 +1696,40 @@ TEST(Support, ReplacePathPrefix) {
   EXPECT_EQ(Path, "C:\\old/foo\\bar");
 }
 
+TEST(Support, FindProgramName) {
+  StringRef WindowsProgName =
+  path::program_name("C:\\Test\\foo.exe", path::Style::windows);
+  EXPECT_EQ(WindowsProgName, "foo");
+
+  StringRef WindowsProgNameManyDots = path::program_name(
+  "C:\\Test.7\\x86_64-freebsd14.0-clang.exe", path::Style::windows);
+  EXPECT_EQ(WindowsProgNameManyDots, "x86_64-freebsd14.0-clang");
+
+  StringRef PosixProgName =
+  path::program_name("/var/empty/clang.exe", path::Style::posix);
+  EXPECT_EQ(PosixProgName, "clang");
+
+  StringRef PosixProgNameManyDotsExe = path::program_name(
+  "/llvm-test16.4/x86_64-portbld-freebsd13.2-llvm-ar.exe",
+  path::Style::posix);
+  EXPECT_EQ(PosixProgNameManyDotsExe, "x86_64-portbld-freebsd13.2-llvm-ar");
+
+  StringRef PosixProgNameManyDots = path::program_name(
+  "/llvm-test16.4/x86_64-portbld-freebsd13.2-llvm-ar", path::Style::posix);
+  EXPECT_EQ(PosixProgNameManyDots, "x86_64-portbld-freebsd13.2-llvm-ar");
+
+  StringRef PosixProgNameSh =
+  
path::program_name("/llvm-test16.4/x86_64-portbld-freebsd13.2-llvm-ar.sh",
+ path::Style::posix);
+  EXPECT_EQ(PosixProgNameSh, "x86_64-portbld-freebsd13.2-llvm-ar.sh");
+
+  // TODO: determine if this is correct. What happens on windows with an 
executable
+  // named ".exe"?

jh7370 wrote:

I just used the Windows UI to rename a file to ".exe" and it works fine (both 
renaming and susbequent execution of the file from the command-line). 
Meanwhile, the documented behaviour of `stem` is that something containing only 
a single dot will result in an empty string, which I think we should be 
mirroring here. I think the behaviour tested here is therefore correct and you 
can probably drop the TODO note.

https://github.com/llvm/llvm-project/pull/65812
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Support target names with dots in more utilities (PR #65812)

2023-09-19 Thread James Henderson via cfe-commits


@@ -5,11 +5,14 @@
 # RUN: mkdir %t
 # RUN: ln -s llvm-ranlib %t/llvm-ranlib-9
 # RUN: ln -s llvm-ranlib %t/ranlib.exe
+# RUN: ln -s llvm-ranlib %t/x86_64-unknown-freebsd13.2-llvm-ranlib

jh7370 wrote:

Let's put the new test files and deletion of this old test in a different PR. 
The old code was untested, so we're not making things worse, but it also helps 
keep the PRs focused. Aside: if we're deleting this old file, I think it would 
be a good idea to add one or two cases to the llvm-ar test showing the 
"llvm-ranlib" name.

https://github.com/llvm/llvm-project/pull/65812
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][Interp] Emit dummy values for unknown C variables (PR #66749)

2023-09-19 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/66749

We can't load anything from them, but we can still take their address or return 
them as lvalues.

>From 9952d03bf25766ada5a41c13c3be45f9bd1e8bf2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Tue, 19 Sep 2023 08:47:01 +0200
Subject: [PATCH] [clang][Interp] Emit dummy values for unknown C variables

We can't load anything from them, but we can still take their address or
return them as lvalues.
---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp |  3 +++
 clang/lib/AST/Interp/Interp.cpp  |  2 +-
 clang/lib/AST/Interp/Program.cpp |  9 -
 clang/lib/AST/Interp/Program.h   |  4 ++--
 clang/test/AST/Interp/c.c| 22 --
 5 files changed, 26 insertions(+), 14 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index c813f9b6d9991c5..24d4991a0308097 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2493,6 +2493,9 @@ bool ByteCodeExprGen::VisitDeclRefExpr(const 
DeclRefExpr *E) {
   // Retry.
   return this->VisitDeclRefExpr(E);
 }
+
+if (std::optional I = P.getOrCreateDummy(D))
+  return this->emitGetPtrGlobal(*I, E);
   }
 
   return this->emitInvalidDeclRef(E, E);
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index e1951574edb6288..4f2d120407e942a 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -139,7 +139,7 @@ bool CheckExtern(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr) {
   if (!Ptr.isExtern())
 return true;
 
-  if (!S.checkingPotentialConstantExpression()) {
+  if (!S.checkingPotentialConstantExpression() && S.getLangOpts().CPlusPlus) {
 const auto *VD = Ptr.getDeclDesc()->asValueDecl();
 const SourceInfo &Loc = S.Current->getSource(OpPC);
 S.FFDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
diff --git a/clang/lib/AST/Interp/Program.cpp b/clang/lib/AST/Interp/Program.cpp
index 63901d90703dc46..65e170881e313d7 100644
--- a/clang/lib/AST/Interp/Program.cpp
+++ b/clang/lib/AST/Interp/Program.cpp
@@ -138,17 +138,16 @@ std::optional Program::getOrCreateGlobal(const 
ValueDecl *VD,
   return std::nullopt;
 }
 
-std::optional Program::getOrCreateDummy(const ParmVarDecl *PD) {
-
+std::optional Program::getOrCreateDummy(const ValueDecl *PD) {
   // Dedup blocks since they are immutable and pointers cannot be compared.
   if (auto It = DummyParams.find(PD);
   It != DummyParams.end())
 return It->second;
 
-  auto &ASTCtx = Ctx.getASTContext();
   // Create a pointer to an incomplete array of the specified elements.
-  QualType ElemTy = PD->getType()->castAs()->getPointeeType();
-  QualType Ty = ASTCtx.getIncompleteArrayType(ElemTy, ArrayType::Normal, 0);
+  QualType ElemTy = PD->getType();
+  QualType Ty =
+  Ctx.getASTContext().getIncompleteArrayType(ElemTy, ArrayType::Normal, 0);
 
   if (auto Idx = createGlobal(PD, Ty, /*isStatic=*/true, /*isExtern=*/true)) {
 DummyParams[PD] = *Idx;
diff --git a/clang/lib/AST/Interp/Program.h b/clang/lib/AST/Interp/Program.h
index d880a738e733e31..f21b908f5bbd23d 100644
--- a/clang/lib/AST/Interp/Program.h
+++ b/clang/lib/AST/Interp/Program.h
@@ -83,7 +83,7 @@ class Program final {
 const Expr *Init = nullptr);
 
   /// Returns or creates a dummy value for parameters.
-  std::optional getOrCreateDummy(const ParmVarDecl *PD);
+  std::optional getOrCreateDummy(const ValueDecl *PD);
 
   /// Creates a global and returns its index.
   std::optional createGlobal(const ValueDecl *VD, const Expr *E);
@@ -208,7 +208,7 @@ class Program final {
   llvm::DenseMap Records;
 
   /// Dummy parameter to generate pointers from.
-  llvm::DenseMap DummyParams;
+  llvm::DenseMap DummyParams;
 
   /// Creates a new descriptor.
   template 
diff --git a/clang/test/AST/Interp/c.c b/clang/test/AST/Interp/c.c
index c0ec5f8339dd1d7..24ece8f26399031 100644
--- a/clang/test/AST/Interp/c.c
+++ b/clang/test/AST/Interp/c.c
@@ -24,15 +24,25 @@ const int b = 3;
 _Static_assert(b == 3, ""); // pedantic-ref-warning {{not an integer constant 
expression}} \
 // pedantic-expected-warning {{not an integer 
constant expression}}
 
+/// FIXME: The new interpreter is missing the "initializer of 'c' unknown" 
diagnostics.
 const int c; // ref-note {{declared here}} \
- // pedantic-ref-note {{declared here}} \
- // expected-note {{declared here}} \
- // pedantic-expected-note {{declared here}}
+ // pedantic-ref-note {{declared here}}
 _Static_assert(c == 0, ""); // ref-error {{not an integral constant 
expression}} \
 // ref-note {{initializer of 'c' is unknown}} \
 // pedantic-ref-error {{not an integral constant 
expression}} \

[clang] [clang][Interp] Emit dummy values for unknown C variables (PR #66749)

2023-09-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

We can't load anything from them, but we can still take their address or return 
them as lvalues.

---
Full diff: https://github.com/llvm/llvm-project/pull/66749.diff


5 Files Affected:

- (modified) clang/lib/AST/Interp/ByteCodeExprGen.cpp (+3) 
- (modified) clang/lib/AST/Interp/Interp.cpp (+1-1) 
- (modified) clang/lib/AST/Interp/Program.cpp (+4-5) 
- (modified) clang/lib/AST/Interp/Program.h (+2-2) 
- (modified) clang/test/AST/Interp/c.c (+16-6) 


``diff
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index c813f9b6d9991c5..24d4991a0308097 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2493,6 +2493,9 @@ bool ByteCodeExprGen::VisitDeclRefExpr(const 
DeclRefExpr *E) {
   // Retry.
   return this->VisitDeclRefExpr(E);
 }
+
+if (std::optional I = P.getOrCreateDummy(D))
+  return this->emitGetPtrGlobal(*I, E);
   }
 
   return this->emitInvalidDeclRef(E, E);
diff --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index e1951574edb6288..4f2d120407e942a 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -139,7 +139,7 @@ bool CheckExtern(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr) {
   if (!Ptr.isExtern())
 return true;
 
-  if (!S.checkingPotentialConstantExpression()) {
+  if (!S.checkingPotentialConstantExpression() && S.getLangOpts().CPlusPlus) {
 const auto *VD = Ptr.getDeclDesc()->asValueDecl();
 const SourceInfo &Loc = S.Current->getSource(OpPC);
 S.FFDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
diff --git a/clang/lib/AST/Interp/Program.cpp b/clang/lib/AST/Interp/Program.cpp
index 63901d90703dc46..65e170881e313d7 100644
--- a/clang/lib/AST/Interp/Program.cpp
+++ b/clang/lib/AST/Interp/Program.cpp
@@ -138,17 +138,16 @@ std::optional Program::getOrCreateGlobal(const 
ValueDecl *VD,
   return std::nullopt;
 }
 
-std::optional Program::getOrCreateDummy(const ParmVarDecl *PD) {
-
+std::optional Program::getOrCreateDummy(const ValueDecl *PD) {
   // Dedup blocks since they are immutable and pointers cannot be compared.
   if (auto It = DummyParams.find(PD);
   It != DummyParams.end())
 return It->second;
 
-  auto &ASTCtx = Ctx.getASTContext();
   // Create a pointer to an incomplete array of the specified elements.
-  QualType ElemTy = PD->getType()->castAs()->getPointeeType();
-  QualType Ty = ASTCtx.getIncompleteArrayType(ElemTy, ArrayType::Normal, 0);
+  QualType ElemTy = PD->getType();
+  QualType Ty =
+  Ctx.getASTContext().getIncompleteArrayType(ElemTy, ArrayType::Normal, 0);
 
   if (auto Idx = createGlobal(PD, Ty, /*isStatic=*/true, /*isExtern=*/true)) {
 DummyParams[PD] = *Idx;
diff --git a/clang/lib/AST/Interp/Program.h b/clang/lib/AST/Interp/Program.h
index d880a738e733e31..f21b908f5bbd23d 100644
--- a/clang/lib/AST/Interp/Program.h
+++ b/clang/lib/AST/Interp/Program.h
@@ -83,7 +83,7 @@ class Program final {
 const Expr *Init = nullptr);
 
   /// Returns or creates a dummy value for parameters.
-  std::optional getOrCreateDummy(const ParmVarDecl *PD);
+  std::optional getOrCreateDummy(const ValueDecl *PD);
 
   /// Creates a global and returns its index.
   std::optional createGlobal(const ValueDecl *VD, const Expr *E);
@@ -208,7 +208,7 @@ class Program final {
   llvm::DenseMap Records;
 
   /// Dummy parameter to generate pointers from.
-  llvm::DenseMap DummyParams;
+  llvm::DenseMap DummyParams;
 
   /// Creates a new descriptor.
   template 
diff --git a/clang/test/AST/Interp/c.c b/clang/test/AST/Interp/c.c
index c0ec5f8339dd1d7..24ece8f26399031 100644
--- a/clang/test/AST/Interp/c.c
+++ b/clang/test/AST/Interp/c.c
@@ -24,15 +24,25 @@ const int b = 3;
 _Static_assert(b == 3, ""); // pedantic-ref-warning {{not an integer constant 
expression}} \
 // pedantic-expected-warning {{not an integer 
constant expression}}
 
+/// FIXME: The new interpreter is missing the "initializer of 'c' unknown" 
diagnostics.
 const int c; // ref-note {{declared here}} \
- // pedantic-ref-note {{declared here}} \
- // expected-note {{declared here}} \
- // pedantic-expected-note {{declared here}}
+ // pedantic-ref-note {{declared here}}
 _Static_assert(c == 0, ""); // ref-error {{not an integral constant 
expression}} \
 // ref-note {{initializer of 'c' is unknown}} \
 // pedantic-ref-error {{not an integral constant 
expression}} \
 // pedantic-ref-note {{initializer of 'c' is 
unknown}} \
 // expected-error {{not an integral constant 
expression}} \
-// expected-note {{initializer of 'c' is unknown}} 
\
-// pedantic-expected-err

[clang] [NFC] Preparatory work for D153131 (PR #66750)

2023-09-19 Thread Clement Courbet via cfe-commits

https://github.com/legrosbuffle created 
https://github.com/llvm/llvm-project/pull/66750

None

>From 3679b5c95a8de88a5cabc9ecdacdbbfef9c68ea8 Mon Sep 17 00:00:00 2001
From: Clement Courbet 
Date: Tue, 19 Sep 2023 10:19:49 +0200
Subject: [PATCH] [NFC] Preparatory work for D153131

---
 clang/lib/Analysis/ThreadSafety.cpp | 18 +-
 1 file changed, 9 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Analysis/ThreadSafety.cpp 
b/clang/lib/Analysis/ThreadSafety.cpp
index 34260ac8f4e7d6f..3107d035254dde6 100644
--- a/clang/lib/Analysis/ThreadSafety.cpp
+++ b/clang/lib/Analysis/ThreadSafety.cpp
@@ -2265,8 +2265,11 @@ void 
ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
   const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
   PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
 
+  CFGBlockInfo &Initial = BlockInfo[CFGraph->getEntry().getBlockID()];
+  CFGBlockInfo &Final   = BlockInfo[CFGraph->getExit().getBlockID()];
+
   // Mark entry block as reachable
-  BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
+  Initial.Reachable = true;
 
   // Compute SSA names for local variables
   LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
@@ -2282,8 +2285,8 @@ void 
ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
   // to initial lockset. Also turn off checking for lock and unlock functions.
   // FIXME: is there a more intelligent way to check lock/unlock functions?
   if (!SortedGraph->empty() && D->hasAttrs()) {
-const CFGBlock *FirstBlock = *SortedGraph->begin();
-FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
+assert(*SortedGraph->begin() == &CFGraph->getEntry());
+FactSet &InitialLockset = Initial.EntrySet;
 
 CapExprSet ExclusiveLocksToAdd;
 CapExprSet SharedLocksToAdd;
@@ -2455,15 +2458,12 @@ void 
ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
 }
   }
 
-  CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
-  CFGBlockInfo *Final   = &BlockInfo[CFGraph->getExit().getBlockID()];
-
   // Skip the final check if the exit block is unreachable.
-  if (!Final->Reachable)
+  if (!Final.Reachable)
 return;
 
   // By default, we expect all locks held on entry to be held on exit.
-  FactSet ExpectedExitSet = Initial->EntrySet;
+  FactSet ExpectedExitSet = Initial.EntrySet;
 
   // Adjust the expected exit set by adding or removing locks, as declared
   // by *-LOCK_FUNCTION and UNLOCK_FUNCTION.  The intersect below will then
@@ -2479,7 +2479,7 @@ void 
ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
 ExpectedExitSet.removeLock(FactMan, Lock);
 
   // FIXME: Should we call this function for all blocks which exit the 
function?
-  intersectAndWarn(ExpectedExitSet, Final->ExitSet, Final->ExitLoc,
+  intersectAndWarn(ExpectedExitSet, Final.ExitSet, Final.ExitLoc,
LEK_LockedAtEndOfFunction, LEK_NotLockedAtEndOfFunction);
 
   Handler.leaveFunction(CurrentFunction);

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


[PATCH] D141800: [clangd] Fix qualifier not being dropped for using declaration referring to scoped enum

2023-09-19 Thread Tom Praschan via Phabricator via cfe-commits
tom-anders added a comment.

(friendly ping)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141800

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


[clang] [InstCombine] Canonicalize `and(zext(A), B)` into `select A, B & 1, 0` (PR #66740)

2023-09-19 Thread Nikita Popov via cfe-commits

nikic wrote:

I think this is the right canonicalization at the IR level, as select allows 
better analysis than zext(icmp). However, this seems to be universally worse 
for the backend: https://llvm.godbolt.org/z/Yh7brfc8b So I think we would need 
an SDAG undo transform. Interestingly, this already happens for riscv64, so 
maybe the undo transform already exists but is not enabled for all target.

@goldsteinn What do you think?

https://github.com/llvm/llvm-project/pull/66740
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c809051 - [NFC] Preparatory work for D153131 (#66750)

2023-09-19 Thread via cfe-commits

Author: Clement Courbet
Date: 2023-09-19T11:02:00+02:00
New Revision: c8090512157ab0aad1e43e398598e689b7e55a52

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

LOG: [NFC] Preparatory work for D153131 (#66750)

Added: 


Modified: 
clang/lib/Analysis/ThreadSafety.cpp

Removed: 




diff  --git a/clang/lib/Analysis/ThreadSafety.cpp 
b/clang/lib/Analysis/ThreadSafety.cpp
index 34260ac8f4e7d6f..3107d035254dde6 100644
--- a/clang/lib/Analysis/ThreadSafety.cpp
+++ b/clang/lib/Analysis/ThreadSafety.cpp
@@ -2265,8 +2265,11 @@ void 
ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
   const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
   PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
 
+  CFGBlockInfo &Initial = BlockInfo[CFGraph->getEntry().getBlockID()];
+  CFGBlockInfo &Final   = BlockInfo[CFGraph->getExit().getBlockID()];
+
   // Mark entry block as reachable
-  BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
+  Initial.Reachable = true;
 
   // Compute SSA names for local variables
   LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
@@ -2282,8 +2285,8 @@ void 
ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
   // to initial lockset. Also turn off checking for lock and unlock functions.
   // FIXME: is there a more intelligent way to check lock/unlock functions?
   if (!SortedGraph->empty() && D->hasAttrs()) {
-const CFGBlock *FirstBlock = *SortedGraph->begin();
-FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
+assert(*SortedGraph->begin() == &CFGraph->getEntry());
+FactSet &InitialLockset = Initial.EntrySet;
 
 CapExprSet ExclusiveLocksToAdd;
 CapExprSet SharedLocksToAdd;
@@ -2455,15 +2458,12 @@ void 
ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
 }
   }
 
-  CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
-  CFGBlockInfo *Final   = &BlockInfo[CFGraph->getExit().getBlockID()];
-
   // Skip the final check if the exit block is unreachable.
-  if (!Final->Reachable)
+  if (!Final.Reachable)
 return;
 
   // By default, we expect all locks held on entry to be held on exit.
-  FactSet ExpectedExitSet = Initial->EntrySet;
+  FactSet ExpectedExitSet = Initial.EntrySet;
 
   // Adjust the expected exit set by adding or removing locks, as declared
   // by *-LOCK_FUNCTION and UNLOCK_FUNCTION.  The intersect below will then
@@ -2479,7 +2479,7 @@ void 
ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
 ExpectedExitSet.removeLock(FactMan, Lock);
 
   // FIXME: Should we call this function for all blocks which exit the 
function?
-  intersectAndWarn(ExpectedExitSet, Final->ExitSet, Final->ExitLoc,
+  intersectAndWarn(ExpectedExitSet, Final.ExitSet, Final.ExitLoc,
LEK_LockedAtEndOfFunction, LEK_NotLockedAtEndOfFunction);
 
   Handler.leaveFunction(CurrentFunction);



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


[clang] [NFC] Preparatory work for D153131 (PR #66750)

2023-09-19 Thread Clement Courbet via cfe-commits

https://github.com/legrosbuffle closed 
https://github.com/llvm/llvm-project/pull/66750
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 97495d3 - [analyzer] TaintPropagation checker strlen() should not propagate (#66086)

2023-09-19 Thread via cfe-commits

Author: Daniel Krupp
Date: 2023-09-19T11:04:50+02:00
New Revision: 97495d3159799677c2dea8516f2246854c19d007

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

LOG: [analyzer] TaintPropagation checker strlen() should not propagate (#66086)

strlen(..) call should not propagate taintedness,
because it brings in many false positive findings. It is a common
pattern to copy user provided input to another buffer. In these cases we
always
get warnings about tainted data used as the malloc parameter:

buf = malloc(strlen(tainted_txt) + 1); // false warning

This pattern can lead to a denial of service attack only, when the
attacker can directly specify the size of the allocated area as an
arbitrary large number (e.g. the value is converted from a user provided
string).

Later, we could reintroduce strlen() as a taint propagating function
with the consideration not to emit warnings when the tainted value
cannot be "arbitrarily large" (such as the size of an already allocated
memory block).

The change has been evaluated on the following open source projects:

- memcached: [1 lost false
positive](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=memcached_1.6.8_ednikru_taint_nostrlen_baseline&newcheck=memcached_1.6.8_ednikru_taint_nostrlen_new&is-unique=on&diff-type=Resolved)

- tmux: 0 lost reports
- twin [3 lost false
positives](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=twin_v0.8.1_ednikru_taint_nostrlen_baseline&newcheck=twin_v0.8.1_ednikru_taint_nostrlen_new&is-unique=on&diff-type=Resolved)
- vim [1 lost false
positive](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=vim_v8.2.1920_ednikru_taint_nostrlen_baseline&newcheck=vim_v8.2.1920_ednikru_taint_nostrlen_new&is-unique=on&diff-type=Resolved)
- openssl 0 lost reports
- sqliste [2 lost false
positives](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=sqlite_version-3.33.0_ednikru_taint_nostrlen_baseline&newcheck=sqlite_version-3.33.0_ednikru_taint_nostrlen_new&is-unique=on&diff-type=Resolved)
- ffmpeg 0 lost repots
- postgresql [3 lost false
positives](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=postgres_REL_13_0_ednikru_taint_nostrlen_baseline&newcheck=postgres_REL_13_0_ednikru_taint_nostrlen_new&is-unique=on&diff-type=Resolved)
- tinyxml 0 lost reports
- libwebm 0 lost reports
- xerces 0 lost reports

In all cases the lost reports are originating from copying untrusted
environment variables into another buffer.

There are 2 types of lost false positive reports:
1) [Where the warning is emitted at the malloc call by the
TaintPropagation Checker
](https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=memcached_1.6.8_ednikru_taint_nostrlen_baseline&newcheck=memcached_1.6.8_ednikru_taint_nostrlen_new&is-unique=on&diff-type=Resolved&report-id=2648506&report-hash=2079221954026f17e1ecb614f5f054db&report-filepath=%2amemcached.c)
`
len = strlen(portnumber_filename)+4+1;
temp_portnumber_filename = malloc(len);
`

2) When pointers are set based on the length of the tainted string by
the ArrayOutofBoundsv2 checker.
For example [this
](https://codechecker-demo.eastus.cloudapp.azure.com/Default/report-detail?run=vim_v8.2.1920_ednikru_taint_nostrlen_baseline&newcheck=vim_v8.2.1920_ednikru_taint_nostrlen_new&is-unique=on&diff-type=Resolved&report-id=2649310&report-hash=79dc8522d2cd34ca8e1b2dc2db64b2df&report-filepath=%2aos_unix.c)case.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/docs/analyzer/checkers.rst
clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
clang/test/Analysis/taint-diagnostic-visitor.c
clang/test/Analysis/taint-generic.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 172818114c3b92b..30c29a5d6db6f5e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -450,6 +450,13 @@ Static Analyzer
   bitwise shift operators produce undefined behavior (because some operand is
   negative or too large).
 
+- The ``alpha.security.taint.TaintPropagation`` checker no longer propagates
+  taint on ``strlen`` and ``strnlen`` calls, unless these are marked
+  explicitly propagators in the user-provided taint configuration file.
+  This removal empirically reduces the number of false positive reports.
+  Read the PR for the details.
+  (`#66086 `_)
+
 .. _release-notes-sanitizers:
 
 Sanitizers

diff  --git a/clang/docs/analyzer/checkers.rst 
b/clang/docs/analyzer/checkers.rst
index 54ea49e7426cc86..dbd6d7787823530 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -2599,8 +2599,8 @@ Default propagat

[clang] [analyzer] TaintPropagation checker strlen() should not propagate (PR #66086)

2023-09-19 Thread Daniel Krupp via cfe-commits

https://github.com/dkrupp closed https://github.com/llvm/llvm-project/pull/66086
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D153131: [clang analysis][thread-safety] Handle return-by-reference...

2023-09-19 Thread Clement Courbet via Phabricator via cfe-commits
courbet updated this revision to Diff 557015.
courbet marked an inline comment as done.
courbet added a comment.

Rebase on NFC changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153131

Files:
  clang/include/clang/Analysis/Analyses/ThreadSafety.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Analysis/ThreadSafety.cpp
  clang/lib/Sema/AnalysisBasedWarnings.cpp
  clang/test/SemaCXX/warn-thread-safety-analysis.cpp

Index: clang/test/SemaCXX/warn-thread-safety-analysis.cpp
===
--- clang/test/SemaCXX/warn-thread-safety-analysis.cpp
+++ clang/test/SemaCXX/warn-thread-safety-analysis.cpp
@@ -5580,6 +5580,85 @@
   }
 };
 
+class Return {
+  Mutex mu;
+  Foo foo GUARDED_BY(mu);
+  Foo* foo_ptr PT_GUARDED_BY(mu);
+
+  Foo returns_value_locked() {
+MutexLock lock(&mu);
+return foo;
+  }
+
+  Foo returns_value_locks_required() EXCLUSIVE_LOCKS_REQUIRED(mu) {
+return foo;
+  }
+
+  Foo returns_value_releases_lock_after_return() UNLOCK_FUNCTION(mu) {
+MutexLock lock(&mu, true);
+return foo;
+  }
+
+  Foo returns_value_aquires_lock() EXCLUSIVE_LOCK_FUNCTION(mu) {
+mu.Lock();
+return foo;
+  }
+  
+  Foo returns_value_not_locked() {
+return foo;   // expected-warning {{reading variable 'foo' requires holding mutex 'mu'}}
+  }
+  
+  Foo returns_value_releases_lock_before_return() UNLOCK_FUNCTION(mu) {
+mu.Unlock();
+return foo;   // expected-warning {{reading variable 'foo' requires holding mutex 'mu'}}
+  }
+
+  Foo &returns_ref_not_locked() {
+return foo;   // expected-warning {{returning variable 'foo' by reference requires holding mutex 'mu'}}
+  }
+
+  Foo &returns_ref_locked() {
+MutexLock lock(&mu);
+return foo;   // expected-warning {{returning variable 'foo' by reference requires holding mutex 'mu'}}
+  }
+
+  Foo &returns_ref_shared_locks_required() SHARED_LOCKS_REQUIRED(mu) {
+return foo;   // expected-warning {{returning variable 'foo' by reference requires holding mutex 'mu' exclusively}}
+  }
+
+  Foo &returns_ref_exclusive_locks_required() EXCLUSIVE_LOCKS_REQUIRED(mu) {
+return foo;
+  }
+
+  Foo &returns_ref_releases_lock_after_return() UNLOCK_FUNCTION(mu) {
+MutexLock lock(&mu, true);
+return foo;   // expected-warning {{returning variable 'foo' by reference requires holding mutex 'mu' exclusively}}
+  }
+
+  Foo& returns_ref_releases_lock_before_return() UNLOCK_FUNCTION(mu) {
+mu.Unlock();
+return foo;   // // expected-warning {{returning variable 'foo' by reference requires holding mutex 'mu' exclusively}}
+  }
+  
+  Foo &returns_ref_aquires_lock() EXCLUSIVE_LOCK_FUNCTION(mu) {
+mu.Lock();
+return foo;
+  }
+  
+  const Foo &returns_constref_shared_locks_required() SHARED_LOCKS_REQUIRED(mu) {
+return foo;
+  }
+  
+  Foo *returns_ptr() {
+return &foo;  // FIXME -- Do we want to warn on this ?
+  }
+
+  Foo &returns_ref2() {
+return *foo_ptr;  // expected-warning {{returning the value that 'foo_ptr' points to by reference requires holding mutex 'mu' exclusively}}
+  }
+
+};
+
 
 }  // end namespace PassByRefTest
 
Index: clang/lib/Sema/AnalysisBasedWarnings.cpp
===
--- clang/lib/Sema/AnalysisBasedWarnings.cpp
+++ clang/lib/Sema/AnalysisBasedWarnings.cpp
@@ -1983,6 +1983,12 @@
 case POK_PtPassByRef:
   DiagID = diag::warn_pt_guarded_pass_by_reference;
   break;
+case POK_ReturnByRef:
+  DiagID = diag::warn_guarded_return_by_reference;
+  break;
+case POK_PtReturnByRef:
+  DiagID = diag::warn_pt_guarded_return_by_reference;
+  break;
   }
   PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
<< D
@@ -2013,6 +2019,12 @@
 case POK_PtPassByRef:
   DiagID = diag::warn_pt_guarded_pass_by_reference;
   break;
+case POK_ReturnByRef:
+  DiagID = diag::warn_guarded_return_by_reference;
+  break;
+case POK_PtReturnByRef:
+  DiagID = diag::warn_pt_guarded_return_by_reference;
+  break;
   }
   PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
<< D
Index: clang/lib/Analysis/ThreadSafety.cpp
===
--- clang/lib/Analysis/ThreadSafety.cpp
+++ clang/lib/Analysis/ThreadSafety.cpp
@@ -1008,7 +1008,7 @@
   threadSafety::SExprBuilder SxBuilder;
 
   ThreadSafetyHandler &Handler;
-  const CXXMethodDecl *CurrentMethod = nullptr;
+  const FunctionDecl *CurrentFunction;
   LocalVariableMap LocalVarMap;
   FactManager FactMan;
   std::vector BlockInfo;
@@ -1243

[clang-tools-extra] [clang] remove ClassScopeFunctionSpecializationDecl (PR #66636)

2023-09-19 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian updated 
https://github.com/llvm/llvm-project/pull/66636

>From d11d546f3190936ba45c57b4825073026d817878 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Fri, 25 Aug 2023 14:07:32 -0400
Subject: [PATCH 1/2] [clang] remove ClassScopeFunctionSpecializationDecl

---
 .../clang-tidy/modernize/UseEmplaceCheck.cpp  |   2 +-
 .../clangd/SemanticHighlighting.cpp   |   9 --
 clang/include/clang/AST/ASTNodeTraverser.h|   7 +-
 clang/include/clang/AST/Decl.h|  10 +-
 clang/include/clang/AST/DeclTemplate.h| 150 +++---
 clang/include/clang/AST/RecursiveASTVisitor.h |  19 ++-
 clang/include/clang/Basic/DeclNodes.td|   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   8 +-
 clang/include/clang/Sema/Sema.h   |   6 +-
 clang/include/clang/Sema/Template.h   |   2 -
 .../include/clang/Serialization/ASTBitCodes.h |   4 -
 .../clang/Serialization/ASTRecordReader.h |   2 +
 clang/lib/AST/ASTImporter.cpp |  26 ++-
 clang/lib/AST/Decl.cpp|  71 ++---
 clang/lib/AST/DeclBase.cpp|   2 -
 clang/lib/AST/DeclTemplate.cpp|  13 --
 clang/lib/AST/ODRHash.cpp |   4 +
 clang/lib/CodeGen/CGDecl.cpp  |   1 -
 clang/lib/Index/IndexSymbol.cpp   |   1 -
 clang/lib/Sema/SemaDecl.cpp   | 112 ++---
 clang/lib/Sema/SemaTemplate.cpp   |  14 +-
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 121 +++---
 clang/lib/Serialization/ASTCommon.cpp |   1 -
 clang/lib/Serialization/ASTReader.cpp |  19 ++-
 clang/lib/Serialization/ASTReaderDecl.cpp |  59 ++-
 clang/lib/Serialization/ASTWriter.cpp |   1 -
 clang/lib/Serialization/ASTWriterDecl.cpp |  42 ++---
 .../Checkers/SmartPtrModeling.cpp |   2 +-
 clang/test/AST/ast-dump-decl.cpp  |   9 +-
 clang/test/CXX/drs/dr7xx.cpp  |   5 +
 .../test/SemaTemplate/instantiate-method.cpp  |   7 +-
 clang/tools/libclang/CIndex.cpp   |   1 -
 32 files changed, 290 insertions(+), 441 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
index 554abcd900e329c..06ae1f4e257528f 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
@@ -67,7 +67,7 @@ AST_MATCHER_P(CallExpr, hasLastArgument,
 // function had parameters defined (this is useful to check if there is only 
one
 // variadic argument).
 AST_MATCHER(CXXMemberCallExpr, hasSameNumArgsAsDeclNumParams) {
-  if (Node.getMethodDecl()->isFunctionTemplateSpecialization())
+  if (Node.getMethodDecl()->getPrimaryTemplate())
 return Node.getNumArgs() == Node.getMethodDecl()
 ->getPrimaryTemplate()
 ->getTemplatedDecl()
diff --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 45c01634e2e38d1..7649e37e1f96663 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -715,13 +715,6 @@ class CollectExtraHighlightings
 return true;
   }
 
-  bool VisitClassScopeFunctionSpecializationDecl(
-  ClassScopeFunctionSpecializationDecl *D) {
-if (auto *Args = D->getTemplateArgsAsWritten())
-  H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
-return true;
-  }
-
   bool VisitDeclRefExpr(DeclRefExpr *E) {
 H.addAngleBracketTokens(E->getLAngleLoc(), E->getRAngleLoc());
 return true;
@@ -752,8 +745,6 @@ class CollectExtraHighlightings
 }
 if (auto *Args = D->getTemplateSpecializationArgsAsWritten())
   H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
-if (auto *I = D->getDependentSpecializationInfo())
-  H.addAngleBracketTokens(I->getLAngleLoc(), I->getRAngleLoc());
 return true;
   }
 
diff --git a/clang/include/clang/AST/ASTNodeTraverser.h 
b/clang/include/clang/AST/ASTNodeTraverser.h
index 1151a756ff377b6..c3d233d3ab4a259 100644
--- a/clang/include/clang/AST/ASTNodeTraverser.h
+++ b/clang/include/clang/AST/ASTNodeTraverser.h
@@ -428,6 +428,8 @@ class ASTNodeTraverser
   void VisitFunctionDecl(const FunctionDecl *D) {
 if (const auto *FTSI = D->getTemplateSpecializationInfo())
   dumpTemplateArgumentList(*FTSI->TemplateArguments);
+else if (const auto *DFTSI = D->getDependentSpecializationInfo())
+  dumpASTTemplateArgumentListInfo(DFTSI->TemplateArgumentsAsWritten);
 
 if (D->param_begin())
   for (const auto *Parameter : D->parameters())
@@ -578,11 +580,6 @@ class ASTNodeTraverser
 dumpTemplateParameters(D->getTemplateParameters());
   }
 
-  void VisitClassScopeFunctionSpecializationDecl(
-  const ClassScopeFunctionSpe

[clang-tools-extra] [clang] remove ClassScopeFunctionSpecializationDecl (PR #66636)

2023-09-19 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian updated 
https://github.com/llvm/llvm-project/pull/66636

>From d11d546f3190936ba45c57b4825073026d817878 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Fri, 25 Aug 2023 14:07:32 -0400
Subject: [PATCH 1/2] [clang] remove ClassScopeFunctionSpecializationDecl

---
 .../clang-tidy/modernize/UseEmplaceCheck.cpp  |   2 +-
 .../clangd/SemanticHighlighting.cpp   |   9 --
 clang/include/clang/AST/ASTNodeTraverser.h|   7 +-
 clang/include/clang/AST/Decl.h|  10 +-
 clang/include/clang/AST/DeclTemplate.h| 150 +++---
 clang/include/clang/AST/RecursiveASTVisitor.h |  19 ++-
 clang/include/clang/Basic/DeclNodes.td|   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   8 +-
 clang/include/clang/Sema/Sema.h   |   6 +-
 clang/include/clang/Sema/Template.h   |   2 -
 .../include/clang/Serialization/ASTBitCodes.h |   4 -
 .../clang/Serialization/ASTRecordReader.h |   2 +
 clang/lib/AST/ASTImporter.cpp |  26 ++-
 clang/lib/AST/Decl.cpp|  71 ++---
 clang/lib/AST/DeclBase.cpp|   2 -
 clang/lib/AST/DeclTemplate.cpp|  13 --
 clang/lib/AST/ODRHash.cpp |   4 +
 clang/lib/CodeGen/CGDecl.cpp  |   1 -
 clang/lib/Index/IndexSymbol.cpp   |   1 -
 clang/lib/Sema/SemaDecl.cpp   | 112 ++---
 clang/lib/Sema/SemaTemplate.cpp   |  14 +-
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 121 +++---
 clang/lib/Serialization/ASTCommon.cpp |   1 -
 clang/lib/Serialization/ASTReader.cpp |  19 ++-
 clang/lib/Serialization/ASTReaderDecl.cpp |  59 ++-
 clang/lib/Serialization/ASTWriter.cpp |   1 -
 clang/lib/Serialization/ASTWriterDecl.cpp |  42 ++---
 .../Checkers/SmartPtrModeling.cpp |   2 +-
 clang/test/AST/ast-dump-decl.cpp  |   9 +-
 clang/test/CXX/drs/dr7xx.cpp  |   5 +
 .../test/SemaTemplate/instantiate-method.cpp  |   7 +-
 clang/tools/libclang/CIndex.cpp   |   1 -
 32 files changed, 290 insertions(+), 441 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
index 554abcd900e329c..06ae1f4e257528f 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
@@ -67,7 +67,7 @@ AST_MATCHER_P(CallExpr, hasLastArgument,
 // function had parameters defined (this is useful to check if there is only 
one
 // variadic argument).
 AST_MATCHER(CXXMemberCallExpr, hasSameNumArgsAsDeclNumParams) {
-  if (Node.getMethodDecl()->isFunctionTemplateSpecialization())
+  if (Node.getMethodDecl()->getPrimaryTemplate())
 return Node.getNumArgs() == Node.getMethodDecl()
 ->getPrimaryTemplate()
 ->getTemplatedDecl()
diff --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 45c01634e2e38d1..7649e37e1f96663 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -715,13 +715,6 @@ class CollectExtraHighlightings
 return true;
   }
 
-  bool VisitClassScopeFunctionSpecializationDecl(
-  ClassScopeFunctionSpecializationDecl *D) {
-if (auto *Args = D->getTemplateArgsAsWritten())
-  H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
-return true;
-  }
-
   bool VisitDeclRefExpr(DeclRefExpr *E) {
 H.addAngleBracketTokens(E->getLAngleLoc(), E->getRAngleLoc());
 return true;
@@ -752,8 +745,6 @@ class CollectExtraHighlightings
 }
 if (auto *Args = D->getTemplateSpecializationArgsAsWritten())
   H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
-if (auto *I = D->getDependentSpecializationInfo())
-  H.addAngleBracketTokens(I->getLAngleLoc(), I->getRAngleLoc());
 return true;
   }
 
diff --git a/clang/include/clang/AST/ASTNodeTraverser.h 
b/clang/include/clang/AST/ASTNodeTraverser.h
index 1151a756ff377b6..c3d233d3ab4a259 100644
--- a/clang/include/clang/AST/ASTNodeTraverser.h
+++ b/clang/include/clang/AST/ASTNodeTraverser.h
@@ -428,6 +428,8 @@ class ASTNodeTraverser
   void VisitFunctionDecl(const FunctionDecl *D) {
 if (const auto *FTSI = D->getTemplateSpecializationInfo())
   dumpTemplateArgumentList(*FTSI->TemplateArguments);
+else if (const auto *DFTSI = D->getDependentSpecializationInfo())
+  dumpASTTemplateArgumentListInfo(DFTSI->TemplateArgumentsAsWritten);
 
 if (D->param_begin())
   for (const auto *Parameter : D->parameters())
@@ -578,11 +580,6 @@ class ASTNodeTraverser
 dumpTemplateParameters(D->getTemplateParameters());
   }
 
-  void VisitClassScopeFunctionSpecializationDecl(
-  const ClassScopeFunctionSpe

[clang-tools-extra] [clang] remove ClassScopeFunctionSpecializationDecl (PR #66636)

2023-09-19 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian resolved 
https://github.com/llvm/llvm-project/pull/66636
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang] remove ClassScopeFunctionSpecializationDecl (PR #66636)

2023-09-19 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian resolved 
https://github.com/llvm/llvm-project/pull/66636
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang] remove ClassScopeFunctionSpecializationDecl (PR #66636)

2023-09-19 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian resolved 
https://github.com/llvm/llvm-project/pull/66636
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang] remove ClassScopeFunctionSpecializationDecl (PR #66636)

2023-09-19 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian resolved 
https://github.com/llvm/llvm-project/pull/66636
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang] remove ClassScopeFunctionSpecializationDecl (PR #66636)

2023-09-19 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian updated 
https://github.com/llvm/llvm-project/pull/66636

>From d11d546f3190936ba45c57b4825073026d817878 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Fri, 25 Aug 2023 14:07:32 -0400
Subject: [PATCH 1/2] [clang] remove ClassScopeFunctionSpecializationDecl

---
 .../clang-tidy/modernize/UseEmplaceCheck.cpp  |   2 +-
 .../clangd/SemanticHighlighting.cpp   |   9 --
 clang/include/clang/AST/ASTNodeTraverser.h|   7 +-
 clang/include/clang/AST/Decl.h|  10 +-
 clang/include/clang/AST/DeclTemplate.h| 150 +++---
 clang/include/clang/AST/RecursiveASTVisitor.h |  19 ++-
 clang/include/clang/Basic/DeclNodes.td|   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   8 +-
 clang/include/clang/Sema/Sema.h   |   6 +-
 clang/include/clang/Sema/Template.h   |   2 -
 .../include/clang/Serialization/ASTBitCodes.h |   4 -
 .../clang/Serialization/ASTRecordReader.h |   2 +
 clang/lib/AST/ASTImporter.cpp |  26 ++-
 clang/lib/AST/Decl.cpp|  71 ++---
 clang/lib/AST/DeclBase.cpp|   2 -
 clang/lib/AST/DeclTemplate.cpp|  13 --
 clang/lib/AST/ODRHash.cpp |   4 +
 clang/lib/CodeGen/CGDecl.cpp  |   1 -
 clang/lib/Index/IndexSymbol.cpp   |   1 -
 clang/lib/Sema/SemaDecl.cpp   | 112 ++---
 clang/lib/Sema/SemaTemplate.cpp   |  14 +-
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 121 +++---
 clang/lib/Serialization/ASTCommon.cpp |   1 -
 clang/lib/Serialization/ASTReader.cpp |  19 ++-
 clang/lib/Serialization/ASTReaderDecl.cpp |  59 ++-
 clang/lib/Serialization/ASTWriter.cpp |   1 -
 clang/lib/Serialization/ASTWriterDecl.cpp |  42 ++---
 .../Checkers/SmartPtrModeling.cpp |   2 +-
 clang/test/AST/ast-dump-decl.cpp  |   9 +-
 clang/test/CXX/drs/dr7xx.cpp  |   5 +
 .../test/SemaTemplate/instantiate-method.cpp  |   7 +-
 clang/tools/libclang/CIndex.cpp   |   1 -
 32 files changed, 290 insertions(+), 441 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
index 554abcd900e329c..06ae1f4e257528f 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp
@@ -67,7 +67,7 @@ AST_MATCHER_P(CallExpr, hasLastArgument,
 // function had parameters defined (this is useful to check if there is only 
one
 // variadic argument).
 AST_MATCHER(CXXMemberCallExpr, hasSameNumArgsAsDeclNumParams) {
-  if (Node.getMethodDecl()->isFunctionTemplateSpecialization())
+  if (Node.getMethodDecl()->getPrimaryTemplate())
 return Node.getNumArgs() == Node.getMethodDecl()
 ->getPrimaryTemplate()
 ->getTemplatedDecl()
diff --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 45c01634e2e38d1..7649e37e1f96663 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -715,13 +715,6 @@ class CollectExtraHighlightings
 return true;
   }
 
-  bool VisitClassScopeFunctionSpecializationDecl(
-  ClassScopeFunctionSpecializationDecl *D) {
-if (auto *Args = D->getTemplateArgsAsWritten())
-  H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
-return true;
-  }
-
   bool VisitDeclRefExpr(DeclRefExpr *E) {
 H.addAngleBracketTokens(E->getLAngleLoc(), E->getRAngleLoc());
 return true;
@@ -752,8 +745,6 @@ class CollectExtraHighlightings
 }
 if (auto *Args = D->getTemplateSpecializationArgsAsWritten())
   H.addAngleBracketTokens(Args->getLAngleLoc(), Args->getRAngleLoc());
-if (auto *I = D->getDependentSpecializationInfo())
-  H.addAngleBracketTokens(I->getLAngleLoc(), I->getRAngleLoc());
 return true;
   }
 
diff --git a/clang/include/clang/AST/ASTNodeTraverser.h 
b/clang/include/clang/AST/ASTNodeTraverser.h
index 1151a756ff377b6..c3d233d3ab4a259 100644
--- a/clang/include/clang/AST/ASTNodeTraverser.h
+++ b/clang/include/clang/AST/ASTNodeTraverser.h
@@ -428,6 +428,8 @@ class ASTNodeTraverser
   void VisitFunctionDecl(const FunctionDecl *D) {
 if (const auto *FTSI = D->getTemplateSpecializationInfo())
   dumpTemplateArgumentList(*FTSI->TemplateArguments);
+else if (const auto *DFTSI = D->getDependentSpecializationInfo())
+  dumpASTTemplateArgumentListInfo(DFTSI->TemplateArgumentsAsWritten);
 
 if (D->param_begin())
   for (const auto *Parameter : D->parameters())
@@ -578,11 +580,6 @@ class ASTNodeTraverser
 dumpTemplateParameters(D->getTemplateParameters());
   }
 
-  void VisitClassScopeFunctionSpecializationDecl(
-  const ClassScopeFunctionSpe

[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits

https://github.com/DavidSpickett requested changes to this pull request.

This looks really nice. Two overall things:

Now that ARM and AArch64 print more than just names, they should have column 
headers like RISC-V does. Name / Description

The clang test case `clang/test/Driver/print-supported-extensions.c` should be 
extended to check at least the column names and 1 row of the extension details. 
This is because we're now combining a few functions to produce this output, so 
an integration test is needed.

It is a bit ugly to have to combine these 2 sources of information but that's a 
larger issue that shouldn't block this.

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits


@@ -600,11 +601,17 @@ StringRef ARM::getARMCPUForArch(const llvm::Triple 
&Triple, StringRef MArch) {
   llvm_unreachable("invalid arch name");
 }
 
-void ARM::PrintSupportedExtensions() {
+void ARM::PrintSupportedExtensions(std::map llvmDescMap) 
{
   outs() << "All available -march extensions for ARM\n\n";
   for (const auto &Ext : ARCHExtNames) {
 // Extensions without a feature cannot be used with -march.
-if (!Ext.Feature.empty())
-  outs() << '\t' << Ext.Name << "\n";
+if (!Ext.Feature.empty()) {
+  if (llvmDescMap.empty()) {
+outs() << '\t' << Ext.Name << "\n";
+  } else {
+outs() << format("\t%-20s", Ext.Name.str().c_str());
+outs() << "\t\t" << llvmDescMap[Ext.Name] << "\n";

DavidSpickett wrote:

This can be one call to outs().

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits


@@ -600,11 +601,17 @@ StringRef ARM::getARMCPUForArch(const llvm::Triple 
&Triple, StringRef MArch) {
   llvm_unreachable("invalid arch name");
 }
 
-void ARM::PrintSupportedExtensions() {
+void ARM::PrintSupportedExtensions(std::map llvmDescMap) 
{
   outs() << "All available -march extensions for ARM\n\n";
   for (const auto &Ext : ARCHExtNames) {
 // Extensions without a feature cannot be used with -march.
-if (!Ext.Feature.empty())
-  outs() << '\t' << Ext.Name << "\n";
+if (!Ext.Feature.empty()) {

DavidSpickett wrote:

https://llvm.org/docs/CodingStandards.html#use-early-exits-and-continue-to-simplify-code

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits


@@ -11,11 +11,13 @@
 //
 
//===--===//
 
-#include "llvm/TargetParser/AArch64TargetParser.h"
+#include "llvm/Support/Error.h"

DavidSpickett wrote:

Why do we need to include Support/Error now?

These includes shouldn't change too much, the "module" include 
`AArch64TargetParser.h` will always come first regardless of name order, 
clang-format should enforce that for you.

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits


@@ -11,11 +11,13 @@
 //
 
//===--===//
 
-#include "llvm/TargetParser/AArch64TargetParser.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/TargetParser/AArch64TargetParser.h"
 #include "llvm/TargetParser/ARMTargetParserCommon.h"
 #include "llvm/TargetParser/Triple.h"
 #include 
+#include 

DavidSpickett wrote:

Probably don't need to include map if `AArch64TargetParser.h` already 
references it.

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits

https://github.com/DavidSpickett edited 
https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits


@@ -1016,7 +1017,8 @@ TEST(TargetParserTest, ARMPrintSupportedExtensions) {
 
   outs().flush();
   testing::internal::CaptureStdout();
-  ARM::PrintSupportedExtensions();
+  std::map EmptyMap;

DavidSpickett wrote:

All tests for this should include at least 1 description, "this is a 
description" is fine. Just to prove we don't crash.

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits


@@ -600,11 +601,17 @@ StringRef ARM::getARMCPUForArch(const llvm::Triple 
&Triple, StringRef MArch) {
   llvm_unreachable("invalid arch name");
 }
 
-void ARM::PrintSupportedExtensions() {
+void ARM::PrintSupportedExtensions(std::map llvmDescMap) 
{
   outs() << "All available -march extensions for ARM\n\n";
   for (const auto &Ext : ARCHExtNames) {
 // Extensions without a feature cannot be used with -march.
-if (!Ext.Feature.empty())
-  outs() << '\t' << Ext.Name << "\n";
+if (!Ext.Feature.empty()) {

DavidSpickett wrote:

Remove a level of indentation by making this:
```
if (Ext.Feature.empty())
  continue;

outs() << '\t' << Ext.Name << "\n";
<...>
```

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits


@@ -198,13 +199,21 @@ static int PrintSupportedExtensions(std::string 
TargetStr) {
   std::unique_ptr TheTargetMachine(
   TheTarget->createTargetMachine(TargetStr, "", "", Options, 
std::nullopt));
   const llvm::Triple &MachineTriple = TheTargetMachine->getTargetTriple();
+  const llvm::MCSubtargetInfo *MCInfo = TheTargetMachine->getMCSubtargetInfo();
+  const llvm::ArrayRef Features =
+MCInfo->getAllProcessorFeatures();
+
+  std::map llvmDescMap;
+  for (const llvm::SubtargetFeatureKV &feature : Features) {
+llvmDescMap.insert(std::make_pair(feature.Key, feature.Desc));

DavidSpickett wrote:

https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits


@@ -198,13 +199,21 @@ static int PrintSupportedExtensions(std::string 
TargetStr) {
   std::unique_ptr TheTargetMachine(
   TheTarget->createTargetMachine(TargetStr, "", "", Options, 
std::nullopt));
   const llvm::Triple &MachineTriple = TheTargetMachine->getTargetTriple();
+  const llvm::MCSubtargetInfo *MCInfo = TheTargetMachine->getMCSubtargetInfo();
+  const llvm::ArrayRef Features =
+MCInfo->getAllProcessorFeatures();
+
+  std::map llvmDescMap;

DavidSpickett wrote:

Potentially this could be https://llvm.org/doxygen/classllvm_1_1StringMap.html 
instead.

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits


@@ -210,24 +210,33 @@ static void verifyTables() {
 #endif
 }
 
-void llvm::riscvExtensionsHelp() {
+void llvm::riscvExtensionsHelp(std::map llvmDescMap) {
+
   outs() << "All available -march extensions for RISC-V\n\n";
-  outs() << '\t' << left_justify("Name", 20) << "Version\n";
+  outs() << '\t' << left_justify("Name", 20) << "Version";
+  outs() << (llvmDescMap.empty() ? "\n" : "\tDescription\n");
 
   RISCVISAInfo::OrderedExtensionMap ExtMap;
   for (const auto &E : SupportedExtensions)
 ExtMap[E.Name] = {E.Version.Major, E.Version.Minor};
-  for (const auto &E : ExtMap)
-outs() << format("\t%-20s%d.%d\n", E.first.c_str(), E.second.MajorVersion,
+  for (const auto &E : ExtMap) {
+outs() << format("\t%-20s%d.%d", E.first.c_str(), E.second.MajorVersion,
  E.second.MinorVersion);
+outs() << (llvmDescMap.empty() ? "\n"

DavidSpickett wrote:

In general I don't think we should assume that all named frontend features will 
be in the backend by the same name, and then also have a description.

Practically, that means I'd prefer we do a lookup for each name, expecting that 
it might fail. Instead of checking if the map is empty and if not doing an 
unconditional lookup.

In 99.9% of cases, the name probably matches. Maybe even has to match, but I 
know we've bent that rule in AArch64 in the past, and it wouldn't cost that 
much in terms of cpu time to do it that way. This is not a hot path, and we're 
spending time building a map already.

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall resolved 
https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits


@@ -87,6 +87,9 @@ class alignas(const Formula *) Formula {
  ArrayRef Operands,
  unsigned Value = 0);
 
+  // Parse Formulas using Arena rather than caling this function directly.
+  static Formula *parse(llvm::BumpPtrAllocator &Alloc, llvm::StringRef &);

sam-mccall wrote:

Right, oops!

https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall resolved 
https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall resolved 
https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall resolved 
https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits


@@ -95,4 +98,94 @@ BoolValue &Arena::makeBoolValue(const Formula &F) {
   return *It->second;
 }
 
+namespace {
+const Formula *parse(Arena &A, llvm::StringRef &In) {
+  auto EatWhitespace = [&] { In = In.ltrim(' '); };

sam-mccall wrote:

Renamed, hard to know if linebreaks etc are more likely to be formatting or 
errors at this point.

https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall resolved 
https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D159519: [clang][AST][ASTImporter] improve AST comparasion on VarDecl & GotoStmt

2023-09-19 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy accepted this revision.
donat.nagy added a comment.
This revision is now accepted and ready to land.

LGTM. I'm not very familiar with this area, but the change seems to be a very 
clean improvement.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159519

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


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits


@@ -258,114 +276,71 @@ TEST(SolverTest, IffWithUnits) {
 }
 
 TEST(SolverTest, IffWithUnitsConflict) {
-  ConstraintContext Ctx;
-  auto X = Ctx.atom();
-  auto Y = Ctx.atom();
-  auto XEqY = Ctx.iff(X, Y);
-  auto NotY = Ctx.neg(Y);
-
-  // (X <=> Y) ^ X  !Y
-  EXPECT_THAT(solve({XEqY, X, NotY}), unsat());
+  Arena A;
+  auto Constraints = parseAll(A, R"(
+ (V0 = V1)
+ V0
+ !V1
+  )");
+  EXPECT_THAT(solve(Constraints), unsat());
 }
 
 TEST(SolverTest, IffTransitiveConflict) {
-  ConstraintContext Ctx;
-  auto X = Ctx.atom();
-  auto Y = Ctx.atom();
-  auto Z = Ctx.atom();
-  auto XEqY = Ctx.iff(X, Y);
-  auto YEqZ = Ctx.iff(Y, Z);
-  auto NotX = Ctx.neg(X);
-
-  // (X <=> Y) ^ (Y <=> Z) ^ Z ^ !X
-  EXPECT_THAT(solve({XEqY, YEqZ, Z, NotX}), unsat());
+  Arena A;
+  auto Constraints = parseAll(A, R"(
+ (V0 = V1)
+ (V1 = V2)
+ V2
+ !V0
+  )");
+  EXPECT_THAT(solve(Constraints), unsat());
 }
 
 TEST(SolverTest, DeMorgan) {
-  ConstraintContext Ctx;
-  auto X = Ctx.atom();
-  auto Y = Ctx.atom();
-  auto Z = Ctx.atom();
-  auto W = Ctx.atom();
-
-  // !(X v Y) <=> !X ^ !Y
-  auto A = Ctx.iff(Ctx.neg(Ctx.disj(X, Y)), Ctx.conj(Ctx.neg(X), Ctx.neg(Y)));
-
-  // !(Z ^ W) <=> !Z v !W
-  auto B = Ctx.iff(Ctx.neg(Ctx.conj(Z, W)), Ctx.disj(Ctx.neg(Z), Ctx.neg(W)));
-
-  // A ^ B
-  EXPECT_THAT(solve({A, B}), sat(_));
+  Arena A;
+  auto Constraints = parseAll(A, R"(
+ (!(V0 | V1) = (!V0 & !V1))
+ (!(V2 & V3) = (!V2 | !V3))
+  )");
+  EXPECT_THAT(solve(Constraints), sat(_));
 }
 
 TEST(SolverTest, RespectsAdditionalConstraints) {
-  ConstraintContext Ctx;
-  auto X = Ctx.atom();
-  auto Y = Ctx.atom();
-  auto XEqY = Ctx.iff(X, Y);
-  auto NotY = Ctx.neg(Y);
-
-  // (X <=> Y) ^ X ^ !Y
-  EXPECT_THAT(solve({XEqY, X, NotY}), unsat());
+  Arena A;
+  auto Constraints = parseAll(A, R"(
+ (V0 = V1)
+ V0
+ !V1
+  )");
+  EXPECT_THAT(solve(Constraints), unsat());
 }
 
 TEST(SolverTest, ImplicationIsEquivalentToDNF) {
-  ConstraintContext Ctx;
-  auto X = Ctx.atom();
-  auto Y = Ctx.atom();
-  auto XImpliesY = Ctx.impl(X, Y);
-  auto XImpliesYDNF = Ctx.disj(Ctx.neg(X), Y);
-  auto NotEquivalent = Ctx.neg(Ctx.iff(XImpliesY, XImpliesYDNF));
-
-  // !((X => Y) <=> (!X v Y))
-  EXPECT_THAT(solve({NotEquivalent}), unsat());
+  Arena A;
+  auto Constraints = parseAll(A, R"(
+ !((V0 => V1) = (!V0 | V1))
+  )");
+  EXPECT_THAT(solve(Constraints), unsat());
 }
 
 TEST(SolverTest, ImplicationConflict) {
-  ConstraintContext Ctx;
-  auto X = Ctx.atom();
-  auto Y = Ctx.atom();
-  auto *XImplY = Ctx.impl(X, Y);
-  auto *XAndNotY = Ctx.conj(X, Ctx.neg(Y));
-
-  // X => Y ^ X ^ !Y
-  EXPECT_THAT(solve({XImplY, XAndNotY}), unsat());
-}
-
-TEST(SolverTest, LowTimeoutResultsInTimedOut) {
-  WatchedLiteralsSolver solver(10);
-  ConstraintContext Ctx;
-  auto X = Ctx.atom();
-  auto Y = Ctx.atom();
-  auto Z = Ctx.atom();
-  auto W = Ctx.atom();
-
-  // !(X v Y) <=> !X ^ !Y
-  auto A = Ctx.iff(Ctx.neg(Ctx.disj(X, Y)), Ctx.conj(Ctx.neg(X), Ctx.neg(Y)));
-
-  // !(Z ^ W) <=> !Z v !W
-  auto B = Ctx.iff(Ctx.neg(Ctx.conj(Z, W)), Ctx.disj(Ctx.neg(Z), Ctx.neg(W)));
-
-  // A ^ B
-  EXPECT_EQ(solver.solve({A, B}).getStatus(), 
Solver::Result::Status::TimedOut);
+  Arena A;
+  auto Constraints = parseAll(A, R"(
+ (V0 => V1)
+ (V0 & !V1)

sam-mccall wrote:

I'm not changing the formulas here - the test above uses three clauses (both 
before & after), and this one used two.

https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Disable OuterScope lambda indentation behaviour for constructor initializers (PR #66755)

2023-09-19 Thread Jon Phillips via cfe-commits

https://github.com/jp4a50 created 
https://github.com/llvm/llvm-project/pull/66755

By default, OuterScope aligns lambdas to the beginning of the current line. 
This makes sense for most types of statements within code blocks but leads to 
unappealing and misleading indentation for lambdas within constructor 
initializers.

>From e07d263a37ef37a21bb5cf424b14be83088eed3d Mon Sep 17 00:00:00 2001
From: Jon Phillips 
Date: Tue, 19 Sep 2023 10:29:57 +0100
Subject: [PATCH] [clang-format] Disable OuterScope lambda indentation
 behaviour for constructor initializers

By default, OuterScope aligns lambdas to the beginning of the current
line. This makes sense for most types of statements within code blocks
but leads to unappealing and misleading indentation for lambdas within
constructor initializers.
---
 clang/lib/Format/ContinuationIndenter.cpp |  3 ++-
 clang/unittests/Format/FormatTest.cpp | 30 +--
 2 files changed, 25 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index deb3e554fdc124b..0fa70eace90f416 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1955,7 +1955,8 @@ void 
ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
 
 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
   if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
-  State.NextToken->is(TT_LambdaLBrace)) {
+  State.NextToken->is(TT_LambdaLBrace) && State.Line &&
+  !State.Line->MightBeFunctionDecl) {
 State.Stack.back().NestedBlockIndent = State.FirstIndent;
   }
   unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 0d0fbdb84e3271b..cb6b22b32e63350 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -22537,10 +22537,12 @@ TEST_F(FormatTest, FormatsLambdas) {
"  }\n"
"}",
Style);
-  verifyFormat("std::sort(v.begin(), v.end(),\n"
-   "  [](const auto &foo, const auto &bar) {\n"
-   "  return foo.baz < bar.baz;\n"
-   "});",
+  verifyFormat("void test() {\n"
+   "  std::sort(v.begin(), v.end(),\n"
+   "[](const auto &foo, const auto &bar) {\n"
+   "return foo.baz < bar.baz;\n"
+   "  });\n"
+   "};",
Style);
   verifyFormat("void test() {\n"
"  (\n"
@@ -22589,9 +22591,23 @@ TEST_F(FormatTest, FormatsLambdas) {
   verifyFormat("Namespace::Foo::Foo(LongClassName bar,\n"
"AnotherLongClassName baz)\n"
": baz{baz}, func{[&] {\n"
-   "  auto qux = bar;\n"
-   "  return aFunkyFunctionCall(qux);\n"
-   "}} {}",
+   "auto qux = bar;\n"
+   "return aFunkyFunctionCall(qux);\n"
+   "  }} {}",
+   Style);
+  verifyFormat("void foo() {\n"
+   "  class Foo {\n"
+   "  public:\n"
+   "Foo()\n"
+   ": qux{[](int quux) {\n"
+   "auto tmp = quux;\n"
+   "return tmp;\n"
+   "  }} {}\n"
+   "\n"
+   "  private:\n"
+   "std::function qux;\n"
+   "  };\n"
+   "}\n",
Style);
   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
   // FIXME: The following test should pass, but fails at the time of writing.

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


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits


@@ -95,4 +98,94 @@ BoolValue &Arena::makeBoolValue(const Formula &F) {
   return *It->second;
 }
 
+namespace {
+const Formula *parse(Arena &A, llvm::StringRef &In) {
+  auto EatWhitespace = [&] { In = In.ltrim(' '); };
+  EatWhitespace();
+
+  if (In.consume_front("!")) {
+if (auto *Arg = parse(A, In))
+  return &A.makeNot(*Arg);
+return nullptr;
+  }
+
+  if (In.consume_front("(")) {
+auto *Arg1 = parse(A, In);
+if (!Arg1)
+  return nullptr;
+
+EatWhitespace();
+decltype(&Arena::makeOr) Op;
+if (In.consume_front("|"))
+  Op = &Arena::makeOr;
+else if (In.consume_front("&"))
+  Op = &Arena::makeAnd;
+else if (In.consume_front("=>"))
+  Op = &Arena::makeImplies;
+else if (In.consume_front("="))
+  Op = &Arena::makeEquals;
+else
+  return nullptr;
+
+auto *Arg2 = parse(A, In);
+if (!Arg2)
+  return nullptr;
+
+EatWhitespace();
+if (!In.consume_front(")"))

sam-mccall wrote:

This makes sense, but usefully characterizing errors adds complexity - I'd like 
to see if this is really needed first.
(The error handling here was sufficient for the dumb mistakes I made when 
writing testcases...)

https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Disable OuterScope lambda indentation behaviour for constructor initializers (PR #66755)

2023-09-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format


Changes

By default, OuterScope aligns lambdas to the beginning of the current line. 
This makes sense for most types of statements within code blocks but leads to 
unappealing and misleading indentation for lambdas within constructor 
initializers.

---
Full diff: https://github.com/llvm/llvm-project/pull/66755.diff


2 Files Affected:

- (modified) clang/lib/Format/ContinuationIndenter.cpp (+2-1) 
- (modified) clang/unittests/Format/FormatTest.cpp (+23-7) 


``diff
diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index deb3e554fdc124b..0fa70eace90f416 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1955,7 +1955,8 @@ void 
ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
 
 void ContinuationIndenter::moveStateToNewBlock(LineState &State) {
   if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
-  State.NextToken->is(TT_LambdaLBrace)) {
+  State.NextToken->is(TT_LambdaLBrace) && State.Line &&
+  !State.Line->MightBeFunctionDecl) {
 State.Stack.back().NestedBlockIndent = State.FirstIndent;
   }
   unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 0d0fbdb84e3271b..cb6b22b32e63350 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -22537,10 +22537,12 @@ TEST_F(FormatTest, FormatsLambdas) {
"  }\n"
"}",
Style);
-  verifyFormat("std::sort(v.begin(), v.end(),\n"
-   "  [](const auto &foo, const auto &bar) {\n"
-   "  return foo.baz < bar.baz;\n"
-   "});",
+  verifyFormat("void test() {\n"
+   "  std::sort(v.begin(), v.end(),\n"
+   "[](const auto &foo, const auto &bar) {\n"
+   "return foo.baz < bar.baz;\n"
+   "  });\n"
+   "};",
Style);
   verifyFormat("void test() {\n"
"  (\n"
@@ -22589,9 +22591,23 @@ TEST_F(FormatTest, FormatsLambdas) {
   verifyFormat("Namespace::Foo::Foo(LongClassName bar,\n"
"AnotherLongClassName baz)\n"
": baz{baz}, func{[&] {\n"
-   "  auto qux = bar;\n"
-   "  return aFunkyFunctionCall(qux);\n"
-   "}} {}",
+   "auto qux = bar;\n"
+   "return aFunkyFunctionCall(qux);\n"
+   "  }} {}",
+   Style);
+  verifyFormat("void foo() {\n"
+   "  class Foo {\n"
+   "  public:\n"
+   "Foo()\n"
+   ": qux{[](int quux) {\n"
+   "auto tmp = quux;\n"
+   "return tmp;\n"
+   "  }} {}\n"
+   "\n"
+   "  private:\n"
+   "std::function qux;\n"
+   "  };\n"
+   "}\n",
Style);
   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
   // FIXME: The following test should pass, but fails at the time of writing.

``




https://github.com/llvm/llvm-project/pull/66755
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits


@@ -95,4 +98,94 @@ BoolValue &Arena::makeBoolValue(const Formula &F) {
   return *It->second;
 }
 
+namespace {
+const Formula *parse(Arena &A, llvm::StringRef &In) {
+  auto EatWhitespace = [&] { In = In.ltrim(' '); };
+  EatWhitespace();
+
+  if (In.consume_front("!")) {
+if (auto *Arg = parse(A, In))
+  return &A.makeNot(*Arg);
+return nullptr;
+  }
+
+  if (In.consume_front("(")) {
+auto *Arg1 = parse(A, In);
+if (!Arg1)
+  return nullptr;
+
+EatWhitespace();
+decltype(&Arena::makeOr) Op;
+if (In.consume_front("|"))
+  Op = &Arena::makeOr;
+else if (In.consume_front("&"))
+  Op = &Arena::makeAnd;
+else if (In.consume_front("=>"))
+  Op = &Arena::makeImplies;
+else if (In.consume_front("="))
+  Op = &Arena::makeEquals;
+else
+  return nullptr;
+
+auto *Arg2 = parse(A, In);
+if (!Arg2)
+  return nullptr;
+
+EatWhitespace();
+if (!In.consume_front(")"))
+  return nullptr;
+
+return &(A.*Op)(*Arg1, *Arg2);
+  }
+
+  if (In.consume_front("V")) {

sam-mccall wrote:

Agree it's too restrictive, but solving it is a slightly bigger scope and I'm 
not sure of the details.

I do think it's important that if you parse a formula that uses certain names 
for the variables, then you can print it out again with the same names. 
(Parsing is mostly useful when formulas are large and have many variables...). 
`V0` is the default name of `Atom{0}` etc, so these variables "round-trip" OK.

To round-trip other variables we need to store their names somewhere. A map 
output-param works (and we have support for printing this way) but it's not 
very ergonomic, and is easy to forget to plumb around.
I've been thinking variable names should live on the arena (`Arena::makeAtom() 
-> Atom`, `Arena::nameAtom(Atom, Twine)` or so). This would provide a fairly 
centralized and natural way to e.g. name flow condition vars. And `parse()` 
could create an atom and name it when it encounters an unknown variable name.

However there's some stuff to work out here: is name tracking always on? do we 
also want to name values/locations, which might help provide atom names? what 
about Formula's `operator<<` which won't find the names?

Added a `FIXME` to handle other names.

https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall updated 
https://github.com/llvm/llvm-project/pull/66424

>From 35b33561af918fc2e13af9de18af6b181535ce49 Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Thu, 14 Sep 2023 21:36:50 +0200
Subject: [PATCH 1/2] [dataflow] Parse formulas from text

My immediate use for this is not in checked-in code, but rather the
ability to plug printed flow conditions (from analysis logs) back into
sat solver unittests to reproduce slowness.

It does allow simplifying some of the existing solver tests, though.
---
 .../clang/Analysis/FlowSensitive/Arena.h  |   5 +
 .../clang/Analysis/FlowSensitive/Formula.h|   3 +
 clang/lib/Analysis/FlowSensitive/Arena.cpp|  93 +++
 clang/lib/Analysis/FlowSensitive/Formula.cpp  |   1 +
 .../Analysis/FlowSensitive/ArenaTest.cpp  |  44 +
 .../Analysis/FlowSensitive/SolverTest.cpp | 153 --
 6 files changed, 210 insertions(+), 89 deletions(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/Arena.h 
b/clang/include/clang/Analysis/FlowSensitive/Arena.h
index 373697dc7379c53..4e07053aae1af53 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Arena.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Arena.h
@@ -11,6 +11,7 @@
 #include "clang/Analysis/FlowSensitive/Formula.h"
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "llvm/ADT/StringRef.h"
 #include 
 
 namespace clang::dataflow {
@@ -109,6 +110,10 @@ class Arena {
 return makeAtomRef(Value ? True : False);
   }
 
+  // Parses a formula from its textual representation.
+  // This may refer to atoms that were not produced by makeAtom() yet!
+  llvm::Expected parseFormula(llvm::StringRef);
+
   /// Returns a new atomic boolean variable, distinct from any other.
   Atom makeAtom() { return static_cast(NextAtom++); };
 
diff --git a/clang/include/clang/Analysis/FlowSensitive/Formula.h 
b/clang/include/clang/Analysis/FlowSensitive/Formula.h
index 64fe8f5b630a0f7..ac95a9ac7d50a1c 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Formula.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Formula.h
@@ -87,6 +87,9 @@ class alignas(const Formula *) Formula {
  ArrayRef Operands,
  unsigned Value = 0);
 
+  // Parse Formulas using Arena rather than caling this function directly.
+  static Formula *parse(llvm::BumpPtrAllocator &Alloc, llvm::StringRef &);
+
 private:
   Formula() = default;
   Formula(const Formula &) = delete;
diff --git a/clang/lib/Analysis/FlowSensitive/Arena.cpp 
b/clang/lib/Analysis/FlowSensitive/Arena.cpp
index a12da2d9b555eb7..557feb373287632 100644
--- a/clang/lib/Analysis/FlowSensitive/Arena.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Arena.cpp
@@ -7,7 +7,10 @@
 
//===--===//
 
 #include "clang/Analysis/FlowSensitive/Arena.h"
+#include "clang/Analysis/FlowSensitive/Formula.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "llvm/Support/Error.h"
+#include 
 
 namespace clang::dataflow {
 
@@ -95,4 +98,94 @@ BoolValue &Arena::makeBoolValue(const Formula &F) {
   return *It->second;
 }
 
+namespace {
+const Formula *parse(Arena &A, llvm::StringRef &In) {
+  auto EatWhitespace = [&] { In = In.ltrim(' '); };
+  EatWhitespace();
+
+  if (In.consume_front("!")) {
+if (auto *Arg = parse(A, In))
+  return &A.makeNot(*Arg);
+return nullptr;
+  }
+
+  if (In.consume_front("(")) {
+auto *Arg1 = parse(A, In);
+if (!Arg1)
+  return nullptr;
+
+EatWhitespace();
+decltype(&Arena::makeOr) Op;
+if (In.consume_front("|"))
+  Op = &Arena::makeOr;
+else if (In.consume_front("&"))
+  Op = &Arena::makeAnd;
+else if (In.consume_front("=>"))
+  Op = &Arena::makeImplies;
+else if (In.consume_front("="))
+  Op = &Arena::makeEquals;
+else
+  return nullptr;
+
+auto *Arg2 = parse(A, In);
+if (!Arg2)
+  return nullptr;
+
+EatWhitespace();
+if (!In.consume_front(")"))
+  return nullptr;
+
+return &(A.*Op)(*Arg1, *Arg2);
+  }
+
+  if (In.consume_front("V")) {
+std::underlying_type_t At;
+if (In.consumeInteger(10, At))
+  return nullptr;
+return &A.makeAtomRef(static_cast(At));
+  }
+
+  if (In.consume_front("true"))
+return &A.makeLiteral(true);
+  if (In.consume_front("false"))
+return &A.makeLiteral(false);
+
+  return nullptr;
+}
+
+class FormulaParseError : public llvm::ErrorInfo {
+  unsigned Offset;
+  std::string Formula;
+
+public:
+  static char ID;
+  FormulaParseError(llvm::StringRef Formula, unsigned Offset)
+  : Offset(Offset), Formula(Formula) {}
+
+  void log(raw_ostream &OS) const override {
+OS << "bad formula at offset " << Offset << "\n";
+OS << Formula << "\n";
+OS.indent(Offset) << "^";
+  }
+
+  std::error_code convertToErrorCode() const override {
+return std::make_error_code(std::errc::invalid_argument);

[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall resolved 
https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall resolved 
https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall resolved 
https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall updated 
https://github.com/llvm/llvm-project/pull/66424

>From 35b33561af918fc2e13af9de18af6b181535ce49 Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Thu, 14 Sep 2023 21:36:50 +0200
Subject: [PATCH 1/3] [dataflow] Parse formulas from text

My immediate use for this is not in checked-in code, but rather the
ability to plug printed flow conditions (from analysis logs) back into
sat solver unittests to reproduce slowness.

It does allow simplifying some of the existing solver tests, though.
---
 .../clang/Analysis/FlowSensitive/Arena.h  |   5 +
 .../clang/Analysis/FlowSensitive/Formula.h|   3 +
 clang/lib/Analysis/FlowSensitive/Arena.cpp|  93 +++
 clang/lib/Analysis/FlowSensitive/Formula.cpp  |   1 +
 .../Analysis/FlowSensitive/ArenaTest.cpp  |  44 +
 .../Analysis/FlowSensitive/SolverTest.cpp | 153 --
 6 files changed, 210 insertions(+), 89 deletions(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/Arena.h 
b/clang/include/clang/Analysis/FlowSensitive/Arena.h
index 373697dc7379c53..4e07053aae1af53 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Arena.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Arena.h
@@ -11,6 +11,7 @@
 #include "clang/Analysis/FlowSensitive/Formula.h"
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "llvm/ADT/StringRef.h"
 #include 
 
 namespace clang::dataflow {
@@ -109,6 +110,10 @@ class Arena {
 return makeAtomRef(Value ? True : False);
   }
 
+  // Parses a formula from its textual representation.
+  // This may refer to atoms that were not produced by makeAtom() yet!
+  llvm::Expected parseFormula(llvm::StringRef);
+
   /// Returns a new atomic boolean variable, distinct from any other.
   Atom makeAtom() { return static_cast(NextAtom++); };
 
diff --git a/clang/include/clang/Analysis/FlowSensitive/Formula.h 
b/clang/include/clang/Analysis/FlowSensitive/Formula.h
index 64fe8f5b630a0f7..ac95a9ac7d50a1c 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Formula.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Formula.h
@@ -87,6 +87,9 @@ class alignas(const Formula *) Formula {
  ArrayRef Operands,
  unsigned Value = 0);
 
+  // Parse Formulas using Arena rather than caling this function directly.
+  static Formula *parse(llvm::BumpPtrAllocator &Alloc, llvm::StringRef &);
+
 private:
   Formula() = default;
   Formula(const Formula &) = delete;
diff --git a/clang/lib/Analysis/FlowSensitive/Arena.cpp 
b/clang/lib/Analysis/FlowSensitive/Arena.cpp
index a12da2d9b555eb7..557feb373287632 100644
--- a/clang/lib/Analysis/FlowSensitive/Arena.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Arena.cpp
@@ -7,7 +7,10 @@
 
//===--===//
 
 #include "clang/Analysis/FlowSensitive/Arena.h"
+#include "clang/Analysis/FlowSensitive/Formula.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "llvm/Support/Error.h"
+#include 
 
 namespace clang::dataflow {
 
@@ -95,4 +98,94 @@ BoolValue &Arena::makeBoolValue(const Formula &F) {
   return *It->second;
 }
 
+namespace {
+const Formula *parse(Arena &A, llvm::StringRef &In) {
+  auto EatWhitespace = [&] { In = In.ltrim(' '); };
+  EatWhitespace();
+
+  if (In.consume_front("!")) {
+if (auto *Arg = parse(A, In))
+  return &A.makeNot(*Arg);
+return nullptr;
+  }
+
+  if (In.consume_front("(")) {
+auto *Arg1 = parse(A, In);
+if (!Arg1)
+  return nullptr;
+
+EatWhitespace();
+decltype(&Arena::makeOr) Op;
+if (In.consume_front("|"))
+  Op = &Arena::makeOr;
+else if (In.consume_front("&"))
+  Op = &Arena::makeAnd;
+else if (In.consume_front("=>"))
+  Op = &Arena::makeImplies;
+else if (In.consume_front("="))
+  Op = &Arena::makeEquals;
+else
+  return nullptr;
+
+auto *Arg2 = parse(A, In);
+if (!Arg2)
+  return nullptr;
+
+EatWhitespace();
+if (!In.consume_front(")"))
+  return nullptr;
+
+return &(A.*Op)(*Arg1, *Arg2);
+  }
+
+  if (In.consume_front("V")) {
+std::underlying_type_t At;
+if (In.consumeInteger(10, At))
+  return nullptr;
+return &A.makeAtomRef(static_cast(At));
+  }
+
+  if (In.consume_front("true"))
+return &A.makeLiteral(true);
+  if (In.consume_front("false"))
+return &A.makeLiteral(false);
+
+  return nullptr;
+}
+
+class FormulaParseError : public llvm::ErrorInfo {
+  unsigned Offset;
+  std::string Formula;
+
+public:
+  static char ID;
+  FormulaParseError(llvm::StringRef Formula, unsigned Offset)
+  : Offset(Offset), Formula(Formula) {}
+
+  void log(raw_ostream &OS) const override {
+OS << "bad formula at offset " << Offset << "\n";
+OS << Formula << "\n";
+OS.indent(Offset) << "^";
+  }
+
+  std::error_code convertToErrorCode() const override {
+return std::make_error_code(std::errc::invalid_argument);

[clang] ad4a513 - [clang][CFG] Cleanup functions

2023-09-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-09-19T11:56:44+02:00
New Revision: ad4a513026d8f15f40ac5a6dede6ad3aabfb

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

LOG: [clang][CFG] Cleanup functions

Add declarations declared with attribute(cleanup(...)) to the CFG,
similar to destructors.

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

Added: 


Modified: 
clang/include/clang/Analysis/CFG.h
clang/lib/Analysis/CFG.cpp
clang/lib/Analysis/PathDiagnostic.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/test/Analysis/scopes-cfg-output.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/CFG.h 
b/clang/include/clang/Analysis/CFG.h
index cf4fa2da2a358e7..67383bb316d3183 100644
--- a/clang/include/clang/Analysis/CFG.h
+++ b/clang/include/clang/Analysis/CFG.h
@@ -14,10 +14,11 @@
 #ifndef LLVM_CLANG_ANALYSIS_CFG_H
 #define LLVM_CLANG_ANALYSIS_CFG_H
 
-#include "clang/Analysis/Support/BumpVector.h"
-#include "clang/Analysis/ConstructionContext.h"
+#include "clang/AST/Attr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
+#include "clang/Analysis/ConstructionContext.h"
+#include "clang/Analysis/Support/BumpVector.h"
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/GraphTraits.h"
@@ -74,7 +75,8 @@ class CFGElement {
 MemberDtor,
 TemporaryDtor,
 DTOR_BEGIN = AutomaticObjectDtor,
-DTOR_END = TemporaryDtor
+DTOR_END = TemporaryDtor,
+CleanupFunction,
   };
 
 protected:
@@ -383,6 +385,32 @@ class CFGImplicitDtor : public CFGElement {
   }
 };
 
+class CFGCleanupFunction final : public CFGElement {
+public:
+  CFGCleanupFunction() = default;
+  CFGCleanupFunction(const VarDecl *VD)
+  : CFGElement(Kind::CleanupFunction, VD) {
+assert(VD->hasAttr());
+  }
+
+  const VarDecl *getVarDecl() const {
+return static_cast(Data1.getPointer());
+  }
+
+  /// Returns the function to be called when cleaning up the var decl.
+  const FunctionDecl *getFunctionDecl() const {
+const CleanupAttr *A = getVarDecl()->getAttr();
+return A->getFunctionDecl();
+  }
+
+private:
+  friend class CFGElement;
+
+  static bool isKind(const CFGElement E) {
+return E.getKind() == Kind::CleanupFunction;
+  }
+};
+
 /// Represents C++ object destructor implicitly generated for automatic object
 /// or temporary bound to const reference at the point of leaving its local
 /// scope.
@@ -1142,6 +1170,10 @@ class CFGBlock {
 Elements.push_back(CFGAutomaticObjDtor(VD, S), C);
   }
 
+  void appendCleanupFunction(const VarDecl *VD, BumpVectorContext &C) {
+Elements.push_back(CFGCleanupFunction(VD), C);
+  }
+
   void appendLifetimeEnds(VarDecl *VD, Stmt *S, BumpVectorContext &C) {
 Elements.push_back(CFGLifetimeEnds(VD, S), C);
   }

diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index b82f9010a83f771..03ab4c6fdf29cae 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -881,6 +881,10 @@ class CFGBuilder {
 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
   }
 
+  void appendCleanupFunction(CFGBlock *B, VarDecl *VD) {
+B->appendCleanupFunction(VD, cfg->getBumpVectorContext());
+  }
+
   void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
   }
@@ -1346,7 +1350,8 @@ class CFGBuilder {
 return {};
   }
 
-  bool hasTrivialDestructor(VarDecl *VD);
+  bool hasTrivialDestructor(const VarDecl *VD) const;
+  bool needsAutomaticDestruction(const VarDecl *VD) const;
 };
 
 } // namespace
@@ -1861,14 +1866,14 @@ void 
CFGBuilder::addAutomaticObjDestruction(LocalScope::const_iterator B,
   if (B == E)
 return;
 
-  SmallVector DeclsNonTrivial;
-  DeclsNonTrivial.reserve(B.distance(E));
+  SmallVector DeclsNeedDestruction;
+  DeclsNeedDestruction.reserve(B.distance(E));
 
   for (VarDecl* D : llvm::make_range(B, E))
-if (!hasTrivialDestructor(D))
-  DeclsNonTrivial.push_back(D);
+if (needsAutomaticDestruction(D))
+  DeclsNeedDestruction.push_back(D);
 
-  for (VarDecl *VD : llvm::reverse(DeclsNonTrivial)) {
+  for (VarDecl *VD : llvm::reverse(DeclsNeedDestruction)) {
 if (BuildOpts.AddImplicitDtors) {
   // If this destructor is marked as a no-return destructor, we need to
   // create a new block for the destructor which does not have as a
@@ -1879,7 +1884,8 @@ void 
CFGBuilder::addAutomaticObjDestruction(LocalScope::const_iterator B,
 Ty = getReferenceInitTemporaryType(VD->getInit());
   Ty = Context->getBaseElementType(Ty);
 
-  if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
+  const CXXRecordDecl *CRD = Ty->getAsCXXRecordDecl();
+  if (CRD && CRD->isAnyDestructorNoReturn())
 Bloc

[PATCH] D157385: [clang][CFG] Cleanup functions

2023-09-19 Thread Timm Bäder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGad4a51302777: [clang][CFG] Cleanup functions (authored by 
tbaeder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157385

Files:
  clang/include/clang/Analysis/CFG.h
  clang/lib/Analysis/CFG.cpp
  clang/lib/Analysis/PathDiagnostic.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/test/Analysis/scopes-cfg-output.cpp

Index: clang/test/Analysis/scopes-cfg-output.cpp
===
--- clang/test/Analysis/scopes-cfg-output.cpp
+++ clang/test/Analysis/scopes-cfg-output.cpp
@@ -1419,3 +1419,68 @@
 }
   }
 }
+
+// CHECK:  [B1]
+// CHECK-NEXT:   1: CFGScopeBegin(i)
+// CHECK-NEXT:   2: int i __attribute__((cleanup(cleanup_int)));
+// CHECK-NEXT:   3: CleanupFunction (cleanup_int)
+// CHECK-NEXT:   4: CFGScopeEnd(i)
+void cleanup_int(int *i);
+void test_cleanup_functions() {
+  int i __attribute__((cleanup(cleanup_int)));
+}
+
+// CHECK:  [B1]
+// CHECK-NEXT:1: 10
+// CHECK-NEXT:2: i
+// CHECK-NEXT:3: [B1.2] = [B1.1]
+// CHECK-NEXT:4: return;
+// CHECK-NEXT:5: CleanupFunction (cleanup_int)
+// CHECK-NEXT:6: CFGScopeEnd(i)
+// CHECK-NEXT:Preds (1): B3
+// CHECK-NEXT:Succs (1): B0
+// CHECK:  [B2]
+// CHECK-NEXT:1: return;
+// CHECK-NEXT:2: CleanupFunction (cleanup_int)
+// CHECK-NEXT:3: CFGScopeEnd(i)
+// CHECK-NEXT:Preds (1): B3
+// CHECK-NEXT:Succs (1): B0
+// CHECK:  [B3]
+// CHECK-NEXT:1: CFGScopeBegin(i)
+// CHECK-NEXT:2: int i __attribute__((cleanup(cleanup_int)));
+// CHECK-NEXT:3: m
+// CHECK-NEXT:4: [B3.3] (ImplicitCastExpr, LValueToRValue, int)
+// CHECK-NEXT:5: 1
+// CHECK-NEXT:6: [B3.4] == [B3.5]
+// CHECK-NEXT:T: if [B3.6]
+// CHECK-NEXT:Preds (1): B4
+// CHECK-NEXT:Succs (2): B2 B1
+void test_cleanup_functions2(int m) {
+  int i __attribute__((cleanup(cleanup_int)));
+
+  if (m == 1) {
+return;
+  }
+
+  i = 10;
+  return;
+}
+
+// CHECK:   [B1]
+// CHECK-NEXT:1: CFGScopeBegin(f)
+// CHECK-NEXT:2:  (CXXConstructExpr, [B1.3], F)
+// CHECK-NEXT:3: __attribute__((cleanup(cleanup_F))) F f;
+// CHECK-NEXT:4: CleanupFunction (cleanup_F)
+// CHECK-NEXT:5: [B1.3].~F() (Implicit destructor)
+// CHECK-NEXT:6: CFGScopeEnd(f)
+// CHECK-NEXT:Preds (1): B2
+// CHECK-NEXT:Succs (1): B0
+class F {
+public:
+  ~F();
+};
+void cleanup_F(F *f);
+
+void test() {
+  F f __attribute((cleanup(cleanup_F)));
+}
Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -993,6 +993,7 @@
   ProcessLoopExit(E.castAs().getLoopStmt(), Pred);
   return;
 case CFGElement::LifetimeEnds:
+case CFGElement::CleanupFunction:
 case CFGElement::ScopeBegin:
 case CFGElement::ScopeEnd:
   return;
Index: clang/lib/Analysis/PathDiagnostic.cpp
===
--- clang/lib/Analysis/PathDiagnostic.cpp
+++ clang/lib/Analysis/PathDiagnostic.cpp
@@ -567,6 +567,7 @@
   }
   case CFGElement::ScopeBegin:
   case CFGElement::ScopeEnd:
+  case CFGElement::CleanupFunction:
 llvm_unreachable("not yet implemented!");
   case CFGElement::LifetimeEnds:
   case CFGElement::LoopExit:
Index: clang/lib/Analysis/CFG.cpp
===
--- clang/lib/Analysis/CFG.cpp
+++ clang/lib/Analysis/CFG.cpp
@@ -881,6 +881,10 @@
 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
   }
 
+  void appendCleanupFunction(CFGBlock *B, VarDecl *VD) {
+B->appendCleanupFunction(VD, cfg->getBumpVectorContext());
+  }
+
   void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
   }
@@ -1346,7 +1350,8 @@
 return {};
   }
 
-  bool hasTrivialDestructor(VarDecl *VD);
+  bool hasTrivialDestructor(const VarDecl *VD) const;
+  bool needsAutomaticDestruction(const VarDecl *VD) const;
 };
 
 } // namespace
@@ -1861,14 +1866,14 @@
   if (B == E)
 return;
 
-  SmallVector DeclsNonTrivial;
-  DeclsNonTrivial.reserve(B.distance(E));
+  SmallVector DeclsNeedDestruction;
+  DeclsNeedDestruction.reserve(B.distance(E));
 
   for (VarDecl* D : llvm::make_range(B, E))
-if (!hasTrivialDestructor(D))
-  DeclsNonTrivial.push_back(D);
+if (needsAutomaticDestruction(D))
+  DeclsNeedDestruction.push_back(D);
 
-  for (VarDecl *VD : llvm::reverse(DeclsNonTrivial)) {
+  for (VarDecl *VD : llvm::reverse(DeclsNeedDestruction)) {
 if (BuildOpts.AddImplicitDtors) {
   // If this destructor is marked as a no-return destructor, we need to
   // create a new block for the destructor which does not have as a
@@ -1879,7 

[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread Balint Cristian via cfe-commits


@@ -210,24 +210,33 @@ static void verifyTables() {
 #endif
 }
 
-void llvm::riscvExtensionsHelp() {
+void llvm::riscvExtensionsHelp(std::map llvmDescMap) {
+
   outs() << "All available -march extensions for RISC-V\n\n";
-  outs() << '\t' << left_justify("Name", 20) << "Version\n";
+  outs() << '\t' << left_justify("Name", 20) << "Version";
+  outs() << (llvmDescMap.empty() ? "\n" : "\tDescription\n");
 
   RISCVISAInfo::OrderedExtensionMap ExtMap;
   for (const auto &E : SupportedExtensions)
 ExtMap[E.Name] = {E.Version.Major, E.Version.Minor};
-  for (const auto &E : ExtMap)
-outs() << format("\t%-20s%d.%d\n", E.first.c_str(), E.second.MajorVersion,
+  for (const auto &E : ExtMap) {
+outs() << format("\t%-20s%d.%d", E.first.c_str(), E.second.MajorVersion,
  E.second.MinorVersion);
+outs() << (llvmDescMap.empty() ? "\n"

cbalint13 wrote:

> In general I don't think we should assume that all named frontend features 
> will be in the backend by the same name, and then also have a description.

Yes, there are misses already, very few ones (less then five for all the 3 
arches).
But this will encourage us to a better house-keeping in tablegen (backend) vs. 
here (frontend).

> Practically, that means I'd prefer we do a lookup for each name, expecting 
> that it might fail. Instead of checking if the map is empty and if not doing 
> an unconditional lookup.

The ```llvmDescMap.empty()``` is for other reason, I was thinking to make the 
whole ```Description``` column optional. It is useful for unit-test to bypass 
the whole target-machine creation saga and just look at the essential mandatory 
two columns (without descriptions column in test-mode).

* See in ```llvm/unittests/Support/RISCVISAInfoTest.cpp```
```
  std::map EmptyMap;
  llvm::riscvExtensionsHelp(EmptyMap);
```
Basically with this feature we have an option to skip "Description" column at 
all.


> In 99.9% of cases, the name probably matches. Maybe even has to match, but I 
> know we've bent that rule in AArch64 in the past, and it wouldn't cost that 
> much in terms of cpu time to do it that way. This is not a hot path, and 
> we're spending time building a map already.

The features amount per arch is less than a hundred, this is a user-help-menu 
anyway guiding the user.






https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread Balint Cristian via cfe-commits


@@ -11,11 +11,13 @@
 //
 
//===--===//
 
-#include "llvm/TargetParser/AArch64TargetParser.h"
+#include "llvm/Support/Error.h"

cbalint13 wrote:

It was for format()```, will double-check to see for a closer header for 
```llvm::format()```.

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread Balint Cristian via cfe-commits

https://github.com/cbalint13 edited 
https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread Balint Cristian via cfe-commits


@@ -11,11 +11,13 @@
 //
 
//===--===//
 
-#include "llvm/TargetParser/AArch64TargetParser.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/TargetParser/AArch64TargetParser.h"
 #include "llvm/TargetParser/ARMTargetParserCommon.h"
 #include "llvm/TargetParser/Triple.h"
 #include 
+#include 

cbalint13 wrote:

> Probably don't need to include map if `AArch64TargetParser.h` already 
> references it.

It was included before, i just re-arrange in alphabetical (clang-format).

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread Balint Cristian via cfe-commits


@@ -600,11 +601,17 @@ StringRef ARM::getARMCPUForArch(const llvm::Triple 
&Triple, StringRef MArch) {
   llvm_unreachable("invalid arch name");
 }
 
-void ARM::PrintSupportedExtensions() {
+void ARM::PrintSupportedExtensions(std::map llvmDescMap) 
{
   outs() << "All available -march extensions for ARM\n\n";
   for (const auto &Ext : ARCHExtNames) {
 // Extensions without a feature cannot be used with -march.
-if (!Ext.Feature.empty())
-  outs() << '\t' << Ext.Name << "\n";
+if (!Ext.Feature.empty()) {
+  if (llvmDescMap.empty()) {
+outs() << '\t' << Ext.Name << "\n";
+  } else {
+outs() << format("\t%-20s", Ext.Name.str().c_str());
+outs() << "\t\t" << llvmDescMap[Ext.Name] << "\n";

cbalint13 wrote:

> This can be one call to outs().

The ```if-else``` It is due to separation of "Description" column as optional.
To compress the 2*outs (inside else) format then will be quite long expansion: 
```llvmDescMap["experimental-"+Ext.Name].str().c_str() ```

Will try again, but spent quite some time on this very estetic part.


https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread Balint Cristian via cfe-commits


@@ -1016,7 +1017,8 @@ TEST(TargetParserTest, ARMPrintSupportedExtensions) {
 
   outs().flush();
   testing::internal::CaptureStdout();
-  ARM::PrintSupportedExtensions();
+  std::map EmptyMap;

cbalint13 wrote:

Will address this, even by adding a dummy description (to skip whole 
target-machine creation +feature-query).


https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread Balint Cristian via cfe-commits

cbalint13 wrote:

@DavidSpickett 


Thank you for the review time, will address all the concerns and be back with a 
re-review request.


https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread Balint Cristian via cfe-commits

https://github.com/cbalint13 edited 
https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread Balint Cristian via cfe-commits

https://github.com/cbalint13 edited 
https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread Balint Cristian via cfe-commits

https://github.com/cbalint13 edited 
https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clangd] Allow --query-driver to match a dot-normalized form of the path (PR #66757)

2023-09-19 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall created 
https://github.com/llvm/llvm-project/pull/66757

(In addition to the un-normalized form, so this is back-compatible)


>From 1923a5142f9cbd3556bba599b611ae8a1bbec776 Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Tue, 19 Sep 2023 12:16:54 +0200
Subject: [PATCH] [clangd] Allow --query-driver to match a dot-normalized form
 of the path

(In addition to the un-normalized form, so this is back-compatible)
---
 clang-tools-extra/clangd/SystemIncludeExtractor.cpp | 8 +++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp 
b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
index 88df5b04ccb09f3..3f93927434dbfa8 100644
--- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -343,7 +343,13 @@ extractSystemIncludesAndTarget(const DriverArgs &InputArgs,
   SPAN_ATTACH(Tracer, "driver", Driver);
   SPAN_ATTACH(Tracer, "lang", InputArgs.Lang);
 
-  if (!QueryDriverRegex.match(Driver)) {
+  // If driver was "../foo" then having to allowlist "/path/a/../foo" rather
+  // than "/path/foo" is absurd.
+  // Allow either to match the whitelist, then proceed with "/path/a/../foo".
+  // This was our historical behavior, and it *could* resolve to something 
else.
+  llvm::SmallString<256> NoDots(Driver);
+  llvm::sys::path::remove_dots(NoDots, /*remove_dot_dot=*/true);
+  if (!QueryDriverRegex.match(Driver) && !QueryDriverRegex.match(NoDots)) {
 vlog("System include extraction: not allowed driver {0}", Driver);
 return std::nullopt;
   }

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


[clang-tools-extra] [InstCombine] Simplify the pattern `a ne/eq (zext/sext (a ne/eq c))` (PR #65852)

2023-09-19 Thread Nikita Popov via cfe-commits


@@ -6309,7 +6309,69 @@ Instruction 
*InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst &I) {
   Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
 
+  ICmpInst::Predicate Pred1, Pred2;
   const APInt *C;
+  // icmp eq/ne X, (zext (icmp eq/ne X, C))
+  if (match(&I, m_c_ICmp(Pred1, m_Value(X),
+ m_ZExt(m_ICmp(Pred2, m_Deferred(X), m_APInt(C) &&
+  ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
+if (C->isZero()) {
+  if (Pred2 == ICmpInst::ICMP_EQ) {
+// icmp eq X, (zext (icmp eq X, 0)) --> false
+// icmp ne X, (zext (icmp eq X, 0)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp ne X, 0)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp ne X, 0)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else if (C->isOne()) {
+  if (Pred2 == ICmpInst::ICMP_NE) {
+// icmp eq X, (zext (icmp ne X, 1)) --> false
+// icmp ne X, (zext (icmp ne X, 1)) --> true
+return replaceInstUsesWith(
+I,
+Constant::getIntegerValue(
+I.getType(),
+APInt(1U, static_cast(Pred1 == ICmpInst::ICMP_NE;
+  } else {
+// icmp eq X, (zext (icmp eq X, 1)) --> icmp ult X, 2
+// icmp ne X, (zext (icmp eq X, 1)) --> icmp ugt X, 1
+return ICmpInst::Create(
+Instruction::ICmp,
+Pred1 == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGT
+   : ICmpInst::ICMP_ULT,
+X,
+Constant::getIntegerValue(
+X->getType(), APInt(X->getType()->getScalarSizeInBits(),
+Pred1 == ICmpInst::ICMP_NE ? 1 : 2)));
+  }
+} else {
+  // C != 0 && C != 1
+  // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
+  // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
+  // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
+  // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
+  return ICmpInst::Create(
+  Instruction::ICmp, Pred1, X,
+  Constant::getIntegerValue(
+  X->getType(),
+  APInt(X->getType()->getScalarSizeInBits(),
+static_cast(Pred2 == ICmpInst::ICMP_NE;
+}
+  }
+

nikic wrote:

My thought here was to do something along the lines of `a pred1 zext(a pred2 
c)` to `a pred2 c ? (a pred1 1) : (a pred1 0)` and then check whether `a pred2 
c` implies `a pred1 1`  is true/false or `a !pred2 c` implies `a pred1 0` is 
true/false. The remaining two comparisons will then get simplified based on 
and/or of icmps.

But I don't know whether this will handle all cases, and maybe the code will be 
more complex overall than listing all special cases.

https://github.com/llvm/llvm-project/pull/65852
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clangd] Allow --query-driver to match a dot-normalized form of the path (PR #66757)

2023-09-19 Thread Sam McCall via cfe-commits

sam-mccall wrote:

@kadircet this is internal b/294113850

https://github.com/llvm/llvm-project/pull/66757
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clangd] Allow --query-driver to match a dot-normalized form of the path (PR #66757)

2023-09-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd


Changes

(In addition to the un-normalized form, so this is back-compatible)


---
Full diff: https://github.com/llvm/llvm-project/pull/66757.diff


1 Files Affected:

- (modified) clang-tools-extra/clangd/SystemIncludeExtractor.cpp (+7-1) 


``diff
diff --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp 
b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
index 88df5b04ccb09f3..3f93927434dbfa8 100644
--- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -343,7 +343,13 @@ extractSystemIncludesAndTarget(const DriverArgs &InputArgs,
   SPAN_ATTACH(Tracer, "driver", Driver);
   SPAN_ATTACH(Tracer, "lang", InputArgs.Lang);
 
-  if (!QueryDriverRegex.match(Driver)) {
+  // If driver was "../foo" then having to allowlist "/path/a/../foo" rather
+  // than "/path/foo" is absurd.
+  // Allow either to match the whitelist, then proceed with "/path/a/../foo".
+  // This was our historical behavior, and it *could* resolve to something 
else.
+  llvm::SmallString<256> NoDots(Driver);
+  llvm::sys::path::remove_dots(NoDots, /*remove_dot_dot=*/true);
+  if (!QueryDriverRegex.match(Driver) && !QueryDriverRegex.match(NoDots)) {
 vlog("System include extraction: not allowed driver {0}", Driver);
 return std::nullopt;
   }

``




https://github.com/llvm/llvm-project/pull/66757
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clangd] Allow --query-driver to match a dot-normalized form of the path (PR #66757)

2023-09-19 Thread Sam McCall via cfe-commits

sam-mccall wrote:

I didn't add a test here because it seems fairly fiddly and fragile (would be a 
lit test) and unlikely to actually regress in practice. But I'm just making 
excuses, happy to add one if you think it's worthwhile.

https://github.com/llvm/llvm-project/pull/66757
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread Balint Cristian via cfe-commits

https://github.com/cbalint13 edited 
https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits


@@ -600,11 +601,17 @@ StringRef ARM::getARMCPUForArch(const llvm::Triple 
&Triple, StringRef MArch) {
   llvm_unreachable("invalid arch name");
 }
 
-void ARM::PrintSupportedExtensions() {
+void ARM::PrintSupportedExtensions(std::map llvmDescMap) 
{
   outs() << "All available -march extensions for ARM\n\n";
   for (const auto &Ext : ARCHExtNames) {
 // Extensions without a feature cannot be used with -march.
-if (!Ext.Feature.empty())
-  outs() << '\t' << Ext.Name << "\n";
+if (!Ext.Feature.empty()) {
+  if (llvmDescMap.empty()) {
+outs() << '\t' << Ext.Name << "\n";
+  } else {
+outs() << format("\t%-20s", Ext.Name.str().c_str());
+outs() << "\t\t" << llvmDescMap[Ext.Name] << "\n";

DavidSpickett wrote:

Sorry, I think I wasn't clear, I meant this could be one call:
```
outs() << format("\t%-20s", Ext.Name.str().c_str());
outs() << "\t\t" << llvmDescMap[Ext.Name] << "\n";
```
As in:
```
outs() << format("\t%-20s", Ext.Name.str().c_str())
  << "\t\t" << llvmDescMap[Ext.Name] << "\n";
```

I didn't mean that having an if/else was a bad idea.

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits


@@ -1016,7 +1017,8 @@ TEST(TargetParserTest, ARMPrintSupportedExtensions) {
 
   outs().flush();
   testing::internal::CaptureStdout();
-  ARM::PrintSupportedExtensions();
+  std::map EmptyMap;

DavidSpickett wrote:

Yeah that's fine. All it should check is that there's no path where a lookup 
(successful or not) causes an exception.

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread Balint Cristian via cfe-commits

https://github.com/cbalint13 edited 
https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clangd] Allow --query-driver to match a dot-normalized form of the path (PR #66757)

2023-09-19 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall updated 
https://github.com/llvm/llvm-project/pull/66757

>From 1923a5142f9cbd3556bba599b611ae8a1bbec776 Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Tue, 19 Sep 2023 12:16:54 +0200
Subject: [PATCH 1/2] [clangd] Allow --query-driver to match a dot-normalized
 form of the path

(In addition to the un-normalized form, so this is back-compatible)
---
 clang-tools-extra/clangd/SystemIncludeExtractor.cpp | 8 +++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp 
b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
index 88df5b04ccb09f3..3f93927434dbfa8 100644
--- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -343,7 +343,13 @@ extractSystemIncludesAndTarget(const DriverArgs &InputArgs,
   SPAN_ATTACH(Tracer, "driver", Driver);
   SPAN_ATTACH(Tracer, "lang", InputArgs.Lang);
 
-  if (!QueryDriverRegex.match(Driver)) {
+  // If driver was "../foo" then having to allowlist "/path/a/../foo" rather
+  // than "/path/foo" is absurd.
+  // Allow either to match the whitelist, then proceed with "/path/a/../foo".
+  // This was our historical behavior, and it *could* resolve to something 
else.
+  llvm::SmallString<256> NoDots(Driver);
+  llvm::sys::path::remove_dots(NoDots, /*remove_dot_dot=*/true);
+  if (!QueryDriverRegex.match(Driver) && !QueryDriverRegex.match(NoDots)) {
 vlog("System include extraction: not allowed driver {0}", Driver);
 return std::nullopt;
   }

>From de641152074d95aa8f83843543d6c486a98da908 Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Tue, 19 Sep 2023 12:24:36 +0200
Subject: [PATCH 2/2] use allowlisted words

---
 clang-tools-extra/clangd/SystemIncludeExtractor.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp 
b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
index 3f93927434dbfa8..74bae786425c829 100644
--- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -345,7 +345,7 @@ extractSystemIncludesAndTarget(const DriverArgs &InputArgs,
 
   // If driver was "../foo" then having to allowlist "/path/a/../foo" rather
   // than "/path/foo" is absurd.
-  // Allow either to match the whitelist, then proceed with "/path/a/../foo".
+  // Allow either to match the allowlist, then proceed with "/path/a/../foo".
   // This was our historical behavior, and it *could* resolve to something 
else.
   llvm::SmallString<256> NoDots(Driver);
   llvm::sys::path::remove_dots(NoDots, /*remove_dot_dot=*/true);

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


[clang] [clang] Enable descriptions for --print-supported-extensions (PR #66715)

2023-09-19 Thread David Spickett via cfe-commits


@@ -210,24 +210,33 @@ static void verifyTables() {
 #endif
 }
 
-void llvm::riscvExtensionsHelp() {
+void llvm::riscvExtensionsHelp(std::map llvmDescMap) {
+
   outs() << "All available -march extensions for RISC-V\n\n";
-  outs() << '\t' << left_justify("Name", 20) << "Version\n";
+  outs() << '\t' << left_justify("Name", 20) << "Version";
+  outs() << (llvmDescMap.empty() ? "\n" : "\tDescription\n");
 
   RISCVISAInfo::OrderedExtensionMap ExtMap;
   for (const auto &E : SupportedExtensions)
 ExtMap[E.Name] = {E.Version.Major, E.Version.Minor};
-  for (const auto &E : ExtMap)
-outs() << format("\t%-20s%d.%d\n", E.first.c_str(), E.second.MajorVersion,
+  for (const auto &E : ExtMap) {
+outs() << format("\t%-20s%d.%d", E.first.c_str(), E.second.MajorVersion,
  E.second.MinorVersion);
+outs() << (llvmDescMap.empty() ? "\n"

DavidSpickett wrote:

> Basically with this feature we have an option to skip "Description" column at 
> all.

I see what you mean now. Yes I agree, if there's some architecture that 
provides 0 descriptions then having it doesn't make any sense.

https://github.com/llvm/llvm-project/pull/66715
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [LLVM] Add new attribute `optdebug` to optimize for debugging (PR #66632)

2023-09-19 Thread Stephen Tozer via cfe-commits


@@ -2325,6 +2325,7 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
   B.addAttribute(llvm::Attribute::Naked);
 
 // OptimizeNone wins over OptimizeForSize and MinSize.
+F->removeFnAttr(llvm::Attribute::OptimizeForDebugging);

SLTozer wrote:

Topic posted: 
https://discourse.llvm.org/t/rfc-new-function-attribute-optdebug-for-prioritizing-debuggability-in-llvm-passes/73552

https://github.com/llvm/llvm-project/pull/66632
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][TSA] Consider cleanup functions for thread safety analysis (PR #65462)

2023-09-19 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?B=C3=A4der?= 
Message-ID:
In-Reply-To: 


tbaederr wrote:

Review continued on Phabricator.

https://github.com/llvm/llvm-project/pull/65462
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][TSA] Consider cleanup functions for thread safety analysis (PR #65462)

2023-09-19 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 


https://github.com/tbaederr closed 
https://github.com/llvm/llvm-project/pull/65462
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [X86] Align 128/256 variants to use void * as 512 variants. (PR #66310)

2023-09-19 Thread Simon Pilgrim via cfe-commits

https://github.com/RKSimon approved this pull request.

LGTM - please update the description to mention that you're updating the movnti 
i32/i64 scalar integer nt ops as well as the vector ops

https://github.com/llvm/llvm-project/pull/66310
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D141192: [Clang] Fix warnings on bad shifts.

2023-09-19 Thread Budimir Aranđelović via Phabricator via cfe-commits
budimirarandjelovicsyrmia added a comment.

Ping.


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

https://reviews.llvm.org/D141192

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


[clang] [dataflow] Parse formulas from text (PR #66424)

2023-09-19 Thread via cfe-commits

https://github.com/martinboehme resolved 
https://github.com/llvm/llvm-project/pull/66424
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Add std::variant checker (PR #66481)

2023-09-19 Thread Gábor Spaits via cfe-commits


@@ -0,0 +1,312 @@
+//===- StdVariantChecker.cpp -*- 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
+//
+//===--===//
+
+#include "clang/AST/Type.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "llvm/ADT/FoldingSet.h"
+
+#include "TaggedUnionModeling.h"
+
+using namespace clang;
+using namespace ento;
+using namespace variant_modeling;
+
+REGISTER_MAP_WITH_PROGRAMSTATE(VariantHeldTypeMap, const MemRegion *, QualType)
+
+namespace clang {
+namespace ento {
+namespace variant_modeling {
+
+// Returns the CallEvent representing the caller of the function
+// It is needed because the CallEvent class does not contain enough information
+// to tell who called it. Checker context is needed.
+CallEventRef<> getCaller(const CallEvent &Call, const ProgramStateRef &State) {
+  const auto *CallLocationContext = Call.getLocationContext();
+  if (!CallLocationContext) {
+return nullptr;
+  }
+
+  if (CallLocationContext->inTopFrame()) {
+return nullptr;
+  }
+  const auto *CallStackFrameContext = CallLocationContext->getStackFrame();
+  if (!CallStackFrameContext) {
+return nullptr;
+  }
+
+  CallEventManager &CEMgr = State->getStateManager().getCallEventManager();
+  return CEMgr.getCaller(CallStackFrameContext, State);
+}
+
+const CXXConstructorDecl *
+getConstructorDeclarationForCall(const CallEvent &Call) {
+  const auto *ConstructorCall = dyn_cast(&Call);
+  if (!ConstructorCall) {
+return nullptr;
+  }
+  return ConstructorCall->getDecl();
+}
+
+bool isCopyConstructorCall(const CallEvent &Call) {
+  const CXXConstructorDecl *ConstructorDecl =
+  getConstructorDeclarationForCall(Call);
+  if (!ConstructorDecl) {
+return false;
+  }
+  return ConstructorDecl->isCopyConstructor();
+}
+
+bool isCopyAssignmentCall(const CallEvent &Call) {
+  const Decl *CopyAssignmentDecl = Call.getDecl();
+  if (!CopyAssignmentDecl) {
+return false;
+  }
+  const auto *AsMethodDecl = dyn_cast(CopyAssignmentDecl);
+  if (!AsMethodDecl) {
+return false;
+  }
+  return AsMethodDecl->isCopyAssignmentOperator();
+}
+
+bool isMoveConstructorCall(const CallEvent &Call) {
+  const CXXConstructorDecl *ConstructorDecl =
+  getConstructorDeclarationForCall(Call);
+  if (!ConstructorDecl) {
+return false;
+  }
+  return ConstructorDecl->isMoveConstructor();
+}
+
+bool isMoveAssignmentCall(const CallEvent &Call) {
+  const Decl *CopyAssignmentDecl = Call.getDecl();
+  if (!CopyAssignmentDecl) {
+return false;
+  }
+  const auto *AsMethodDecl = dyn_cast(CopyAssignmentDecl);
+  if (!AsMethodDecl) {
+return false;
+  }
+  return AsMethodDecl->isMoveAssignmentOperator();
+}
+
+const TemplateArgument &getFirstTemplateArgument(const CallEvent &Call) {
+  const CallExpr *CE = cast(Call.getOriginExpr());
+  const FunctionDecl *FD = CE->getDirectCallee();
+  assert(1 <= FD->getTemplateSpecializationArgs()->asArray().size() &&
+ "std::get should have at least 1 template argument!");
+  return FD->getTemplateSpecializationArgs()->asArray()[0];
+}
+
+bool isStdType(const Type *Type, const std::string &TypeName) {
+  auto *Decl = Type->getAsRecordDecl();
+  if (!Decl) {
+return false;
+  }
+
+  return (Decl->getNameAsString() == TypeName) && Decl->isInStdNamespace();
+}
+
+bool isStdVariant(const Type *Type) {
+  return isStdType(Type, std::string("variant"));
+}
+
+bool calledFromSystemHeader(const CallEvent &Call,
+const ProgramStateRef &State) {
+  auto Caller = getCaller(Call, State);
+  if (Caller) {
+return Caller->isInSystemHeader();
+  }
+  return false;
+}
+
+bool calledFromSystemHeader(const CallEvent &Call, CheckerContext &C) {
+  return calledFromSystemHeader(Call, C.getState());
+}
+
+} // end of namespace variant_modeling
+} // end of namespace ento
+} // end of namespace clang
+
+static ArrayRef
+getTemplateArgsFromVariant(const Type *VariantType) {
+  const auto *TempSpecType = VariantType->getAs();
+  assert(TempSpecType &&
+ "We are in a variant instance. It must be a template 
specialization!");
+  return TempSpecType->template_arguments();
+}
+
+static QualType getNthTemplateTypeArgFromVariant(const Type *varType,
+ unsigned i) {
+  return getTemplateArgsFromVariant(varType)[i].getAsType();
+}
+
+class StdVaria

[clang] [analyzer] Remove inaccurate legacy handling of bad bitwise shifts (PR #66647)

2023-09-19 Thread via cfe-commits

DonatNagyE wrote:

The impact is limited, because `core.BitwiseShift` is a `PreStmt` callback, so 
when I merged it, it turned the logic tweaked/affected in this commit into 
"almost dead" code.

The most significant change is that some "pedantic-only" issues (i.e. code like 
`-1 >> 3` that's undefined behavior according to the standard, but works in 
practice) are no longer reported after this commit. (Note that I ran the 
evaluation with the default mode `core.BitwiseShift:Pedantic=false`, it's clear 
that pedantic mode would've reported these situations.) The change also 
elminates a few FPs, and sometimes new alpha.core.Conversion results appeared 
on branches that were previously stopped by a core.UndefinedBinaryOperator 
report.

Full results:

| Project | New reports | Lost reports | Difference |
| --- | --- | --- | --- |
| memcached | [New 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=memcached_1.6.8_baseline&newcheck=memcached_1.6.8_remove_ubor_shifts&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=memcached_1.6.8_baseline&newcheck=memcached_1.6.8_remove_ubor_shifts&is-unique=on&diff-mode=Resolved)
 | no effect |
| tmux | [New 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=tmux_2.6_baseline&newcheck=tmux_2.6_remove_ubor_shifts&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=tmux_2.6_baseline&newcheck=tmux_2.6_remove_ubor_shifts&is-unique=on&diff-mode=Resolved)
 | no effect |
| curl | [New 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=curl_curl-7_66_0_baseline&newcheck=curl_curl-7_66_0_remove_ubor_shifts&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=curl_curl-7_66_0_baseline&newcheck=curl_curl-7_66_0_remove_ubor_shifts&is-unique=on&diff-mode=Resolved)
 | no effect |
| twin | [New 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=twin_v0.8.1_baseline&newcheck=twin_v0.8.1_remove_ubor_shifts&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=twin_v0.8.1_baseline&newcheck=twin_v0.8.1_remove_ubor_shifts&is-unique=on&diff-mode=Resolved)
 | no effect |
| vim | [New 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=vim_v8.2.1920_baseline&newcheck=vim_v8.2.1920_remove_ubor_shifts&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=vim_v8.2.1920_baseline&newcheck=vim_v8.2.1920_remove_ubor_shifts&is-unique=on&diff-mode=Resolved)
 | one cryptic FP eliminated |
| openssl | [New 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=openssl_openssl-3.0.0-alpha7_baseline&newcheck=openssl_openssl-3.0.0-alpha7_remove_ubor_shifts&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=openssl_openssl-3.0.0-alpha7_baseline&newcheck=openssl_openssl-3.0.0-alpha7_remove_ubor_shifts&is-unique=on&diff-mode=Resolved)
 | one pedantic-only issue lost |
| sqlite | [New 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=sqlite_version-3.33.0_baseline&newcheck=sqlite_version-3.33.0_remove_ubor_shifts&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=sqlite_version-3.33.0_baseline&newcheck=sqlite_version-3.33.0_remove_ubor_shifts&is-unique=on&diff-mode=Resolved)
 | no effect |
| ffmpeg | [New 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=ffmpeg_n4.3.1_baseline&newcheck=ffmpeg_n4.3.1_remove_ubor_shifts&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=ffmpeg_n4.3.1_baseline&newcheck=ffmpeg_n4.3.1_remove_ubor_shifts&is-unique=on&diff-mode=Resolved)
 | 2 new, 7 lost [1] |
| postgres | [New 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=postgres_REL_13_0_baseline&newcheck=postgres_REL_13_0_remove_ubor_shifts&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=postgres_REL_13_0_baseline&newcheck=postgres_REL_13_0_remove_ubor_shifts&is-unique=on&diff-mode=Resolved)
 | 1 new, 2 lost [2] |
| tinyxml2 | [New 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=tinyxml2_8.0.0_baseline&newcheck=tinyxml2_8.0.0_remove_ubor_shifts&is-unique=on&diff-mode=New)
 | [Lost 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=tinyxml2_8.0.0_baseline&newcheck=tinyxml2_8.0.0_remove_ubor_shifts&is-unique=on&diff-mode=Resolved)
 | no effect |
| libwebm | [New 
reports](https://codechecker.gic.ericsson.se/clangsa_checkers/reports?run=libwebm_libwebm-1.0.0.27_baseline&newcheck=libwebm_libwebm-1.0.0.27_remove_ubor_shifts&is-unique=on&d

[clang] [X86] Align 128/256 variants to use void * as 512 variants. (PR #66310)

2023-09-19 Thread Shengchen Kan via cfe-commits

https://github.com/KanRobert approved this pull request.

LGTM

https://github.com/llvm/llvm-project/pull/66310
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][dataflow] Reorder checks to protect against a null pointer dereference. (PR #66764)

2023-09-19 Thread via cfe-commits

https://github.com/martinboehme created 
https://github.com/llvm/llvm-project/pull/66764

I've received a report of a null pointer dereference happening on the
`LocDst->getType()` dereference. I wasn't unfortunately able to find a repro,
but I'd argue the new version is better for the reduced indentation alone.


>From 22a3df68bc5ba1b7e349d3e9d003bbc2c25e9b85 Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Tue, 19 Sep 2023 12:05:01 +
Subject: [PATCH] [clang][dataflow] Reorder checks to protect against a null
 pointer dereference.

I've received a report of a null pointer dereference happening on the
`LocDst->getType()` dereference. I wasn't unfortunately able to find a repro,
but I'd argue the new version is better for the reduced indentation alone.
---
 clang/lib/Analysis/FlowSensitive/Transfer.cpp | 13 +++--
 1 file changed, 7 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index b510114a7a355eb..2414a1cc026af5f 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -531,17 +531,18 @@ class TransferVisitor : public 
ConstStmtVisitor {
   auto *LocDst =
   cast_or_null(Env.getStorageLocation(*Arg0));
 
+  if (LocSrc == nullptr || LocDst == nullptr)
+return;
+
   // The assignment operators are different from the type of the 
destination
-  // in this model (i.e. in one of their base classes). This must be very 
rare
-  // and we just bail.
+  // in this model (i.e. in one of their base classes). This must be very
+  // rare and we just bail.
   if (Method->getThisObjectType().getCanonicalType().getUnqualifiedType() 
!=
   LocDst->getType().getCanonicalType().getUnqualifiedType())
 return;
 
-  if (LocSrc != nullptr && LocDst != nullptr) {
-copyRecord(*LocSrc, *LocDst, Env);
-Env.setStorageLocation(*S, *LocDst);
-  }
+  copyRecord(*LocSrc, *LocDst, Env);
+  Env.setStorageLocation(*S, *LocDst);
 }
   }
 

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


[clang] [clang][dataflow] Reorder checks to protect against a null pointer dereference. (PR #66764)

2023-09-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

I've received a report of a null pointer dereference happening on the
`LocDst->getType()` dereference. I wasn't unfortunately able to find a repro,
but I'd argue the new version is better for the reduced indentation alone.


---
Full diff: https://github.com/llvm/llvm-project/pull/66764.diff


1 Files Affected:

- (modified) clang/lib/Analysis/FlowSensitive/Transfer.cpp (+7-6) 


``diff
diff --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index b510114a7a355eb..2414a1cc026af5f 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -531,17 +531,18 @@ class TransferVisitor : public 
ConstStmtVisitor {
   auto *LocDst =
   cast_or_null(Env.getStorageLocation(*Arg0));
 
+  if (LocSrc == nullptr || LocDst == nullptr)
+return;
+
   // The assignment operators are different from the type of the 
destination
-  // in this model (i.e. in one of their base classes). This must be very 
rare
-  // and we just bail.
+  // in this model (i.e. in one of their base classes). This must be very
+  // rare and we just bail.
   if (Method->getThisObjectType().getCanonicalType().getUnqualifiedType() 
!=
   LocDst->getType().getCanonicalType().getUnqualifiedType())
 return;
 
-  if (LocSrc != nullptr && LocDst != nullptr) {
-copyRecord(*LocSrc, *LocDst, Env);
-Env.setStorageLocation(*S, *LocDst);
-  }
+  copyRecord(*LocSrc, *LocDst, Env);
+  Env.setStorageLocation(*S, *LocDst);
 }
   }
 

``




https://github.com/llvm/llvm-project/pull/66764
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clangd] Allow --query-driver to match a dot-normalized form of the path (PR #66757)

2023-09-19 Thread kadir çetinkaya via cfe-commits

kadircet wrote:

thanks, no need for tests, the logic is rather trivial (might be worth 
mentioning in change notes though, so that we can build them up more naturally 
for the future and encourage others to do so as well)

https://github.com/llvm/llvm-project/pull/66757
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   3   4   5   >