[clang] [analyzer][NFC] Introduce APSIntPtr, a safe wrapper of APSInt (1/4) (PR #120435)

2024-12-19 Thread Arseniy Zaostrovnykh via cfe-commits


@@ -0,0 +1,64 @@
+//== APSIntPtr.h - Wrapper for APSInt objects owned separately -*- 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
+//
+//===--===//
+
+#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_APSIntPtr_H
+#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_APSIntPtr_H
+
+#include "llvm/ADT/APSInt.h"
+
+namespace clang::ento {
+class BasicValueFactory;
+
+/// A safe wrapper around APSInt objects allocated and owned by
+/// \c BasicValueFactory. This just wraps a common llvm::APSInt.
+class APSIntPtr {
+  using APSInt = llvm::APSInt;
+
+public:
+  APSIntPtr() = delete;
+  APSIntPtr(const APSIntPtr &) = default;
+  APSIntPtr &operator=(const APSIntPtr &) & = default;
+  ~APSIntPtr() = default;
+
+  /// You should not use this API.
+  /// If do, ensure that the \p Ptr not going to dangle.
+  /// Prefer using \c BasicValueFactory::getValue() to get an APSIntPtr object.
+  static APSIntPtr unsafeConstructor(const APSInt *Ptr) {
+return APSIntPtr(Ptr);
+  }
+
+  const APSInt *get() const { return Ptr; }
+  /*implicit*/ operator const APSInt &() const { return *get(); }
+
+  APSInt operator-() const { return -*Ptr; }
+  APSInt operator~() const { return ~*Ptr; }
+
+#define DEFINE_OPERATOR(OP)
\
+  bool operator OP(APSIntPtr Other) const { return (*Ptr)OP(*Other.Ptr); }
+  DEFINE_OPERATOR(>)
+  DEFINE_OPERATOR(>=)
+  DEFINE_OPERATOR(<)
+  DEFINE_OPERATOR(<=)
+  DEFINE_OPERATOR(==)
+  DEFINE_OPERATOR(!=)
+#undef DEFINE_OPERATOR
+
+  const APSInt &operator*() const { return *Ptr; }
+  const APSInt *operator->() const { return Ptr; }
+
+private:
+  friend class BasicValueFactory;

necto wrote:

Given that you have `unsafeConstructor`, is it worth having a blanked 
friendship coupling?
Additionaly, using `unsafeConstructor` could help `BasicValueFactory` itself to 
explicify when the persistent values are created and find sneaky timebombs, 
like the `BasicValueFactory::Convert` member function

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


[clang] [analyzer][NFC] Introduce APSIntPtr, a safe wrapper of APSInt (1/4) (PR #120435)

2024-12-19 Thread Arseniy Zaostrovnykh via cfe-commits


@@ -165,79 +166,70 @@ class BasicValueFactory {
 
   /// Convert - Create a new persistent APSInt with the same value as 'From'
   ///  but with the bitwidth and signedness of 'To'.
-  const llvm::APSInt &Convert(const llvm::APSInt& To,
-  const llvm::APSInt& From) {
+  APSIntPtr Convert(const llvm::APSInt &To, const llvm::APSInt &From) {
 APSIntType TargetType(To);
 if (TargetType == APSIntType(From))
-  return From;
+  return APSIntPtr(&From);

necto wrote:

This might create a tricky bug, given that despite the doc comment and the type 
signature, this function does not create a persistent APSInt *only in this 
case*, if `From` was not persistent on the call.
I suggest requiring the `From` argument to be `APSIntPtr` to make this function 
safer.

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


[clang] [analyzer][NFC] Introduce APSIntPtr, a safe wrapper of APSInt (1/4) (PR #120435)

2024-12-19 Thread Arseniy Zaostrovnykh via cfe-commits

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


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


[clang] [WebKit checkers] Recognize adoptRef as a safe function (PR #119846)

2024-12-19 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated 
https://github.com/llvm/llvm-project/pull/119846

>From 6b4a6b832f61efc26396f60309744c2e7264156d Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Fri, 13 Dec 2024 01:49:21 -0800
Subject: [PATCH 1/4] [WebKit checkers] Recognize adoptRef as a safe function

adoptRef in WebKit constructs Ref/RefPtr so treat it as such in 
isCtorOfRefCounted.
Also removed the support for makeRef and makeRefPtr as they don't exist any 
more.
---
 .../Checkers/WebKit/PtrTypesSemantics.cpp |  5 ++--
 .../Analysis/Checkers/WebKit/call-args.cpp| 17 +++
 .../Analysis/Checkers/WebKit/mock-types.h | 28 ++-
 3 files changed, 46 insertions(+), 4 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index 797f3e1f3fba5a..5487fea1b956c8 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -125,9 +125,8 @@ bool isCtorOfRefCounted(const clang::FunctionDecl *F) {
   assert(F);
   const std::string &FunctionName = safeGetName(F);
 
-  return isRefType(FunctionName) || FunctionName == "makeRef" ||
- FunctionName == "makeRefPtr" || FunctionName == "UniqueRef" ||
- FunctionName == "makeUniqueRef" ||
+  return isRefType(FunctionName) || FunctionName == "adoptRef" ||
+ FunctionName == "UniqueRef" || FunctionName == "makeUniqueRef" ||
  FunctionName == "makeUniqueRefWithoutFastMallocCheck"
 
  || FunctionName == "String" || FunctionName == "AtomString" ||
diff --git a/clang/test/Analysis/Checkers/WebKit/call-args.cpp 
b/clang/test/Analysis/Checkers/WebKit/call-args.cpp
index 94efddeaf66cd8..574e3aa6ef476a 100644
--- a/clang/test/Analysis/Checkers/WebKit/call-args.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/call-args.cpp
@@ -365,3 +365,20 @@ namespace call_with_explicit_temporary_obj {
 RefPtr { provide() }->method();
   }
 }
+
+namespace call_with_adopt_ref {
+  class Obj {
+  public:
+void ref() const;
+void deref() const;
+void method();
+  };
+
+  struct dummy {
+RefPtr any;
+  };
+
+  void foo() {
+adoptRef(new Obj)->method();
+  }
+}
diff --git a/clang/test/Analysis/Checkers/WebKit/mock-types.h 
b/clang/test/Analysis/Checkers/WebKit/mock-types.h
index fb1ee51c7ec1de..17c449b6c2ec26 100644
--- a/clang/test/Analysis/Checkers/WebKit/mock-types.h
+++ b/clang/test/Analysis/Checkers/WebKit/mock-types.h
@@ -46,7 +46,10 @@ template struct DefaultRefDerefTraits {
 template , typename 
RefDerefTraits = DefaultRefDerefTraits> struct Ref {
   typename PtrTraits::StorageType t;
 
+  enum AdoptTag { Adopt };
+
   Ref() : t{} {};
+  Ref(T &t, AdoptTag) : t(&t) { }
   Ref(T &t) : t(&RefDerefTraits::ref(t)) { }
   Ref(const Ref& o) : t(RefDerefTraits::refIfNotNull(PtrTraits::unwrap(o.t))) 
{ }
   Ref(Ref&& o) : t(o.leakRef()) { }
@@ -73,10 +76,19 @@ template , 
typename RefDerefTra
   T* leakRef() { return PtrTraits::exchange(t, nullptr); }
 };
 
+template  Ref adoptRef(T& t) {
+  using Ref = Ref;
+  return Ref(t, Ref::Adopt);
+}
+
+template class RefPtr;
+template RefPtr adoptRef(T*);
+
 template  struct RefPtr {
   T *t;
 
-  RefPtr() : t(new T) {}
+  RefPtr() : t(nullptr) { }
+
   RefPtr(T *t)
 : t(t) {
 if (t)
@@ -85,6 +97,9 @@ template  struct RefPtr {
   RefPtr(Ref&& o)
 : t(o.leakRef())
   { }
+  RefPtr(RefPtr&& o)
+: t(o.leakRef())
+  { }
   ~RefPtr() {
 if (t)
   t->deref();
@@ -110,8 +125,19 @@ template  struct RefPtr {
 return *this;
   }
   operator bool() const { return t; }
+
+private:
+  friend RefPtr adoptRef(T*);
+
+  // call_with_adopt_ref in call-args.cpp requires this method to be private.
+  enum AdoptTag { Adopt };
+  RefPtr(T *t, AdoptTag) : t(t) { }
 };
 
+template  RefPtr adoptRef(T* t) {
+  return RefPtr(t, RefPtr::Adopt);
+}
+
 template  bool operator==(const RefPtr &, const RefPtr &) {
   return false;
 }

>From 0cdeb5676251a3c8d832baf1de800fe8a535b600 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Fri, 13 Dec 2024 01:58:00 -0800
Subject: [PATCH 2/4] Fix the mock RefPtr

---
 clang/test/Analysis/Checkers/WebKit/mock-types.h | 8 +---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/clang/test/Analysis/Checkers/WebKit/mock-types.h 
b/clang/test/Analysis/Checkers/WebKit/mock-types.h
index 17c449b6c2ec26..9625ae6128883c 100644
--- a/clang/test/Analysis/Checkers/WebKit/mock-types.h
+++ b/clang/test/Analysis/Checkers/WebKit/mock-types.h
@@ -95,11 +95,13 @@ template  struct RefPtr {
   t->ref();
   }
   RefPtr(Ref&& o)
-: t(o.leakRef())
+: t(o.leafkRef())
   { }
   RefPtr(RefPtr&& o)
-: t(o.leakRef())
-  { }
+: t(o.t)
+  {
+o.t = nullptr;
+  }
   ~RefPtr() {
 if (t)
   t->deref();

>From bc318db7b2a4c48882988d1ca26ab54cb351757a Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Wed, 18 Dec 2024 10:31:41 -0800
Subject: [PATCH 3/4]

[clang] Patch series to reapply #119638 and substantially improve it (PR #120534)

2024-12-19 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-sparc

@llvm/pr-subscribers-backend-arm

Author: Chandler Carruth (chandlerc)


Changes

This PR is for a patch series of 5 patches to try and fully address the Clang 
builtin string tables. I'm posting it as a single PR to give context to the 
series and explain what the overarching goal is, but each of the 5 patches is 
designed to be reasonable to review on its own and land on its own. The only 
issue I expect is that MSVC 16.9 on one build bot is likely to miscompile the 
intermediate steps, and MSVC will consume a large amount of memory during 
compilation until all the patches are in place.

That said, I'm happy to have each patch reviewed here, or I can post 
independent PRs for each patch, whichever would work best for reviewers.

The overarching goal of this patch series is to re-land the port of Clang's 
builtin tables to use offsets into string tables rather than containing 
dynamically relocated pointers to individual strings. A naive port as in #119638 has some serious issues due to forming *extraordinarily* large string 
tables, and many of them. To address this, subsequent patches restructure the 
builtin tables to make them smaller through sharding, use of TableGen-ed string 
tables without duplicates, and extracting a common prefix that can be 
dynamically added. The first patch results in a string table over 500KiB, but 
at the end the largest is well below 200KiB.

Combined, this patch series reduces the readonly data used by Clang's builtins 
by roughly 50% in addition to removing the dynamic relocations needed. The net 
result is a 30% reduction in the binary's dynamic relocation metadata, and a 2% 
reduction in the total binary size.

```
FILE SIZEVM SIZE
 --  --
  +1.6%  +763Ki  +1.6%  +763Ki.rodata
  +0.0% +5.61Ki  +0.0% +5.61Ki.text
  +0.0%+344  +0.0%+344.dynstr
  +0.0%+264  +0.0%+264.eh_frame
  +0.0%+192  +0.0%+192.dynsym
  +0.0% +56  +0.0% +56.eh_frame_hdr
  +0.0% +40  +0.0% +40.gnu.hash
  +3.1% +24  +3.1% +24[LOAD #2 [R]]
  +0.0% +16  +0.0% +16.gnu.version
  +200% +16  [ = ]   0[Unmapped]
  [ = ]   0 -91.9% -1.78Ki.relro_padding
 -29.4% -1.35Mi -29.4% -1.35Mi.data.rel.ro
 -30.0% -2.53Mi -30.0% -2.53Mi.rela.dyn
  -1.9% -3.13Mi  -1.9% -3.13MiTOTAL
```

An overview of the various patches in the series:

1) Reapplies #119638 but using the new ADT for representing the string 
tables and offsets.
2) Restructures builtin tables to support sharding both the main and target 
builtins into multiple shards. This both allows each shard to be smaller, and 
also allows independent construction of each shard.
3) Leverages the sharded structure to switch RISCV (a target with larger 
tables) to directly generate some of its builtins data with TableGen rather 
than using X-macros. This lets TableGen generate the string table, eliminitaing 
redundant strings and reducing macro-based compile time memory overhead.
4) Repeats the restructuring of (3) for AArch64 and ARM, which includes the 
largest builtin table (SVE).
5) Switch Neon, SVE, SME, and RVV builtins to extract a prefix of their names 
from the strings in the tables, and add it back when needed dynamically.

Each patch has a somewhat more detailed description in its commit message.

The struture at the end opens up a lot of room to make more improvements, 
especially leveraging TableGen more heavily by having the ability to fall back 
to X-macro structures where necessary. I have a partial patch to move the main 
builtins to TableGen as well, but that will be more involved and unlikely to 
have as significant of impact on string literal size or binary size.

---

Patch is 115.77 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/120534.diff


62 Files Affected:

- (modified) clang/include/clang/Basic/Builtins.h (+187-35) 
- (removed) clang/include/clang/Basic/BuiltinsNEON.def (-22) 
- (modified) clang/include/clang/Basic/BuiltinsPPC.def (+1) 
- (removed) clang/include/clang/Basic/BuiltinsRISCVVector.def (-22) 
- (modified) clang/include/clang/Basic/TargetBuiltins.h (+24-10) 
- (modified) clang/include/clang/Basic/TargetInfo.h (+6-4) 
- (modified) clang/lib/AST/ByteCode/InterpBuiltin.cpp (+2-2) 
- (modified) clang/lib/AST/ExprConstant.cpp (+7-8) 
- (modified) clang/lib/Basic/Builtins.cpp (+131-49) 
- (modified) clang/lib/Basic/Targets/AArch64.cpp (+109-31) 
- (modified) clang/lib/Basic/Targets/AArch64.h (+1-1) 
- (modified) clang/lib/Basic/Targets/AMDGPU.cpp (+17-9) 
- (modified) clang/lib/Basic/Targets/AMDGPU.h (+1-1) 
- (modified) clang/lib/Basic/Targets/ARC.h (+3-1) 
- (modified) clang/lib/Basic/Targets/ARM.cpp (+58-23) 
- (modified) clang/lib/Basic/Targets/ARM.h (+1-1) 
- (modified) clang/lib/Basic/Targets/AVR.h (+3-1) 
- (modified) clang/lib/Basic/Targets/BPF.cpp (+15-7) 
- (modified) clang/

[clang] Patch series to reapply #119638 and substantially improve it (PR #120534)

2024-12-19 Thread Chandler Carruth via cfe-commits

chandlerc wrote:

@dyung - I believe this PR may be a credible path to address the issues hit 
with your MSVC builders, would appreciate any help testing it in advance if 
possible.

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


[clang] Add configuration option PenaltyBreakBeforeMemberAccess (PR #118409)

2024-12-19 Thread Owen Pan via cfe-commits

https://github.com/owenca commented:

Please rebase and run `ninja clang-format-style`.

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


[clang] [clang-format] Add BreakBeforeTemplateClose option (PR #118046)

2024-12-19 Thread Björn Schäpers via cfe-commits


@@ -11077,6 +11077,221 @@ TEST_F(FormatTest, 
WrapsTemplateDeclarationsWithComments) {
   Style);
 }
 
+TEST_F(FormatTest, BreakBeforeTemplateClose) {

HazardyKnusperkeks wrote:

One additional test: How about nested templates?
`template typename T>` for example.

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


[clang] Patch series to reapply #119638 and substantially improve it (PR #120534)

2024-12-19 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff 5c5a769cc0ccc6634a09273289e6d79da109c842 
fd353de6d0cbb57a919eb44b6fbcb0784fa61ae4 --extensions h,cpp -- 
clang/include/clang/Basic/Builtins.h clang/include/clang/Basic/TargetBuiltins.h 
clang/include/clang/Basic/TargetInfo.h clang/lib/AST/ByteCode/InterpBuiltin.cpp 
clang/lib/AST/ExprConstant.cpp clang/lib/Basic/Builtins.cpp 
clang/lib/Basic/Targets/AArch64.cpp clang/lib/Basic/Targets/AArch64.h 
clang/lib/Basic/Targets/AMDGPU.cpp clang/lib/Basic/Targets/AMDGPU.h 
clang/lib/Basic/Targets/ARC.h clang/lib/Basic/Targets/ARM.cpp 
clang/lib/Basic/Targets/ARM.h clang/lib/Basic/Targets/AVR.h 
clang/lib/Basic/Targets/BPF.cpp clang/lib/Basic/Targets/BPF.h 
clang/lib/Basic/Targets/CSKY.cpp clang/lib/Basic/Targets/CSKY.h 
clang/lib/Basic/Targets/DirectX.h clang/lib/Basic/Targets/Hexagon.cpp 
clang/lib/Basic/Targets/Hexagon.h clang/lib/Basic/Targets/Lanai.h 
clang/lib/Basic/Targets/LoongArch.cpp clang/lib/Basic/Targets/LoongArch.h 
clang/lib/Basic/Targets/M68k.cpp clang/lib/Basic/Targets/M68k.h 
clang/lib/Basic/Targets/MSP430.h clang/lib/Basic/Targets/Mips.cpp 
clang/lib/Basic/Targets/Mips.h clang/lib/Basic/Targets/NVPTX.cpp 
clang/lib/Basic/Targets/NVPTX.h clang/lib/Basic/Targets/PNaCl.h 
clang/lib/Basic/Targets/PPC.cpp clang/lib/Basic/Targets/PPC.h 
clang/lib/Basic/Targets/RISCV.cpp clang/lib/Basic/Targets/RISCV.h 
clang/lib/Basic/Targets/SPIR.cpp clang/lib/Basic/Targets/SPIR.h 
clang/lib/Basic/Targets/Sparc.h clang/lib/Basic/Targets/SystemZ.cpp 
clang/lib/Basic/Targets/SystemZ.h clang/lib/Basic/Targets/TCE.h 
clang/lib/Basic/Targets/VE.cpp clang/lib/Basic/Targets/VE.h 
clang/lib/Basic/Targets/WebAssembly.cpp clang/lib/Basic/Targets/WebAssembly.h 
clang/lib/Basic/Targets/X86.cpp clang/lib/Basic/Targets/X86.h 
clang/lib/Basic/Targets/XCore.cpp clang/lib/Basic/Targets/XCore.h 
clang/lib/CodeGen/CGBuiltin.cpp clang/lib/CodeGen/CodeGenModule.cpp 
clang/lib/Sema/SemaARM.cpp clang/lib/Sema/SemaChecking.cpp 
clang/lib/Sema/SemaExpr.cpp clang/lib/StaticAnalyzer/Core/CheckerContext.cpp 
clang/utils/TableGen/NeonEmitter.cpp clang/utils/TableGen/RISCVVEmitter.cpp 
clang/utils/TableGen/SveEmitter.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/utils/TableGen/RISCVVEmitter.cpp 
b/clang/utils/TableGen/RISCVVEmitter.cpp
index e6d68d0b4e..4a36a255c4 100644
--- a/clang/utils/TableGen/RISCVVEmitter.cpp
+++ b/clang/utils/TableGen/RISCVVEmitter.cpp
@@ -549,8 +549,8 @@ void RVVEmitter::createBuiltins(raw_ostream &OS) {
   OS << "#ifdef GET_RISCVV_BUILTIN_INFOS\n";
   for (RVVIntrinsic *Def : UniqueDefs) {
 OS << "Builtin::Info{Builtin::Info::StrOffsets{"
-   << Table.GetStringOffset(Def->getBuiltinName()) << " /* " << 
Def->getBuiltinName()
-   << " */, ";
+   << Table.GetStringOffset(Def->getBuiltinName()) << " /* "
+   << Def->getBuiltinName() << " */, ";
 if (Def->hasBuiltinAlias()) {
   OS << "0, ";
 } else {

``




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


[clang] Patch series to reapply #118734 and substantially improve it (PR #120534)

2024-12-19 Thread Chandler Carruth via cfe-commits

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


[clang] Patch series to reapply #118734 and substantially improve it (PR #120534)

2024-12-19 Thread Chandler Carruth via cfe-commits

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


[clang] [clang-tools-extra] [clangd][clang-tidy] Make clangd run `format::cleanupAroundReplacements()` for all code actions just as clang-tidy does (PR #118569)

2024-12-19 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 commented:

clang-tidy part is fine for me. If it's only a refactor for clang-tidy, you 
could remove the `[clang-tidy]` in title.

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


[clang] Patch series to reapply #118734 and substantially improve it (PR #120534)

2024-12-19 Thread via cfe-commits

dyung wrote:

> @dyung - I believe this PR may be a credible path to address the issues hit 
> with your MSVC builders, would appreciate any help testing it in advance if 
> possible.

Sure, I'll give it a try

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


[libcxx] [libcxxabi] [libunwind] [llvm] [runtimes] Probe for -nostdlib++ and -nostdinc++ with the C compiler (PR #108357)

2024-12-19 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

#120370 was reverted, because libc++ tests expose major problem:
Tests and likely many users can have `-nostdlib++ -lc++`.
The if we remove c++ sanitizer runtimes from linking it will break them and 
force to add `-fsanitize-link-c++-runtime`

I will reland unrelated parts of #120370, and think for other solutions.



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


[clang] [clang-format] Add BreakBeforeTemplateClose option (PR #118046)

2024-12-19 Thread Björn Schäpers via cfe-commits


@@ -11077,6 +11077,221 @@ TEST_F(FormatTest, 
WrapsTemplateDeclarationsWithComments) {
   Style);
 }
 
+TEST_F(FormatTest, BreakBeforeTemplateClose) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
+  Style.ColumnLimit = 0;
+  verifyNoChange("template \n"
+ "void foo() {}",
+ Style);
+  verifyNoChange("template <\n"
+ "typename Foo,\n"
+ "typename Bar>\n"
+ "void foo() {}",
+ Style);
+  // when BreakBeforeTemplateClose is off, this line break is removed:
+  verifyFormat("template <\n"
+   "typename Foo,\n"
+   "typename Bar>\n"
+   "void foo() {}",
+   "template <\n"
+   "typename Foo,\n"
+   "typename Bar\n"
+   ">\n"
+   "void foo() {}",
+   Style);
+  Style.BreakBeforeTemplateClose = true;
+  // BreakBeforeTemplateClose should NOT force multiline templates
+  verifyNoChange("template \n"
+ "void foo() {}",
+ Style);
+  verifyNoChange("template \n"
+ "void foo() {}",
+ Style);
+  // it should allow a line break:
+  verifyNoChange("template <\n"
+ "typename Foo\n"
+ ">\n"
+ "void foo() {}",
+ Style);
+  verifyNoChange("template <\n"
+ "typename Foo,\n"
+ "typename Bar\n"
+ ">\n"
+ "void foo() {}",
+ Style);
+  // it should add a line break if not already present:
+  verifyFormat("template <\n"
+   "typename Foo\n"
+   ">\n"
+   "void foo() {}",
+   "template <\n"
+   "typename Foo>\n"
+   "void foo() {}",
+   Style);
+  verifyFormat("template <\n"
+   "typename Foo,\n"
+   "typename Bar\n"
+   ">\n"
+   "void foo() {}",
+   "template <\n"
+   "typename Foo,\n"
+   "typename Bar>\n"
+   "void foo() {}",
+   Style);
+  // when within an indent scope, the > should be placed appropriately:
+  verifyFormat("struct Baz {\n"
+   "  template <\n"
+   "  typename Foo,\n"
+   "  typename Bar\n"
+   "  >\n"
+   "  void foo() {}\n"
+   "};",
+   "struct Baz {\n"
+   "  template <\n"
+   "  typename Foo,\n"
+   "  typename Bar>\n"
+   "  void foo() {}\n"
+   "};",
+   Style);
+
+  // test from issue #80049
+  verifyFormat(
+  "void foo() {\n"
+  "  using type = std::remove_cv_t<\n"
+  "  add_common_cv_reference<\n"
+  "  std::common_type_t, std::decay_t>,\n"
+  "  T0,\n"
+  "  T1\n"
+  "  >\n"
+  "  >;\n"
+  "}\n",
+  "void foo() {\n"
+  "  using type = std::remove_cv_t<\n"
+  "  add_common_cv_reference<\n"
+  "  std::common_type_t, std::decay_t>,\n"
+  "  T0,\n"
+  "  T1>>;\n"
+  "}\n",
+  Style);
+
+  // test lambda goes to next line:

HazardyKnusperkeks wrote:

Can you also add a lambda where the template is not on a new line? And multiple 
template parameters?

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


[clang] Patch series to reapply #118734 and substantially improve it (PR #120534)

2024-12-19 Thread via cfe-commits

dyung wrote:

> > @dyung - I believe this PR may be a credible path to address the issues hit 
> > with your MSVC builders, would appreciate any help testing it in advance if 
> > possible.
> 
> Sure, I'll give it a try

You seem to still be working on it, can you tell me which commit I should try 
building/testing when you are done?

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


[clang] Patch series to reapply #118734 and substantially improve it (PR #120534)

2024-12-19 Thread Chandler Carruth via cfe-commits

chandlerc wrote:

> > > @dyung - I believe this PR may be a credible path to address the issues 
> > > hit with your MSVC builders, would appreciate any help testing it in 
> > > advance if possible.
> > 
> > 
> > Sure, I'll give it a try
> 
> You seem to still be working on it, can you tell me which commit I should try 
> building/testing when you are done?

Sorry, was just tidying up things that I missed until the PR was uploaded. Only 
rebasing on top-of-tree and a clang-format issue, nothing that changes 
functionality. And I think all done now so you should be good-to-go with the 
top of this PR (I think [`2bcc4e5` 
(#120534)](https://github.com/llvm/llvm-project/pull/120534/commits/2bcc4e5f7043dab1ef673dd20b38009363db51db)
 is the link to that commit)

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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-19 Thread Stephen Senran Zhang via cfe-commits


@@ -1520,15 +1520,102 @@ ConstantRange ConstantRange::binaryNot() const {
   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
 }
 
+/// Estimate the 'bit-masked AND' operation's lower bound.
+///
+/// E.g., given two ranges as follows (single quotes are separators and
+/// have no meaning here),
+///
+///   LHS = [10'001'010,  ; LLo
+///  10'100'000]  ; LHi
+///   RHS = [10'111'010,  ; RLo
+///  10'111'100]  ; RHi
+///
+/// we know that the higher 2 bits of the result is always '10'; and note that
+/// there's at least one bit is 1 in LHS[3:6] (since the range is continuous),
+/// and all bits in RHS[3:6] are 1, so we know the lower bound of the result is
+/// 10'001'000.
+///
+/// The algorithm is as follows,
+/// 1. we first calculate a mask to mask out the higher common bits by
+///   Mask = (LLo ^ LHi) | (LLo ^ LHi) | (LLo ^ RLo);
+///   Mask = set all non-leading-zero bits to 1 for Mask;
+/// 2. find the bit field with at least 1 in LHS (i.e., bit 3:6 in the example)
+///after applying the mask, with
+///   StartBit = BitWidth - (LLo & Mask).clz() - 1;
+///   EndBit = BitWidth - (LHi & Mask).clz();
+/// 3. check if all bits in [StartBit:EndBit] in RHS are 1, and all bits of
+///RLo and RHi in [StartBit:BitWidth] are same, and if so, the lower bound
+///can be updated to
+///   LowerBound = LLo & Keep;
+///where Keep is a mask to mask out trailing bits (the lower 3 bits in the
+///example);
+/// 4. repeat the step 2 and 3 with LHS and RHS swapped, and update the lower
+///bound with the smaller one.
+static APInt estimateBitMaskedAndLowerBound(const ConstantRange &LHS,
+const ConstantRange &RHS) {
+  auto BitWidth = LHS.getBitWidth();
+  // If either is full set or unsigned wrapped, then the range must contain '0'
+  // which leads the lower bound to 0.
+  if ((LHS.isFullSet() || RHS.isFullSet()) ||
+  (LHS.isWrappedSet() || RHS.isWrappedSet()))
+return APInt::getZero(BitWidth);
+
+  auto LLo = LHS.getLower();
+  auto LHi = LHS.getUpper() - 1;

zsrkmyn wrote:

May I know why?

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


[libcxx] [libcxxabi] [libunwind] [llvm] [runtimes] Probe for -nostdlib++ and -nostdinc++ with the C compiler (PR #108357)

2024-12-19 Thread Martin Storsjö via cfe-commits

mstorsjo wrote:

> #120370 was reverted, because libc++ tests expose major problem:
> Tests and likely many users can have `-nostdlib++ -lc++`.
> The if we remove c++ sanitizer runtimes from linking it will break them and 
> force to add `-fsanitize-link-c++-runtime`

That's indeed a problem... However the libc++ test failure, as far as I can 
see, seems to be that there was a libc++ test that used to fail when built with 
sanitizers, but that test now no longer fail in that configuration. (I'm not 
entirely sure why it did use to fail though - but I guess that discussion 
belongs in #120370 - I'll comment more on it there.)

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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-19 Thread Stephen Senran Zhang via cfe-commits


@@ -1520,15 +1520,102 @@ ConstantRange ConstantRange::binaryNot() const {
   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
 }
 
+/// Estimate the 'bit-masked AND' operation's lower bound.
+///
+/// E.g., given two ranges as follows (single quotes are separators and
+/// have no meaning here),
+///
+///   LHS = [10'001'010,  ; LLo
+///  10'100'000]  ; LHi
+///   RHS = [10'111'010,  ; RLo
+///  10'111'100]  ; RHi
+///
+/// we know that the higher 2 bits of the result is always '10'; and note that
+/// there's at least one bit is 1 in LHS[3:6] (since the range is continuous),
+/// and all bits in RHS[3:6] are 1, so we know the lower bound of the result is
+/// 10'001'000.
+///
+/// The algorithm is as follows,
+/// 1. we first calculate a mask to mask out the higher common bits by
+///   Mask = (LLo ^ LHi) | (LLo ^ LHi) | (LLo ^ RLo);
+///   Mask = set all non-leading-zero bits to 1 for Mask;
+/// 2. find the bit field with at least 1 in LHS (i.e., bit 3:6 in the example)
+///after applying the mask, with
+///   StartBit = BitWidth - (LLo & Mask).clz() - 1;
+///   EndBit = BitWidth - (LHi & Mask).clz();
+/// 3. check if all bits in [StartBit:EndBit] in RHS are 1, and all bits of
+///RLo and RHi in [StartBit:BitWidth] are same, and if so, the lower bound
+///can be updated to
+///   LowerBound = LLo & Keep;
+///where Keep is a mask to mask out trailing bits (the lower 3 bits in the
+///example);
+/// 4. repeat the step 2 and 3 with LHS and RHS swapped, and update the lower
+///bound with the smaller one.
+static APInt estimateBitMaskedAndLowerBound(const ConstantRange &LHS,
+const ConstantRange &RHS) {
+  auto BitWidth = LHS.getBitWidth();
+  // If either is full set or unsigned wrapped, then the range must contain '0'
+  // which leads the lower bound to 0.
+  if ((LHS.isFullSet() || RHS.isFullSet()) ||
+  (LHS.isWrappedSet() || RHS.isWrappedSet()))
+return APInt::getZero(BitWidth);
+
+  auto LLo = LHS.getLower();
+  auto LHi = LHS.getUpper() - 1;
+  auto RLo = RHS.getLower();
+  auto RHi = RHS.getUpper() - 1;
+
+  // Calculate the mask that mask out the higher common bits.
+  auto Mask = (LLo ^ LHi) | (RLo ^ RHi) | (LLo ^ RLo);
+  unsigned LeadingZeros = Mask.countLeadingZeros();
+  Mask.setLowBits(BitWidth - LeadingZeros);
+
+  auto estimateBound =
+  [BitWidth, &Mask](const APInt &ALo, const APInt &AHi, const APInt &BLo,
+const APInt &BHi) -> std::optional {
+unsigned LeadingZeros = (ALo & Mask).countLeadingZeros();
+if (LeadingZeros == BitWidth)
+  return std::nullopt;
+
+unsigned StartBit = BitWidth - LeadingZeros - 1;
+
+if (BLo.extractBits(BitWidth - StartBit, StartBit) !=
+BHi.extractBits(BitWidth - StartBit, StartBit))
+  return std::nullopt;
+
+unsigned EndBit = BitWidth - (AHi & Mask).countLeadingZeros();
+if (!(BLo.extractBits(EndBit - StartBit, StartBit) &
+  BHi.extractBits(EndBit - StartBit, StartBit))
+ .isAllOnes())
+  return std::nullopt;
+
+APInt Keep(BitWidth, 0);
+Keep.setBits(StartBit, BitWidth);
+return Keep & ALo;
+  };
+
+  auto LowerBoundByLHS = estimateBound(LLo, LHi, RLo, RHi);
+  auto LowerBoundByRHS = estimateBound(RLo, RHi, LLo, LHi);
+
+  if (LowerBoundByLHS && LowerBoundByRHS)
+return LowerBoundByLHS->ult(*LowerBoundByRHS) ? *LowerBoundByLHS

zsrkmyn wrote:

Great catch!

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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-19 Thread Stephen Senran Zhang via cfe-commits


@@ -1520,15 +1520,102 @@ ConstantRange ConstantRange::binaryNot() const {
   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
 }
 
+/// Estimate the 'bit-masked AND' operation's lower bound.
+///
+/// E.g., given two ranges as follows (single quotes are separators and
+/// have no meaning here),
+///
+///   LHS = [10'001'010,  ; LLo
+///  10'100'000]  ; LHi
+///   RHS = [10'111'010,  ; RLo
+///  10'111'100]  ; RHi
+///
+/// we know that the higher 2 bits of the result is always '10'; and note that
+/// there's at least one bit is 1 in LHS[3:6] (since the range is continuous),
+/// and all bits in RHS[3:6] are 1, so we know the lower bound of the result is
+/// 10'001'000.
+///
+/// The algorithm is as follows,
+/// 1. we first calculate a mask to mask out the higher common bits by
+///   Mask = (LLo ^ LHi) | (LLo ^ LHi) | (LLo ^ RLo);
+///   Mask = set all non-leading-zero bits to 1 for Mask;
+/// 2. find the bit field with at least 1 in LHS (i.e., bit 3:6 in the example)
+///after applying the mask, with
+///   StartBit = BitWidth - (LLo & Mask).clz() - 1;
+///   EndBit = BitWidth - (LHi & Mask).clz();
+/// 3. check if all bits in [StartBit:EndBit] in RHS are 1, and all bits of
+///RLo and RHi in [StartBit:BitWidth] are same, and if so, the lower bound
+///can be updated to
+///   LowerBound = LLo & Keep;
+///where Keep is a mask to mask out trailing bits (the lower 3 bits in the
+///example);
+/// 4. repeat the step 2 and 3 with LHS and RHS swapped, and update the lower
+///bound with the smaller one.
+static APInt estimateBitMaskedAndLowerBound(const ConstantRange &LHS,
+const ConstantRange &RHS) {
+  auto BitWidth = LHS.getBitWidth();
+  // If either is full set or unsigned wrapped, then the range must contain '0'
+  // which leads the lower bound to 0.
+  if ((LHS.isFullSet() || RHS.isFullSet()) ||
+  (LHS.isWrappedSet() || RHS.isWrappedSet()))
+return APInt::getZero(BitWidth);
+
+  auto LLo = LHS.getLower();
+  auto LHi = LHS.getUpper() - 1;
+  auto RLo = RHS.getLower();
+  auto RHi = RHS.getUpper() - 1;
+
+  // Calculate the mask that mask out the higher common bits.
+  auto Mask = (LLo ^ LHi) | (RLo ^ RHi) | (LLo ^ RLo);
+  unsigned LeadingZeros = Mask.countLeadingZeros();
+  Mask.setLowBits(BitWidth - LeadingZeros);
+
+  auto estimateBound =
+  [BitWidth, &Mask](const APInt &ALo, const APInt &AHi, const APInt &BLo,
+const APInt &BHi) -> std::optional {
+unsigned LeadingZeros = (ALo & Mask).countLeadingZeros();
+if (LeadingZeros == BitWidth)
+  return std::nullopt;
+
+unsigned StartBit = BitWidth - LeadingZeros - 1;
+
+if (BLo.extractBits(BitWidth - StartBit, StartBit) !=
+BHi.extractBits(BitWidth - StartBit, StartBit))
+  return std::nullopt;
+
+unsigned EndBit = BitWidth - (AHi & Mask).countLeadingZeros();
+if (!(BLo.extractBits(EndBit - StartBit, StartBit) &
+  BHi.extractBits(EndBit - StartBit, StartBit))
+ .isAllOnes())
+  return std::nullopt;
+
+APInt Keep(BitWidth, 0);
+Keep.setBits(StartBit, BitWidth);
+return Keep & ALo;

zsrkmyn wrote:

clearLowBits works in place and returns void, and that's why I didn't use it 
LOL.

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


[clang] Patch series to reapply #118734 and substantially improve it (PR #120534)

2024-12-19 Thread via cfe-commits

dyung wrote:

> > > > @dyung - I believe this PR may be a credible path to address the issues 
> > > > hit with your MSVC builders, would appreciate any help testing it in 
> > > > advance if possible.
> > > 
> > > 
> > > Sure, I'll give it a try
> > 
> > 
> > You seem to still be working on it, can you tell me which commit I should 
> > try building/testing when you are done?
> 
> Sorry, was just tidying up things that I missed until the PR was uploaded. 
> Only rebasing on top-of-tree and a clang-format issue, nothing that changes 
> functionality. And I think all done now so you should be good-to-go with the 
> top of this PR (I think [`2bcc4e5` 
> (#120534)](https://github.com/llvm/llvm-project/pull/120534/commits/2bcc4e5f7043dab1ef673dd20b38009363db51db)
>  is the link to that commit)

I'll try it and let you know. Give me about an hour or so.

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


[clang] [webkit.UncountedLambdaCapturesChecker] Detect protectedThis pattern. (PR #120528)

2024-12-19 Thread Rashmi Mudduluru via cfe-commits


@@ -207,6 +207,58 @@ struct RefCountableWithLambdaCapturingThis {
 };
 call(lambda);
   }
+
+  void method_captures_this_unsafe_capture_local_var_explicitly() {
+RefCountable* x = make_obj();
+call([this, protectedThis = RefPtr { this }, x]() {
+  // expected-warning@-1{{Captured raw-pointer 'x' to ref-counted type or 
CheckedPtr-capable type is unsafe [webkit.UncountedLambdaCapturesChecker]}}
+  nonTrivial();
+  x->method();
+});
+  }
+
+  void method_captures_this_with_other_protected_var() {
+RefCountable* x = make_obj();
+call([this, protectedX = RefPtr { x }]() {
+  // expected-warning@-1{{Captured raw-pointer 'this' to ref-counted type 
or CheckedPtr-capable type is unsafe [webkit.UncountedLambdaCapturesChecker]}}
+  nonTrivial();
+  protectedX->method();
+});
+  }
+
+  void method_captures_this_unsafe_capture_local_var_explicitly_with_deref() {
+RefCountable* x = make_obj();
+call([this, protectedThis = Ref { *this }, x]() {
+  // expected-warning@-1{{Captured raw-pointer 'x' to ref-counted type or 
CheckedPtr-capable type is unsafe [webkit.UncountedLambdaCapturesChecker]}}
+  nonTrivial();
+  x->method();
+});
+  }
+
+  void method_captures_this_unsafe_local_var_via_vardecl() {
+RefCountable* x = make_obj();
+auto lambda = [this, protectedThis = Ref { *this }, x]() {
+  // expected-warning@-1{{Captured raw-pointer 'x' to ref-counted type or 
CheckedPtr-capable type is unsafe [webkit.UncountedLambdaCapturesChecker]}}
+  nonTrivial();
+  x->method();
+};
+call(lambda);
+  }
+
+  void method_captures_this_with_guardian() {
+auto lambda = [this, protectedThis = Ref { *this }]() {
+  nonTrivial();
+};
+call(lambda);
+  }
+
+  void method_captures_this_with_guardian_refPtr() {
+auto lambda = [this, protectedThis = RefPtr { &*this }]() {
+  nonTrivial();
+};
+call(lambda);
+  }
+
 };

t-rasmud wrote:

@rniwa I'm running into the following crash when I run this test locally:

```
RUN: at line 1: /Users/admin/webkit-pr/build-xcode/bin/clang -cc1 
-internal-isystem /Users/admin/webkit-pr/build-xcode/lib/clang/20/include 
-nostdsysteminc -analyze -analyzer-constraints=range -setup-static-analyzer 
-analyzer-checker=webkit.UncountedLambdaCapturesChecker -verify 
/Users/admin/webkit-pr/llvm-project/clang/test/Analysis/Checkers/WebKit/uncounted-lambda-captures.cpp
+ /Users/admin/webkit-pr/build-xcode/bin/clang -cc1 -internal-isystem 
/Users/admin/webkit-pr/build-xcode/lib/clang/20/include -nostdsysteminc 
-analyze -analyzer-constraints=range -setup-static-analyzer 
-analyzer-checker=webkit.UncountedLambdaCapturesChecker -verify 
/Users/admin/webkit-pr/llvm-project/clang/test/Analysis/Checkers/WebKit/uncounted-lambda-captures.cpp
Assertion failed: (capturesVariable() && "No variable available for capture"), 
function getCapturedVar, file LambdaCapture.h, line 105.
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and 
include the crash backtrace, preprocessed source, and associated run script.
Stack dump:
0.  Program arguments: /Users/admin/webkit-pr/build-xcode/bin/clang -cc1 
-internal-isystem /Users/admin/webkit-pr/build-xcode/lib/clang/20/include 
-nostdsysteminc -analyze -analyzer-constraints=range -setup-static-analyzer 
-analyzer-checker=webkit.UncountedLambdaCapturesChecker -verify 
/Users/admin/webkit-pr/llvm-project/clang/test/Analysis/Checkers/WebKit/uncounted-lambda-captures.cpp
1.   parser at end of file
 #0 0x00010a558d5c llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
(/Users/admin/webkit-pr/build-xcode/bin/clang-20+0x10a048d5c)
 #1 0x00010a559258 PrintStackTraceSignalHandler(void*) 
(/Users/admin/webkit-pr/build-xcode/bin/clang-20+0x10a049258)
 #2 0x00010a5572b0 llvm::sys::RunSignalHandlers() 
(/Users/admin/webkit-pr/build-xcode/bin/clang-20+0x10a0472b0)
 #3 0x00010a559fbc SignalHandler(int) 
(/Users/admin/webkit-pr/build-xcode/bin/clang-20+0x10a049fbc)
 #4 0x0001991dc184 (/usr/lib/system/libsystem_platform.dylib+0x180484184)
 #5 0x0001991a6f70 (/usr/lib/system/libsystem_pthread.dylib+0x18044ef70)
 #6 0x0001990b3908 (/usr/lib/system/libsystem_c.dylib+0x18035b908)
 #7 0x0001990b2c1c (/usr/lib/system/libsystem_c.dylib+0x18035ac1c)
 #8 0x00010217f778 clang::LambdaCapture::getCapturedVar() const 
(/Users/admin/webkit-pr/build-xcode/bin/clang-20+0x101c6f778)
 #9 0x000105979588 (anonymous 
namespace)::UncountedLambdaCapturesChecker::visitLambdaExpr(clang::LambdaExpr*, 
bool, bool) const (/Users/admin/webkit-pr/build-xcode/bin/clang-20+0x105469588)
#10 0x0001059775b8 (anonymous 
namespace)::UncountedLambdaCapturesChecker::checkASTDecl(clang::TranslationUnitDecl
 const*, clang::ento::AnalysisManager&, clang::ento::BugReporter&) 
const::LocalVisitor::VisitDeclRefExpr(clang::DeclRefExpr*) 
(/Users/admin/webkit-pr/build-xcode/bin/clang-20+0x1054675b8)
#11 0

[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-19 Thread Stephen Senran Zhang via cfe-commits


@@ -1520,15 +1520,102 @@ ConstantRange ConstantRange::binaryNot() const {
   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
 }
 
+/// Estimate the 'bit-masked AND' operation's lower bound.
+///
+/// E.g., given two ranges as follows (single quotes are separators and
+/// have no meaning here),
+///
+///   LHS = [10'001'010,  ; LLo
+///  10'100'000]  ; LHi
+///   RHS = [10'111'010,  ; RLo
+///  10'111'100]  ; RHi
+///
+/// we know that the higher 2 bits of the result is always '10'; and note that
+/// there's at least one bit is 1 in LHS[3:6] (since the range is continuous),
+/// and all bits in RHS[3:6] are 1, so we know the lower bound of the result is
+/// 10'001'000.
+///
+/// The algorithm is as follows,
+/// 1. we first calculate a mask to mask out the higher common bits by
+///   Mask = (LLo ^ LHi) | (LLo ^ LHi) | (LLo ^ RLo);
+///   Mask = set all non-leading-zero bits to 1 for Mask;
+/// 2. find the bit field with at least 1 in LHS (i.e., bit 3:6 in the example)
+///after applying the mask, with
+///   StartBit = BitWidth - (LLo & Mask).clz() - 1;
+///   EndBit = BitWidth - (LHi & Mask).clz();
+/// 3. check if all bits in [StartBit:EndBit] in RHS are 1, and all bits of
+///RLo and RHi in [StartBit:BitWidth] are same, and if so, the lower bound
+///can be updated to
+///   LowerBound = LLo & Keep;
+///where Keep is a mask to mask out trailing bits (the lower 3 bits in the
+///example);
+/// 4. repeat the step 2 and 3 with LHS and RHS swapped, and update the lower
+///bound with the smaller one.
+static APInt estimateBitMaskedAndLowerBound(const ConstantRange &LHS,
+const ConstantRange &RHS) {
+  auto BitWidth = LHS.getBitWidth();
+  // If either is full set or unsigned wrapped, then the range must contain '0'
+  // which leads the lower bound to 0.
+  if ((LHS.isFullSet() || RHS.isFullSet()) ||
+  (LHS.isWrappedSet() || RHS.isWrappedSet()))

zsrkmyn wrote:

Extra parenthesis was added here to avoid clang-format to break the line 
unintentionally. :-D

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


[libcxx] [libcxxabi] [libunwind] [llvm] [runtimes] Probe for -nostdlib++ and -nostdinc++ with the C compiler (PR #108357)

2024-12-19 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

> > #120370 was reverted, because libc++ tests expose major problem:
> > Tests and likely many users can have `-nostdlib++ -lc++`.
> > The if we remove c++ sanitizer runtimes from linking it will break them and 
> > force to add `-fsanitize-link-c++-runtime`
> 
> That's indeed a problem... However the libc++ test failure, as far as I can 
> see, seems to be that there was a libc++ test that used to fail when built 
> with sanitizers, but that test now no longer fail in that configuration. (I'm 
> not entirely sure why it did use to fail though - but I guess that discussion 
> belongs in #120370 - I'll comment more on it there.)

That's apply to asan,msan

`-nostdlib++ -lc++` is relevant for many ubsan tests 
https://lab.llvm.org/buildbot/#/builders/25/builds/5017

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


[clang] Patch series to reapply #118734 and substantially improve it (PR #120534)

2024-12-19 Thread Chandler Carruth via cfe-commits

chandlerc wrote:

> I'll try it and let you know. Give me about an hour or so.

Awesome! But no huge rush, mostly just hoping this happens to dodge whatever 
has been tripping up things here.

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


[clang] [llvm] [ConstantRange] Estimate tighter lower (upper) bounds for masked binary and (or) (PR #120352)

2024-12-19 Thread Stephen Senran Zhang via cfe-commits

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


[clang] [compiler-rt] [driver] Fix sanitizer libc++ runtime linking (PR #120370)

2024-12-19 Thread Martin Storsjö via cfe-commits

mstorsjo wrote:

This was reverted, because 
https://github.com/llvm/llvm-project/blob/main/libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp
 in libc++ started passing unexpectedly.

I'm not entirely sure about why that is though - previously, it used to fail 
like this:
```
/home/martin/clang-trunk/bin/clang++ /home/martin/code/llvm-project/libcxx/test/
libcxx/language.support/support.dynamic/libcpp_deallocate.sh.cpp -pthread --targ
et=x86_64-unknown-linux-gnu -g -fno-omit-frame-pointer -fsanitize=address -nostd
inc++ -I /home/martin/code/llvm-project/build-libcxx-sanitizers/libcxx/test-suit
e-install/include/c++/v1 -I 
/home/martin/code/llvm-project/build-libcxx-sanitizers/libcxx/test-suite-install/include/c++/v1
 -I /home/martin/code/llvm-project/li
bcxx/test/support -std=c++26 -Werror -Wall -Wctad-maybe-unsupported -Wextra -Wsh
adow -Wundef -Wunused-template -Wno-unused-command-line-argument -Wno-attributes
 -Wno-pessimizing-move -Wno-noexcept-type -Wno-atomic-alignment -Wno-reserved-mo
dule-identifier -Wdeprecated-copy -Wdeprecated-copy-dtor -Wno-user-defined-liter
als -Wno-tautological-compare -Wsign-compare -Wunused-variable -Wunused-paramete
r -Wunreachable-code -Wno-unused-local-typedef -Wno-local-type-template-args -Wn
o-c++11-extensions -Wno-unknown-pragmas -Wno-pass-failed -Wno-mismatched-new-del
ete -Wno-redundant-move -Wno-self-move -D_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER -D_
LIBCPP_ENABLE_EXPERIMENTAL -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_NONE 
-Werror=thread-safety -Wuser-defined-warnings  -lc++experimental -nostdlib++ -L 
/home/martin/code/llvm-project/build-libcxx-sanitizers/libcxx/test-suite-install
/lib -Wl,-rpath,/home/martin/code/llvm-project/build-libcxx-sanitizers/libcxx/te
st-suite-install/lib -lc++ -latomic -o /home/martin/code/llvm-project/build-libc
xx-sanitizers/libcxx/test/libcxx/language.support/support.dynamic/Output/libcpp_deallocate.sh.cpp.dir/t.tmp.exe
 -faligned-allocation -fsized-deallocation
# executed command: /home/martin/clang-trunk/bin/clang++ /home/martin/code/llvm-
project/libcxx/test/libcxx/language.support/support.dynamic/libcpp_deallocate.sh
.cpp -pthread --target=x86_64-unknown-linux-gnu -g -fno-omit-frame-pointer -fsan
itize=address -nostdinc++ -I /home/martin/code/llvm-project/build-libcxx-sanitiz
ers/libcxx/test-suite-install/include/c++/v1 -I /home/martin/code/llvm-project/b
uild-libcxx-sanitizers/libcxx/test-suite-install/include/c++/v1 -I /home/martin/
code/llvm-project/libcxx/test/support -std=c++26 -Werror -Wall -Wctad-maybe-unsu
pported -Wextra -Wshadow -Wundef -Wunused-template -Wno-unused-command-line-argu
ment -Wno-attributes -Wno-pessimizing-move -Wno-noexcept-type -Wno-atomic-alignm
ent -Wno-reserved-module-identifier -Wdeprecated-copy -Wdeprecated-copy-dtor -Wn
o-user-defined-literals -Wno-tautological-compare -Wsign-compare -Wunused-variab
le -Wunused-parameter -Wunreachable-code -Wno-unused-local-typedef -Wno-local-ty
pe-template-args -Wno-c++11-extensions -Wno-unknown-pragmas -Wno-pass-failed -Wn
o-mismatched-new-delete -Wno-redundant-move -Wno-self-move -D_LIBCPP_HAS_NO_PRAG
MA_SYSTEM_HEADER -D_LIBCPP_ENABLE_EXPERIMENTAL -D_LIBCPP_HARDENING_MODE=_LIBCPP_
HARDENING_MODE_NONE -Werror=thread-safety -Wuser-defined-warnings -lc++experimen
tal -nostdlib++ -L /home/martin/code/llvm-project/build-libcxx-sanitizers/libcxx
/test-suite-install/lib -Wl,-rpath,/home/martin/code/llvm-project/build-libcxx-s
anitizers/libcxx/test-suite-install/lib -lc++ -latomic -o /home/martin/code/llvm
-project/build-libcxx-sanitizers/libcxx/test/libcxx/language.support/support.dyn
amic/Output/libcpp_deallocate.sh.cpp.dir/t.tmp.exe -faligned-allocation 
-fsized-deallocation
# RUN: at line 25
/usr/bin/python3 /home/martin/code/llvm-project/libcxx/utils/run.py --execdir /h
ome/martin/code/llvm-project/build-libcxx-sanitizers/libcxx/test/libcxx/language
.support/support.dynamic/Output/libcpp_deallocate.sh.cpp.dir --  /home/martin/co
de/llvm-project/build-libcxx-sanitizers/libcxx/test/libcxx/language.support/support.dynamic/Output/libcpp_deallocate.sh.cpp.dir/t.tmp.exe
# executed command: /usr/bin/python3 /home/martin/code/llvm-project/libcxx/utils
/run.py --execdir /home/martin/code/llvm-project/build-libcxx-sanitizers/libcxx/
test/libcxx/language.support/support.dynamic/Output/libcpp_deallocate.sh.cpp.dir
 -- 
/home/martin/code/llvm-project/build-libcxx-sanitizers/libcxx/test/libcxx/language.support/support.dynamic/Output/libcpp_deallocate.sh.cpp.dir/t.tmp.exe
# .---command stderr
# | =
# | ==2987905==ERROR: AddressSanitizer: alloc-dealloc-mismatch (operator new vs 
free) on 0x6d15b6e20010
# | #0 0x5b56d8dee976  (/home/martin/code/llvm-project/build-libcxx-sanitize
rs/libcxx/test/libcxx/language.support/support.dynamic/Output/libcpp_deallocate.sh.cpp.dir/t.tmp.exe+0xcf976)
# | #1 0x5b56d8e34578  (/home/martin/code/llvm-project/build-libcxx-sanitize
rs/li

[libcxx] [libcxxabi] [libunwind] [llvm] [runtimes] Probe for -nostdlib++ and -nostdinc++ with the C compiler (PR #108357)

2024-12-19 Thread Martin Storsjö via cfe-commits

mstorsjo wrote:

> > > #120370 was reverted, because libc++ tests expose major problem:
> > > Tests and likely many users can have `-nostdlib++ -lc++`.
> > > The if we remove c++ sanitizer runtimes from linking it will break them 
> > > and force to add `-fsanitize-link-c++-runtime`
> > 
> > 
> > That's indeed a problem... However the libc++ test failure, as far as I can 
> > see, seems to be that there was a libc++ test that used to fail when built 
> > with sanitizers, but that test now no longer fail in that configuration. 
> > (I'm not entirely sure why it did use to fail though - but I guess that 
> > discussion belongs in #120370 - I'll comment more on it there.)
> 
> That's apply to asan,msan
> 
> `-nostdlib++ -lc++` is relevant for many ubsan tests 
> https://lab.llvm.org/buildbot/#/builders/25/builds/5017

Ah, I see, yeah, there's clearly not just one single test failing there. I 
mirrored part of this conversation into #120370 where it may be more on topic 
regarding the fallout of that change.

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


[clang] [clang][Darwin] Remove legacy framework search path logic in the frontend (PR #120149)

2024-12-19 Thread Louis Dionne via cfe-commits


@@ -1,13 +1,6 @@
-// RUN: %clang -cc1 -fcuda-is-device -isysroot /var/empty \
-// RUN:   -triple nvptx-nvidia-cuda -aux-triple i386-apple-macosx \
-// RUN:   -E -fcuda-is-device -v -o /dev/null -x cuda %s 2>&1 | FileCheck %s
-
-// RUN: %clang -cc1 -isysroot /var/empty \
-// RUN:   -triple i386-apple-macosx -aux-triple nvptx-nvidia-cuda \
-// RUN:   -E -fcuda-is-device -v -o /dev/null -x cuda %s 2>&1 | FileCheck %s
-
 // Check that when we do CUDA host and device compiles on MacOS, we check for
 // includes in /System/Library/Frameworks and /Library/Frameworks.
 
-// CHECK-DAG: ignoring nonexistent directory 
"/var/empty/System/Library/Frameworks"
-// CHECK-DAG: ignoring nonexistent directory "/var/empty/Library/Frameworks"
+// RUN: %clang -isysroot /var/empty -target unknown-nvidia-cuda -v 
-fsyntax-only -x cuda %s -### 2>&1 | FileCheck %s

ldionne wrote:

Oh, okay then! So I'll just remove that test entirely.

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


[clang-tools-extra] Added options to readability-implicit-bool-conversion (PR #120087)

2024-12-19 Thread via cfe-commits


@@ -319,10 +319,9 @@ Changes in existing checks
   diagnostic.
 
 - Improved :doc:`readability-implicit-bool-conversion
-  ` check
-  by adding the option `UseUpperCaseLiteralSuffix` to select the
-  case of the literal suffix in fixes and fixing false positive for implicit
-  conversion of comparison result in C23.
+  ` check by adding the
+   options:
+   
`UseUpperCaseLiteralSuffix`,`CheckConversionsToBool`,`CheckConversionsFromBool`.

4m4n-x-B4w4ne wrote:

Done Thanks.

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


[clang] [analyzer] Handle [[assume(cond)]] as __builtin_assume(cond) (PR #116462)

2024-12-19 Thread Thurston Dang via cfe-commits

thurstond wrote:

I've reverted it in 
https://github.com/llvm/llvm-project/commit/2b9abf0db2d106c7208b4372e662ef5df869e6f1
 to clear up some buildbots

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


[clang] 2b9abf0 - Revert "[analyzer] Handle [[assume(cond)]] as __builtin_assume(cond) (#116462)"

2024-12-19 Thread Thurston Dang via cfe-commits

Author: Thurston Dang
Date: 2024-12-19T17:02:16Z
New Revision: 2b9abf0db2d106c7208b4372e662ef5df869e6f1

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

LOG: Revert "[analyzer] Handle [[assume(cond)]] as __builtin_assume(cond) 
(#116462)"

This reverts commit 89da344e5879e5347b5057520d5230e40ae24831.

Reason: buildbot breakages e.g., 
https://lab.llvm.org/buildbot/#/builders/55/builds/4556 (for which the reverted 
patch is the only code change)

Added: 


Modified: 
clang/include/clang/AST/AttrIterator.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
clang/lib/Analysis/CFG.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
clang/test/Analysis/out-of-bounds-new.cpp

Removed: 
clang/test/Analysis/cxx23-assume-attribute.cpp



diff  --git a/clang/include/clang/AST/AttrIterator.h 
b/clang/include/clang/AST/AttrIterator.h
index 2f39c144dc1608a..7e2bb0381d4c8f0 100644
--- a/clang/include/clang/AST/AttrIterator.h
+++ b/clang/include/clang/AST/AttrIterator.h
@@ -16,7 +16,6 @@
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/ADL.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Casting.h"
 #include 
 #include 
@@ -125,17 +124,6 @@ inline auto *getSpecificAttr(const Container &container) {
   return It != specific_attr_end(container) ? *It : nullptr;
 }
 
-template 
-inline auto getSpecificAttrs(const Container &container) {
-  using ValueTy = llvm::detail::ValueOfRange;
-  using ValuePointeeTy = std::remove_pointer_t;
-  using IterTy = std::conditional_t,
-const SpecificAttr, SpecificAttr>;
-  auto Begin = specific_attr_begin(container);
-  auto End = specific_attr_end(container);
-  return llvm::make_range(Begin, End);
-}
-
 } // namespace clang
 
 #endif // LLVM_CLANG_AST_ATTRITERATOR_H

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index 078a1d840d0516d..8c7493e27fcaa63 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -498,10 +498,6 @@ class ExprEngine {
   void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred,
  ExplodedNodeSet &Dst);
 
-  /// VisitAttributedStmt - Transfer function logic for AttributedStmt
-  void VisitAttributedStmt(const AttributedStmt *A, ExplodedNode *Pred,
-   ExplodedNodeSet &Dst);
-
   /// VisitLogicalExpr - Transfer function logic for '&&', '||'
   void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
 ExplodedNodeSet &Dst);

diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 65f915ef087afab..304bbb2b422c61d 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -433,7 +433,7 @@ class reverse_children {
   ArrayRef children;
 
 public:
-  reverse_children(Stmt *S, ASTContext &Ctx);
+  reverse_children(Stmt *S);
 
   using iterator = ArrayRef::reverse_iterator;
 
@@ -443,47 +443,28 @@ class reverse_children {
 
 } // namespace
 
-reverse_children::reverse_children(Stmt *S, ASTContext &Ctx) {
-  switch (S->getStmtClass()) {
-  case Stmt::CallExprClass: {
-children = cast(S)->getRawSubExprs();
+reverse_children::reverse_children(Stmt *S) {
+  if (CallExpr *CE = dyn_cast(S)) {
+children = CE->getRawSubExprs();
 return;
   }
-
-  // Note: Fill in this switch with more cases we want to optimize.
-  case Stmt::InitListExprClass: {
-InitListExpr *IE = cast(S);
-children = llvm::ArrayRef(reinterpret_cast(IE->getInits()),
-  IE->getNumInits());
-return;
+  switch (S->getStmtClass()) {
+// Note: Fill in this switch with more cases we want to optimize.
+case Stmt::InitListExprClass: {
+  InitListExpr *IE = cast(S);
+  children = llvm::ArrayRef(reinterpret_cast(IE->getInits()),
+IE->getNumInits());
+  return;
+}
+default:
+  break;
   }
-  case Stmt::AttributedStmtClass: {
-auto *AS = cast(S);
 
-// for an attributed stmt, the "children()" returns only the NullStmt
-// (;) but semantically the "children" are supposed to be the
-// expressions _within_ i.e. the two square brackets i.e. [[ HERE ]]
-// so we add the subexpressions first, _then_ add the "children"
+  // Default case for all other statements.
+  llvm::append_range(childrenBuf, S->children());
 
-for (const auto *Attr : AS->getAttrs()) {
-  if (const auto *AssumeAttr = dyn_cast(Attr)) {
-Exp

[clang] [analyzer] Handle [[assume(cond)]] as __builtin_assume(cond) (PR #116462)

2024-12-19 Thread Balazs Benics via cfe-commits

steakhal wrote:

> I've reverted it in 
> https://github.com/llvm/llvm-project/commit/2b9abf0db2d106c7208b4372e662ef5df869e6f1
>  to clear up some buildbots

Thanks! Ill have a look later.

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


[clang] Patch series to reapply #118734 and substantially improve it (PR #120534)

2024-12-19 Thread Chandler Carruth via cfe-commits

chandlerc wrote:

> > > I'll try it and let you know. Give me about an hour or so.
> > 
> > Awesome! But no huge rush, mostly just hoping this happens to dodge 
> > whatever has been tripping up things here.
> 
> Sorry for the delay, but the failures still seem to be present. :( (The tests 
> are still running, but the amount of output being generated is slowing things 
> down).

Strange... Is it the *same* output??

Can you upload the output somewhere? 

> 
> Just a heads up, we are probably going to be upgrading our internal machines 
> and upstream bot to a later build of VS2019 to avoid this issue. I'm 
> validating a newer build today and if all goes well, I am going to try and 
> get it deployed on Friday.

While this generally seems good, I'd like to avoid requiring even more MSVC 
upgrades, so interested in knowing how this is failing.



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


[clang] Patch series to reapply #118734 and substantially improve it (PR #120534)

2024-12-19 Thread Chandler Carruth via cfe-commits

chandlerc wrote:


> Overall, I'm positive on this, and think this is beneficial.  If this is 
> something we can get to settle (I recognize this is probably what you were 
> talking about with the RFC to increase the 'required MSVC version'), I'm all 
> for it.

Yeah, this was the motivation.

The downside is that the issue dyung and I are discussing is even with a 
version of MSVC past the new baseline. =\




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


[clang-tools-extra] Added options to readability-implicit-bool-conversion (PR #120087)

2024-12-19 Thread via cfe-commits

https://github.com/4m4n-x-B4w4ne updated 
https://github.com/llvm/llvm-project/pull/120087

>From 03f536888ddc5b7be2514c2d880c6d3119b7f4ee Mon Sep 17 00:00:00 2001
From: 4m4n-x-B4w4ne <125849251+4m4n-x-b4w...@users.noreply.github.com>
Date: Mon, 16 Dec 2024 19:43:42 +0530
Subject: [PATCH 01/25] Update ImplicitBoolConversionCheck.cpp

Added new options in ImplicitBoolConversionCheck CheckConversionToBool and 
CheckConversionFromBool.
---
 .../readability/ImplicitBoolConversionCheck.cpp   | 15 +--
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index f9fd1d903e231e..517a5d2b982751 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -258,14 +258,17 @@ ImplicitBoolConversionCheck::ImplicitBoolConversionCheck(
 : ClangTidyCheck(Name, Context),
   AllowIntegerConditions(Options.get("AllowIntegerConditions", false)),
   AllowPointerConditions(Options.get("AllowPointerConditions", false)),
-  UseUpperCaseLiteralSuffix(
-  Options.get("UseUpperCaseLiteralSuffix", false)) {}
+  UseUpperCaseLiteralSuffix(Options.get("UseUpperCaseLiteralSuffix", 
false)),
+  CheckConversionsToBool(Options.get("CheckConversionsToBool",true)),
+  CheckConversionsFromBool(Options.get("CheckConversionsFromBool",true)) {}
 
 void ImplicitBoolConversionCheck::storeOptions(
 ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "AllowIntegerConditions", AllowIntegerConditions);
   Options.store(Opts, "AllowPointerConditions", AllowPointerConditions);
   Options.store(Opts, "UseUpperCaseLiteralSuffix", UseUpperCaseLiteralSuffix);
+  Options.store(Opts,"CheckConversionsToBool",CheckConversionsToBool);
+  Options.store(Opts,"CheckConversionsFromBool",CheckConversionsFromBool);
 }
 
 void ImplicitBoolConversionCheck::registerMatchers(MatchFinder *Finder) {
@@ -358,14 +361,14 @@ void 
ImplicitBoolConversionCheck::registerMatchers(MatchFinder *Finder) {
 void ImplicitBoolConversionCheck::check(
 const MatchFinder::MatchResult &Result) {
 
-  if (const auto *CastToBool =
-  Result.Nodes.getNodeAs("implicitCastToBool")) {
+  if (CheckConversionsToBool && (const auto *CastToBool =
+  Result.Nodes.getNodeAs("implicitCastToBool"))) {
 const auto *Parent = Result.Nodes.getNodeAs("parentStmt");
 return handleCastToBool(CastToBool, Parent, *Result.Context);
   }
 
-  if (const auto *CastFromBool =
-  Result.Nodes.getNodeAs("implicitCastFromBool")) {
+  if (CheckConversionsFromBool && (const auto *CastFromBool =
+  Result.Nodes.getNodeAs("implicitCastFromBool"))) {
 const auto *NextImplicitCast =
 Result.Nodes.getNodeAs("furtherImplicitCast");
 return handleCastFromBool(CastFromBool, NextImplicitCast, *Result.Context);

>From 16c7c95939b4c0c38ebccbbc6cd1da3739244a24 Mon Sep 17 00:00:00 2001
From: 4m4n-x-B4w4ne <125849251+4m4n-x-b4w...@users.noreply.github.com>
Date: Mon, 16 Dec 2024 19:45:37 +0530
Subject: [PATCH 02/25] Update ImplicitBoolConversionCheck.h

Added CheckConversionToBool and CheckConversionFromBool Options in the header
---
 .../clang-tidy/readability/ImplicitBoolConversionCheck.h| 2 ++
 1 file changed, 2 insertions(+)

diff --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.h 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.h
index 5947f7316e67cc..b0c3c2943e649c 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.h
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.h
@@ -37,6 +37,8 @@ class ImplicitBoolConversionCheck : public ClangTidyCheck {
   const bool AllowIntegerConditions;
   const bool AllowPointerConditions;
   const bool UseUpperCaseLiteralSuffix;
+  const bool CheckConversionsToBool;
+  const bool CheckConversionsFromBool;
 };
 
 } // namespace clang::tidy::readability

>From 0d6fae8b08a4a365c9295ac8a96de2aba9974c98 Mon Sep 17 00:00:00 2001
From: 4m4n-x-B4w4ne <125849251+4m4n-x-b4w...@users.noreply.github.com>
Date: Mon, 16 Dec 2024 19:48:48 +0530
Subject: [PATCH 03/25] Create implicit-bool-conversion-check.cpp

Added new test to check the new options added in the 
ImplicitBoolConversionCheck.cpp
---
 .../implicit-bool-conversion-check.cpp| 92 +++
 1 file changed, 92 insertions(+)
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion-check.cpp

diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion-check.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion-check.cpp
new file mode 100644
index 00..506769d5a57322
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers

[clang] [HLSL] Make fast math the default for HLSL (PR #119820)

2024-12-19 Thread Justin Bogner via cfe-commits

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


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


[clang] [clang][Darwin] Remove legacy framework search path logic in the frontend (PR #120149)

2024-12-19 Thread Louis Dionne via cfe-commits


@@ -0,0 +1,26 @@
+// UNSUPPORTED: system-windows
+//   Windows is unsupported because we use the Unix path separator `/` in the 
test.
+
+// Add default directories before running clang to check default
+// search paths.
+// RUN: rm -rf %t && mkdir -p %t
+// RUN: cp -R %S/Inputs/MacOSX15.1.sdk %t/
+// RUN: mkdir -p %t/MacOSX15.1.sdk/System/Library/Frameworks
+// RUN: mkdir -p %t/MacOSX15.1.sdk/System/Library/SubFrameworks
+// RUN: mkdir -p %t/MacOSX15.1.sdk/usr/include
+
+// RUN: %clang -xc %s -target arm64-apple-darwin13.0 -isysroot 
%t/MacOSX15.1.sdk -E -v 2>&1 | FileCheck --check-prefix=CHECK-C %s

ldionne wrote:

What would you want to check for DriverKit? I naively went ahead and started 
adding a test, and then I went back and realized I wasn't sure what you wanted 
me to test.

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


[clang] [HLSL] Make fast math the default for HLSL (PR #119820)

2024-12-19 Thread Chris B via cfe-commits

llvm-beanz wrote:

Quick sanity check question for @bogner:

In DXC we apply the `fast` flag, which in LLVM 3.7 implies: `nnan ninf nsz 
arcp` and includes the modern interpretation of `reassoc`

With this change we are applying: `reassoc nnan ninf nsz arcp afn` (no `fast` 
because its meaning is redefined. The main addition is `afn`.

> Approximate functions - Allow substitution of approximate calculations for 
> functions (sin, log, sqrt, etc). See floating-point intrinsic definitions for 
> places where this can apply to LLVM’s intrinsic math functions.

[source](https://llvm.org/docs/LangRef.html#fast-math-flags)

Two questions:
1) Do we foresee any issue adding `afn` (I suspect not)
2) Do we also need to apply `contract`, which I believe was also implied by 
`fast` in 3.7 although the docs are unclear?

Also, I think we may need to put implement the backend support for translating 
the fast math flags to 3.7-equivalents before we merge this. I'm sorry I hadn't 
thought of that until now, but I expect this change breaks DXIL generation.

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


[clang] [clang][Darwin] Remove legacy framework search path logic in the frontend (PR #120149)

2024-12-19 Thread Louis Dionne via cfe-commits

https://github.com/ldionne updated 
https://github.com/llvm/llvm-project/pull/120149

>From e578bd75d82a5ff16168222e4f30c32f9aa5e6bd Mon Sep 17 00:00:00 2001
From: Louis Dionne 
Date: Mon, 16 Dec 2024 13:28:38 -0500
Subject: [PATCH 1/3] [clang][Darwin] Remove legacy framework search path logic
 in the frontend

This removes a long standing piece of technical debt. Most other platforms
have moved all their header search path logic to the driver, but Darwin
still had some logic for setting framework search paths present in the
frontend. This patch moves that logic to the driver alongside existing
logic that already handles part of these search paths.

To achieve parity with the previous search path order, this patch
introduces the -internal-iframework flag which is used to pass
system framework paths from the driver to the frontend. These paths
are handled specially in that they are added after normal framework
search paths, which preserves the old frontend behavior for system
frameworks.

This patch is a re-application of 
https://github.com/llvm/llvm-project/pull/75841
which was reverted in d34901f30 because it broke framework search paths.
In fact, the original patch was only adding framework search paths to
the linker job, but was not adding search paths for finding headers.
That issue is resolved in this version of the patch, with added tests.

Fixes #75638
---
 clang/include/clang/Driver/Options.td |  5 ++
 clang/lib/Driver/Job.cpp  |  2 +-
 clang/lib/Driver/ToolChains/Darwin.cpp| 49 ++-
 clang/lib/Frontend/CompilerInvocation.cpp |  7 ++-
 clang/lib/Lex/InitHeaderSearch.cpp| 19 ++-
 .../Driver/darwin-framework-search-paths.c| 26 ++
 clang/test/Driver/darwin-subframeworks.c  | 18 ---
 .../test/Preprocessor/cuda-macos-includes.cu  | 13 ++---
 8 files changed, 79 insertions(+), 60 deletions(-)
 create mode 100644 clang/test/Driver/darwin-framework-search-paths.c
 delete mode 100644 clang/test/Driver/darwin-subframeworks.c

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 88862ae9edb29d..8692d5d7eabe1c 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -8265,6 +8265,11 @@ def internal_externc_isystem : Separate<["-"], 
"internal-externc-isystem">,
"implicit extern \"C\" semantics; these are assumed to not be "
"user-provided and are used to model system and standard headers' "
"paths.">;
+def internal_iframework : Separate<["-"], "internal-iframework">,
+  MetaVarName<"">,
+  HelpText<"Add directory to the internal system framework include search 
path; these "
+   "are assumed to not be user-provided and are used to model system "
+   "and standard frameworks' paths.">;
 
 } // let Visibility = [CC1Option]
 
diff --git a/clang/lib/Driver/Job.cpp b/clang/lib/Driver/Job.cpp
index ae2f1cd1f56c99..07d2d371c5626b 100644
--- a/clang/lib/Driver/Job.cpp
+++ b/clang/lib/Driver/Job.cpp
@@ -73,7 +73,7 @@ static bool skipArgs(const char *Flag, bool HaveCrashVFS, int 
&SkipNum,
 .Cases("-internal-externc-isystem", "-iprefix", true)
 .Cases("-iwithprefixbefore", "-isystem", "-iquote", true)
 .Cases("-isysroot", "-I", "-F", "-resource-dir", true)
-.Cases("-iframework", "-include-pch", true)
+.Cases("-internal-iframework", "-iframework", "-include-pch", true)
 .Default(false);
   if (IsInclude)
 return !HaveCrashVFS;
diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index cdb6d21a0148b6..76d6244daff920 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -800,9 +800,15 @@ void darwin::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 }
   }
 
-  // Add non-standard, platform-specific search paths, e.g., for DriverKit:
-  //  -L/System/DriverKit/usr/lib
-  //  -F/System/DriverKit/System/Library/Framework
+  // Add framework include paths and library search paths.
+  // There are two flavors:
+  // 1. The "non-standard" paths, e.g. for DriverKit:
+  //  -L/System/DriverKit/usr/lib
+  //  -F/System/DriverKit/System/Library/Frameworks
+  // 2. The "standard" paths, e.g. for macOS and iOS:
+  //  -F/System/Library/Frameworks
+  //  -F/System/Library/SubFrameworks
+  //  -F/Library/Frameworks
   {
 bool NonStandardSearchPath = false;
 const auto &Triple = getToolChain().getTriple();
@@ -813,18 +819,23 @@ void darwin::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   (Version.getMajor() == 605 && Version.getMinor().value_or(0) < 1);
 }
 
-if (NonStandardSearchPath) {
-  if (auto *Sysroot = Args.getLastArg(options::OPT_isysroot)) {
-auto AddSearchPath = [&](StringRef Flag, StringRef SearchPath) {
-  SmallString<128> P(Sysroot->getValue());
-  AppendPlatformPrefix(P, Triple);
-   

[clang] [clang][Darwin] Remove legacy framework search path logic in the frontend (PR #120149)

2024-12-19 Thread Louis Dionne via cfe-commits


@@ -2539,6 +2550,18 @@ void DarwinClang::AddClangSystemIncludeArgs(const 
llvm::opt::ArgList &DriverArgs
 llvm::sys::path::append(P, "usr", "include");
 addExternCSystemInclude(DriverArgs, CC1Args, P.str());
   }
+
+  // Add default framework search paths
+  auto addFrameworkInclude = [&](auto ...Path) {
+SmallString<128> P(Sysroot);
+llvm::sys::path::append(P, Path...);
+
+CC1Args.push_back("-internal-iframework");
+CC1Args.push_back(DriverArgs.MakeArgString(P));
+  };
+  addFrameworkInclude("System", "Library", "Frameworks");

ldionne wrote:

Do you mean something like this?

```c++
addFrameworkInclude(DriverArgs, CC1Args, P);
```

That's possible, in fact I started with that. However, I will have to do this:

```c++
auto addFrameworkInclude = [](const llvm::opt::ArgList &DriverArgs, 
llvm::opt::ArgStringList &CC1Args, SmallString<128> const& P) {
  CC1Args.push_back("-internal-iframework");
  CC1Args.push_back(DriverArgs.MakeArgString(P));
};

{
  SmallString<128> P(Sysroot);
  llvm::sys::path::append(P, "System", "Library", "Frameworks");
  addFrameworkInclude(DriverArgs, CC1Args, P);
}
{
  SmallString<128> P(Sysroot);
  llvm::sys::path::append(P, "System", "Library", "SubFrameworks");
  addFrameworkInclude(DriverArgs, CC1Args, P);  
}
{
  SmallString<128> P(Sysroot);
  llvm::sys::path::append(P, "Library", "Frameworks");
  addFrameworkInclude(DriverArgs, CC1Args, P);  
}
```

Minor variations on this may be possible, but I thought that was less readable. 
If you have a preference for this (perhaps motivated for future refactoring 
potential), I'm fine with going for that, just let me know.

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


[clang] [flang] [flang] Integrate the option -flang-experimental-integer-overflow into -fno-wrapv (PR #110063)

2024-12-19 Thread Slava Zakharin via cfe-commits

vzakhari wrote:

Thank you for the pointers and the information, Tom!  It looks like exchange2 
is pretty much the same problem as with bwaves.  I posted a note into 
https://github.com/llvm/llvm-project/issues/117318

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


[clang] [CIR] floating-point, pointer, and function types (PR #120484)

2024-12-19 Thread Ronan Keryell via cfe-commits

keryell wrote:


@dkolsen-pgi  Great PR!
Since it touches functions returning `!void` or `!cir.void`, I made some 
changes recently with 
https://github.com/llvm/clangir/commit/568b51537e573c7a8fb616cda5cdd0aa54bc0832 
to avoid disrupting some MLIR invariants.
Are you up-streaming the changes in commit order or are you up-streaming the 
changes with the latest version of a feature?
@joker-eph How to up-stream some changes which are cross-project like 
https://github.com/llvm/clangir/pull/1203 which introduces a new MLIR 
parser/pretty-printer feature like:
https://github.com/llvm/clangir/pull/1203/files#diff-cfea91beb87a3b28295e5612974f0556b4daf9a42c1adeb65e56f0dec062feaa
https://github.com/llvm/clangir/pull/1203/files#diff-6c1c134d749d53cf770548806b955401e47b1f15ffe084905a0b132d73b0b1fe
https://github.com/llvm/clangir/pull/1203/files#diff-dabff257abfd11fded480c2dfc0c2afdf640769384af9e37820e11003a75edb1
to allow some keywords starting with `!`?

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


[clang] [Clang] Implement P2280R4 Using unknown pointers and references in constant expressions (PR #95474)

2024-12-19 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik updated 
https://github.com/llvm/llvm-project/pull/95474

>From 69b09ea5b0f0a1c5419c488ade29b6fedc6de773 Mon Sep 17 00:00:00 2001
From: Shafik Yaghmour 
Date: Thu, 13 Jun 2024 14:20:50 -0700
Subject: [PATCH 1/9] [Clang] Implement P2280R4 Using unknown pointers and
 references in constant expressions

P2280R4 allows the use of references in pointers of unknown origins in a
constant expression context but only in specific cases that could be constant
expressions.

We track whether a variable is a constexpr unknown in a constant expression by
setting a flag in either APValue or LValue and using this flag to prevent using
unknown values in places where it is not allowed.

In `evaluateVarDeclInit` we may need to create a new `APValue` to track the
unknown referene or pointer and we track that `APValue` in the
`CallStackFrame`.

Fixes: https://github.com/llvm/llvm-project/issues/63139
https://github.com/llvm/llvm-project/issues/63117
---
 clang/include/clang/AST/APValue.h | 48 +++
 clang/lib/AST/APValue.cpp | 12 ++-
 clang/lib/AST/ExprConstant.cpp| 85 +--
 .../SemaCXX/constant-expression-cxx11.cpp | 16 ++--
 .../SemaCXX/constant-expression-cxx2a.cpp |  3 +-
 .../SemaCXX/constant-expression-p2280r4.cpp   | 54 
 6 files changed, 183 insertions(+), 35 deletions(-)
 create mode 100644 clang/test/SemaCXX/constant-expression-p2280r4.cpp

diff --git a/clang/include/clang/AST/APValue.h 
b/clang/include/clang/AST/APValue.h
index c4206b73b11562..6352348107a647 100644
--- a/clang/include/clang/AST/APValue.h
+++ b/clang/include/clang/AST/APValue.h
@@ -249,6 +249,7 @@ class APValue {
   struct NoLValuePath {};
   struct UninitArray {};
   struct UninitStruct {};
+  struct ConstexprUnknown {};
 
   template  friend class clang::serialization::BasicReaderBase;
   friend class ASTImporter;
@@ -256,6 +257,7 @@ class APValue {
 
 private:
   ValueKind Kind;
+  bool AllowConstexprUnknown = false;
 
   struct ComplexAPSInt {
 APSInt Real, Imag;
@@ -314,53 +316,69 @@ class APValue {
   DataType Data;
 
 public:
-  APValue() : Kind(None) {}
-  explicit APValue(APSInt I) : Kind(None) {
+  bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
+
+  void setConstexprUnknown() { AllowConstexprUnknown = true; }
+
+  APValue() : Kind(None), AllowConstexprUnknown(false) {}
+  explicit APValue(APSInt I) : Kind(None), AllowConstexprUnknown(false) {
 MakeInt(); setInt(std::move(I));
   }
-  explicit APValue(APFloat F) : Kind(None) {
+  explicit APValue(APFloat F) : Kind(None), AllowConstexprUnknown(false) {
 MakeFloat(); setFloat(std::move(F));
   }
-  explicit APValue(APFixedPoint FX) : Kind(None) {
+  explicit APValue(APFixedPoint FX) : Kind(None), AllowConstexprUnknown(false) 
{
 MakeFixedPoint(std::move(FX));
   }
-  explicit APValue(const APValue *E, unsigned N) : Kind(None) {
+  explicit APValue(const APValue *E, unsigned N)
+  : Kind(None), AllowConstexprUnknown(false) {
 MakeVector(); setVector(E, N);
   }
-  APValue(APSInt R, APSInt I) : Kind(None) {
+  APValue(APSInt R, APSInt I) : Kind(None), AllowConstexprUnknown(false) {
 MakeComplexInt(); setComplexInt(std::move(R), std::move(I));
   }
-  APValue(APFloat R, APFloat I) : Kind(None) {
+  APValue(APFloat R, APFloat I) : Kind(None), AllowConstexprUnknown(false) {
 MakeComplexFloat(); setComplexFloat(std::move(R), std::move(I));
   }
   APValue(const APValue &RHS);
   APValue(APValue &&RHS);
   APValue(LValueBase B, const CharUnits &O, NoLValuePath N,
   bool IsNullPtr = false)
-  : Kind(None) {
+  : Kind(None), AllowConstexprUnknown(false) {
 MakeLValue(); setLValue(B, O, N, IsNullPtr);
   }
   APValue(LValueBase B, const CharUnits &O, ArrayRef Path,
   bool OnePastTheEnd, bool IsNullPtr = false)
-  : Kind(None) {
+  : Kind(None), AllowConstexprUnknown(false) {
 MakeLValue(); setLValue(B, O, Path, OnePastTheEnd, IsNullPtr);
   }
-  APValue(UninitArray, unsigned InitElts, unsigned Size) : Kind(None) {
+
+  APValue(LValueBase B, ConstexprUnknown, const CharUnits &O,
+  bool IsNullPtr = false)
+  : Kind(None), AllowConstexprUnknown(true) {
+MakeLValue();
+setLValue(B, O, NoLValuePath{}, IsNullPtr);
+  }
+
+  APValue(UninitArray, unsigned InitElts, unsigned Size)
+  : Kind(None), AllowConstexprUnknown(false) {
 MakeArray(InitElts, Size);
   }
-  APValue(UninitStruct, unsigned B, unsigned M) : Kind(None) {
+  APValue(UninitStruct, unsigned B, unsigned M)
+  : Kind(None), AllowConstexprUnknown(false) {
 MakeStruct(B, M);
   }
   explicit APValue(const FieldDecl *D, const APValue &V = APValue())
-  : Kind(None) {
+  : Kind(None), AllowConstexprUnknown(false) {
 MakeUnion(); setUnion(D, V);
   }
   APValue(const ValueDecl *Member, bool IsDerivedMember,
-  ArrayRef Path) : Kind(None) {
+  ArrayRef Path)
+  : Kind(None), Allo

[clang] Patch series to reapply #118734 and substantially improve it (PR #120534)

2024-12-19 Thread via cfe-commits

dyung wrote:

> > I'll try it and let you know. Give me about an hour or so.
> 
> Awesome! But no huge rush, mostly just hoping this happens to dodge whatever 
> has been tripping up things here.

Sorry for the delay, but the failures still seem to be present. :( (The tests 
are still running, but the amount of output being generated is slowing things 
down).

Just a heads up, we are probably going to be upgrading our internal machines 
and upstream bot to a later build of VS2019 to avoid this issue. I'm validating 
a newer build today and if all goes well, I am going to try and get it deployed 
on Friday.

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


[clang] [FMV][AArch64] Emit mangled default version if explicitly specified. (PR #120022)

2024-12-19 Thread Alexandros Lamprineas via cfe-commits

https://github.com/labrinea updated 
https://github.com/llvm/llvm-project/pull/120022

>From f3997c43e57265444bade9372833a9235e3426cb Mon Sep 17 00:00:00 2001
From: Alexandros Lamprineas 
Date: Fri, 13 Dec 2024 12:42:31 +
Subject: [PATCH 1/2] [FMV][AArch64] Emit mangled default version if explicitly
 specified.

Curently we need at least one more version other than the default
to trigger FMV. However we would like a header file declaration

__attribute__((target_version("default"))) void f(void);

to guarantee that there will be f.default
---
 clang/lib/CodeGen/CodeGenModule.cpp   |   2 +-
 clang/lib/Sema/SemaDecl.cpp   |  47 ++--
 .../fmv-mix-explicit-implicit-default.c   | 221 ++
 clang/test/CodeGen/attr-target-version.c  |  51 +++-
 clang/test/CodeGenCXX/fmv-namespace.cpp   |  22 +-
 clang/test/Sema/attr-target-version.c |   4 +
 clang/test/SemaCXX/attr-target-version.cpp|   4 +-
 7 files changed, 305 insertions(+), 46 deletions(-)
 create mode 100644 
clang/test/CodeGen/AArch64/fmv-mix-explicit-implicit-default.c

diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index d3d5c0743a520b..b65e3dc2496797 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -4280,7 +4280,7 @@ void CodeGenModule::emitMultiVersionFunctions() {
 getContext().forEachMultiversionedFunctionVersion(
 FD, [&](const FunctionDecl *CurFD) {
   llvm::SmallVector Feats;
-  bool IsDefined = CurFD->doesThisDeclarationHaveABody();
+  bool IsDefined = CurFD->getDefinition() != nullptr;
 
   if (const auto *TA = CurFD->getAttr()) {
 assert(getTarget().getTriple().isX86() && "Unsupported target");
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 55e891e3acf20d..7c3e5ceabb771d 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -11073,9 +11073,9 @@ bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, 
Decl *PrevDecl) {
 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
   const auto *TA = FD->getAttr();
   const auto *TVA = FD->getAttr();
-  assert(
-  (TA || TVA) &&
-  "MultiVersion candidate requires a target or target_version attribute");
+
+  assert((TA || TVA) && "Expecting target or target_version attribute");
+
   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
   enum ErrType { Feature = 0, Architecture = 1 };
 
@@ -11372,10 +11372,6 @@ static bool CheckMultiVersionFirstFunction(Sema &S, 
FunctionDecl *FD) {
   // otherwise it is treated as a normal function.
   if (TA && !TA->isDefaultVersion())
 return false;
-  // The target_version attribute only causes Multiversioning if this
-  // declaration is NOT the default version.
-  if (TVA && TVA->isDefaultVersion())
-return false;
 
   if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
 FD->setInvalidDecl();
@@ -11422,26 +11418,24 @@ static bool 
CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
   LookupResult &Previous) {
   assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
 
+  const auto *NewTA = NewFD->getAttr();
+  const auto *OldTA = OldFD->getAttr();
+  const auto *NewTVA = NewFD->getAttr();
+  const auto *OldTVA = OldFD->getAttr();
+
+  assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
+
   // The definitions should be allowed in any order. If we have discovered
   // a new target version and the preceeding was the default, then add the
   // corresponding attribute to it.
   patchDefaultTargetVersion(NewFD, OldFD);
 
-  const auto *NewTA = NewFD->getAttr();
-  const auto *NewTVA = NewFD->getAttr();
-  const auto *OldTA = OldFD->getAttr();
-
   // If the old decl is NOT MultiVersioned yet, and we don't cause that
   // to change, this is a simple redeclaration.
   if (NewTA && !NewTA->isDefaultVersion() &&
   (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
 return false;
 
-  // The target_version attribute only causes Multiversioning if this
-  // declaration is NOT the default version.
-  if (NewTVA && NewTVA->isDefaultVersion())
-return false;
-
   // Otherwise, this decl causes MultiVersioning.
   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
NewTVA ? MultiVersionKind::TargetVersion
@@ -11456,7 +11450,8 @@ static bool CheckDeclarationCausesMultiVersioning(Sema 
&S, FunctionDecl *OldFD,
   }
 
   // If this is 'default', permit the forward declaration.
-  if (NewTA && NewTA->isDefaultVersion() && !OldTA) {
+  if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
+  (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
 Redeclaration = true;
 OldDecl = OldFD;
 OldFD->setIsMultiVersion();
@@ -11464,7 +11459,7 @@ static bool CheckDeclarationCausesMultiVersioning(Sema 
&S, F

[clang-tools-extra] [clang-tidy] support parameters file in command line (PR #120547)

2024-12-19 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 created 
https://github.com/llvm/llvm-project/pull/120547

Fixes: #103499


>From 2927ef2ccd286e1efeb12ef12eb5f0fd2dcf2454 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Thu, 19 Dec 2024 15:23:02 +0800
Subject: [PATCH] [clang-tidy] support parameters file in command line

Fixes: #103499
---
 .../clang-tidy/tool/ClangTidyMain.cpp| 16 
 clang-tools-extra/docs/ReleaseNotes.rst  |  2 ++
 .../infrastructure/Inputs/param/parameters.txt   |  2 ++
 .../infrastructure/read-parameters-from-file.cpp |  5 +
 4 files changed, 25 insertions(+)
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/Inputs/param/parameters.txt
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/read-parameters-from-file.cpp

diff --git a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp 
b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
index d42dafa8ffc362..9aebd450e458c1 100644
--- a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -20,12 +20,14 @@
 #include "../GlobList.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "llvm/ADT/StringSet.h"
+#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/PluginLoader.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/WithColor.h"
+#include "llvm/TargetParser/Host.h"
 #include 
 
 using namespace clang::tooling;
@@ -553,6 +555,20 @@ static llvm::IntrusiveRefCntPtr 
createBaseFS() {
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
+  SmallVector Args{argv, argv + argc};
+
+  llvm::BumpPtrAllocator Alloc;
+  llvm::cl::TokenizerCallback Tokenizer =
+  llvm::Triple(llvm::sys::getProcessTriple()).isOSWindows()
+  ? llvm::cl::TokenizeWindowsCommandLine
+  : llvm::cl::TokenizeGNUCommandLine;
+  llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer);
+  if (llvm::Error Err = ECtx.expandResponseFiles(Args)) {
+llvm::WithColor::error() << Err << "\n";
+return 1;
+  }
+  argc = static_cast(Args.size());
+  argv = Args.data();
 
   // Enable help for -load option, if plugins are enabled.
   if (cl::Option *LoadOpt = cl::getRegisteredOptions().lookup("load"))
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 3fd7a4f9da18ad..5999a7134c7528 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -115,6 +115,8 @@ Improvements to clang-tidy
 - Improved :program:`run-clang-tidy.py` script. Fixed minor shutdown noise
   happening on certain platforms when interrupting the script.
 
+- Improved :program:`clang-tidy` by accepting parameters file in command line.
+
 - Removed :program:`clang-tidy`'s global options for most of checks. All 
options
   are changed to local options except `IncludeStyle`, `StrictMode` and
   `IgnoreMacros`.
diff --git 
a/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/param/parameters.txt 
b/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/param/parameters.txt
new file mode 100644
index 00..a6d8fa7ee299fa
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/param/parameters.txt
@@ -0,0 +1,2 @@
+-checks='-*,llvm-namespace-comment'
+--warnings-as-errors=llvm-namespace-comment
diff --git 
a/clang-tools-extra/test/clang-tidy/infrastructure/read-parameters-from-file.cpp
 
b/clang-tools-extra/test/clang-tidy/infrastructure/read-parameters-from-file.cpp
new file mode 100644
index 00..9d8c40a2e7d415
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/infrastructure/read-parameters-from-file.cpp
@@ -0,0 +1,5 @@
+// RUN: not clang-tidy %s @%S/Inputs/param/parameters.txt -- | FileCheck %s
+
+namespace i {
+}
+// CHECK: error: namespace 'i' not terminated with a closing comment 
[llvm-namespace-comment,-warnings-as-errors]

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


[clang-tools-extra] [clang-tidy] support parameters file in command line (PR #120547)

2024-12-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Congcong Cai (HerrCai0907)


Changes

Fixes: #103499


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


4 Files Affected:

- (modified) clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp (+16) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+2) 
- (added) 
clang-tools-extra/test/clang-tidy/infrastructure/Inputs/param/parameters.txt 
(+2) 
- (added) 
clang-tools-extra/test/clang-tidy/infrastructure/read-parameters-from-file.cpp 
(+5) 


``diff
diff --git a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp 
b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
index d42dafa8ffc362..9aebd450e458c1 100644
--- a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -20,12 +20,14 @@
 #include "../GlobList.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "llvm/ADT/StringSet.h"
+#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/PluginLoader.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/WithColor.h"
+#include "llvm/TargetParser/Host.h"
 #include 
 
 using namespace clang::tooling;
@@ -553,6 +555,20 @@ static llvm::IntrusiveRefCntPtr 
createBaseFS() {
 
 int clangTidyMain(int argc, const char **argv) {
   llvm::InitLLVM X(argc, argv);
+  SmallVector Args{argv, argv + argc};
+
+  llvm::BumpPtrAllocator Alloc;
+  llvm::cl::TokenizerCallback Tokenizer =
+  llvm::Triple(llvm::sys::getProcessTriple()).isOSWindows()
+  ? llvm::cl::TokenizeWindowsCommandLine
+  : llvm::cl::TokenizeGNUCommandLine;
+  llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer);
+  if (llvm::Error Err = ECtx.expandResponseFiles(Args)) {
+llvm::WithColor::error() << Err << "\n";
+return 1;
+  }
+  argc = static_cast(Args.size());
+  argv = Args.data();
 
   // Enable help for -load option, if plugins are enabled.
   if (cl::Option *LoadOpt = cl::getRegisteredOptions().lookup("load"))
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 3fd7a4f9da18ad..5999a7134c7528 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -115,6 +115,8 @@ Improvements to clang-tidy
 - Improved :program:`run-clang-tidy.py` script. Fixed minor shutdown noise
   happening on certain platforms when interrupting the script.
 
+- Improved :program:`clang-tidy` by accepting parameters file in command line.
+
 - Removed :program:`clang-tidy`'s global options for most of checks. All 
options
   are changed to local options except `IncludeStyle`, `StrictMode` and
   `IgnoreMacros`.
diff --git 
a/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/param/parameters.txt 
b/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/param/parameters.txt
new file mode 100644
index 00..a6d8fa7ee299fa
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/infrastructure/Inputs/param/parameters.txt
@@ -0,0 +1,2 @@
+-checks='-*,llvm-namespace-comment'
+--warnings-as-errors=llvm-namespace-comment
diff --git 
a/clang-tools-extra/test/clang-tidy/infrastructure/read-parameters-from-file.cpp
 
b/clang-tools-extra/test/clang-tidy/infrastructure/read-parameters-from-file.cpp
new file mode 100644
index 00..9d8c40a2e7d415
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/infrastructure/read-parameters-from-file.cpp
@@ -0,0 +1,5 @@
+// RUN: not clang-tidy %s @%S/Inputs/param/parameters.txt -- | FileCheck %s
+
+namespace i {
+}
+// CHECK: error: namespace 'i' not terminated with a closing comment 
[llvm-namespace-comment,-warnings-as-errors]

``




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


[clang] [analyzer][NFC] Introduce APSIntPtr, a safe wrapper of APSInt (1/4) (PR #120435)

2024-12-19 Thread Arseniy Zaostrovnykh via cfe-commits

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


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


[clang] [clang] Fix dangling false positives for conditional operators. (PR #120233)

2024-12-19 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/120233

>From 1bd4bf164082d236d17ada8240d7ba096a94609d Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Tue, 17 Dec 2024 14:28:00 +0100
Subject: [PATCH] [clang] Fix dangling false positives for conditional
 operators.

---
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/lib/Sema/CheckExprLifetime.cpp  |  9 ++
 .../Sema/warn-lifetime-analysis-nocfg.cpp | 29 +++
 3 files changed, 40 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5f91ff90634036..9128a8e2ec40f2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -700,6 +700,8 @@ Improvements to Clang's diagnostics
   return ptr + index < ptr; // warning
 }
 
+- Fix -Wdangling false positives on conditional operators (#120206).
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index add6d7506bd6f0..7109de03cadd12 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -582,6 +582,15 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 //   Temp().ptr; // Here ptr might not dangle.
 if (isa(Arg->IgnoreImpCasts()))
   return;
+// Avoid false positives when the object is constructed from a conditional
+// operator argument. A common case is:
+//   // 'ptr' might not be owned by the Owner object.
+//   std::string_view s = cond() ? Owner().ptr : sv;
+if (const auto *Cond =
+dyn_cast(Arg->IgnoreImpCasts());
+Cond && isPointerLikeType(Cond->getType()))
+  return;
+
 auto ReturnType = Callee->getReturnType();
 
 // Once we initialized a value with a non gsl-owner reference, it can no
diff --git a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp 
b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
index 45b4dc838f44ed..4c19367bb7f3dd 100644
--- a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -777,3 +777,32 @@ void test4() {
 }
 
 } // namespace LifetimeboundInterleave
+
+namespace GH120206 {
+struct S {
+  std::string_view s;
+};
+
+struct [[gsl::Owner]] Q1 {
+  const S* get() const [[clang::lifetimebound]];
+};
+std::string_view test1(int c, std::string_view sv) {
+  std::string_view k = c > 1 ? Q1().get()->s : sv;
+  if (c == 1)
+return  c > 1 ? Q1().get()->s : sv;
+  Q1 q;
+  return c > 1 ? q.get()->s : sv;
+}
+
+struct Q2 {
+  const S* get() const [[clang::lifetimebound]];
+};
+std::string_view test2(int c, std::string_view sv) {
+  std::string_view k = c > 1 ? Q2().get()->s : sv;
+  if (c == 1)
+return c > 1 ? Q2().get()->s : sv;
+  Q2 q;
+  return c > 1 ? q.get()->s : sv;
+}
+
+} // namespace GH120206

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


[clang-tools-extra] [clang-tidy] support parameters file in command line (PR #120547)

2024-12-19 Thread Piotr Zegar via cfe-commits

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


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


[clang] [CIR] floating-point, pointer, and function types (PR #120484)

2024-12-19 Thread David Olsen via cfe-commits


@@ -18,6 +21,87 @@ mlir::MLIRContext &CIRGenTypes::getMLIRContext() const {
   return *builder.getContext();
 }
 
+/// Return true if the specified type in a function parameter or result 
position
+/// can be converted to a CIR type at this point. This boils down to being
+/// whether it is complete, as well as whether we've temporarily deferred
+/// expanding the type because we're in a recursive context.
+bool CIRGenTypes::isFuncParamTypeConvertible(clang::QualType type) {
+  // Some ABIs cannot have their member pointers represented in LLVM IR unless
+  // certain circumstances have been reached.
+  assert(!type->getAs() && "NYI");
+
+  // If this isn't a tagged type, we can convert it!

dkolsen-pgi wrote:

> rather than returning a value we wouldn't be sure of.

That wouldn't be the case.  The ClangIR incubator project already implements 
type conversions for virtually all types.  It is known that incomplete tag 
types are the only ones that are problematic in this context.  We already know 
that all non-tag types are fine.

This function is making assumptions based on code that is in the incubator 
project but hasn't been upstreamed yet.  I am trying to minimize that, of 
course.  But eliminating those assumptions entirely would slow down the 
upstreaming work even more, for no tangible benefit for the end result.


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


[clang] [libclang/python] Add a few things to the python api (PR #120590)

2024-12-19 Thread Jannick Kremer via cfe-commits

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


[clang] [libclang/python] Add a few things to the python api (PR #120590)

2024-12-19 Thread Jannick Kremer via cfe-commits

https://github.com/DeinAlptraum commented:

Hi and thanks for the PR!

To keep our history readable, please this up into smaller more focused PRs with 
an appropriate title ("Add a few things" won't be accepted ;)). This could be 
split into e.g. additions to the `File` interface, additions to the `Cursor` 
interface, and then type annotation(s).

If you add interfaces, please also add tests for them. `has_attrs` is also 
missing a doc string.

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


[clang] [Darwin][Driver][clang] apple-none-macho orders the resource directory after internal-externc-isystem when nostdlibinc is used (PR #120507)

2024-12-19 Thread Jon Roelofs via cfe-commits


@@ -2631,55 +2643,65 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
   }
 
   case ToolChain::CST_Libstdcxx:
-llvm::SmallString<128> UsrIncludeCxx = Sysroot;
-llvm::sys::path::append(UsrIncludeCxx, "usr", "include", "c++");
-
-llvm::Triple::ArchType arch = getTriple().getArch();
-bool IsBaseFound = true;
-switch (arch) {
-default: break;
-
-case llvm::Triple::x86:
-case llvm::Triple::x86_64:
-  IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, 
UsrIncludeCxx,
-"4.2.1",
-"i686-apple-darwin10",
-arch == llvm::Triple::x86_64 ? 
"x86_64" : "");
-  IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, 
UsrIncludeCxx,
-"4.0.0", "i686-apple-darwin8",
- "");
-  break;
+AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args);
+break;
+  }
+}
 
-case llvm::Triple::arm:
-case llvm::Triple::thumb:
-  IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, 
UsrIncludeCxx,
-"4.2.1",
-"arm-apple-darwin10",
-"v7");
-  IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, 
UsrIncludeCxx,
-"4.2.1",
-"arm-apple-darwin10",
- "v6");
-  break;
+void MachO::AddGnuCPlusPlusIncludePaths(
+const llvm::opt::ArgList &DriverArgs,
+llvm::opt::ArgStringList &CC1Args) const {}
 
-case llvm::Triple::aarch64:
-  IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, 
UsrIncludeCxx,
-"4.2.1",
-"arm64-apple-darwin10",
-"");
-  break;
-}
+void DarwinClang::AddGnuCPlusPlusIncludePaths(
+const llvm::opt::ArgList &DriverArgs,
+llvm::opt::ArgStringList &CC1Args) const {
+  llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
 
-if (!IsBaseFound) {
-  getDriver().Diag(diag::warn_drv_libstdcxx_not_found);
-}
+  llvm::SmallString<128> UsrIncludeCxx = Sysroot;

jroelofs wrote:

`Sysroot` isn't used after this point, but I'm not sure if llvm will coalesce 
the two stack objects for these two `SmallString`s. Maybe this ought to be:

```
llvm::SmallString<128> UserIncludeCxx = GetEffectiveSysroot(DriverArgs);
```

and drop the other one, to be sure we don't use loads of extra stack when 
computing this.

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


[clang] [libclang/python] Add a few things to the python api (PR #120590)

2024-12-19 Thread via cfe-commits

github-actions[bot] wrote:




:warning: Python code formatter, darker found issues in your code. :warning:



You can test this locally with the following command:


``bash
darker --check --diff -r 
6f8afafd308d37d9abc4af0801dd5a4451c13718...1c68440616b555c376a3c227338f23ca80a2c777
 clang/bindings/python/clang/cindex.py
``





View the diff from darker here.


``diff
--- cindex.py   2024-12-19 15:22:04.00 +
+++ cindex.py   2024-12-19 16:32:57.052528 +
@@ -2027,12 +2027,11 @@
 
 @property
 def specialized_template(self):
 """Return the base template that this cursor is a specialization of, 
if any."""
 return Cursor.from_cursor_result(
-conf.lib.clang_getSpecializedCursorTemplate(self),
-self
+conf.lib.clang_getSpecializedCursorTemplate(self), self
 )
 
 @property
 def translation_unit(self):
 """Returns the TranslationUnit to which this Cursor belongs."""
@@ -3414,11 +3413,13 @@
 
 def __repr__(self):
 return "" % (self.name)
 
 def __eq__(self, other):
-return isinstance(other, File) and 
bool(conf.lib.clang_File_isEqual(self, other))
+return isinstance(other, File) and bool(
+conf.lib.clang_File_isEqual(self, other)
+)
 
 def __ne__(self, other):
 return not self.__eq__(other)
 
 @staticmethod

``




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


[clang] [Darwin][Driver][clang] apple-none-macho orders the resource directory after internal-externc-isystem when nostdlibinc is used (PR #120507)

2024-12-19 Thread Jon Roelofs via cfe-commits


@@ -0,0 +1,55 @@
+// UNSUPPORTED: system-windows
+//   Windows is unsupported because we use the Unix path separator `/` in the 
test.
+
+// Add default directories before running clang to check default
+// search paths.
+// RUN: rm -rf %t && mkdir -p %t
+// RUN: cp -R %S/Inputs/MacOSX15.1.sdk %t/
+// RUN: mkdir -p %t/MacOSX15.1.sdk/usr/include
+// RUN: mkdir -p %t/MacOSX15.1.sdk/usr/include/c++/v1
+// RUN: mkdir -p %t/MacOSX15.1.sdk/usr/local/include
+// RUN: mkdir -p %t/MacOSX15.1.sdk/embedded/usr/include
+// RUN: mkdir -p %t/MacOSX15.1.sdk/embedded/usr/local/include

jroelofs wrote:

The "usual" pattern for this is to put `.keep` files in a folder structure in 
e.g. 
`clang/test/Driver/Inputs/darwin-embedded-search-paths/MacOSX15.1.sdk/...`, 
instead of creating them dynamically.

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


[clang] [CIR] floating-point, pointer, and function types (PR #120484)

2024-12-19 Thread Erich Keane via cfe-commits


@@ -18,6 +21,87 @@ mlir::MLIRContext &CIRGenTypes::getMLIRContext() const {
   return *builder.getContext();
 }
 
+/// Return true if the specified type in a function parameter or result 
position
+/// can be converted to a CIR type at this point. This boils down to being
+/// whether it is complete, as well as whether we've temporarily deferred
+/// expanding the type because we're in a recursive context.
+bool CIRGenTypes::isFuncParamTypeConvertible(clang::QualType type) {
+  // Some ABIs cannot have their member pointers represented in LLVM IR unless
+  // certain circumstances have been reached.
+  assert(!type->getAs() && "NYI");
+
+  // If this isn't a tagged type, we can convert it!

erichkeane wrote:

>It is known that incomplete tag types are the only ones that are problematic 
>in this context.

This seems inaccurate to me.  CIR doesn't seem to be able to represent(see 
here: 
https://github.com/llvm/clangir/blob/main/clang/include/clang/CIR/Dialect/IR/CIRTypes.td)
  Atomic Types, BitInt types, Block types, and Matrix types upon quick look 
(that is perhaps an incomplete list).  

The function was written across; 
https://github.com/llvm/clangir/commit/101e732565d0e5004c5191b0053eebd8e849cade
and 
https://github.com/llvm/clangir/commit/93f55f6d43be394250009013c83d343be7c63f41

Neither of which mention those types specifically?  It seems it USED to have an 
assert for not-tag-type, though it isn't clear that the authors considered the 
above types.

Can @lanza and @bcardosolopes chime in and let me know if I'm misinterpreting 
the commits there?



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


[clang] [Clang][AArch64] Add signed index/offset variants of sve2p1 qword stores (PR #120549)

2024-12-19 Thread via cfe-commits

https://github.com/SpencerAbson created 
https://github.com/llvm/llvm-project/pull/120549

This patch adds signed offset/index variants to the SVE2p1 quadword store 
intrinsics, in accordance with https://github.com/ARM-software/acle/pull/359.

>From f1969c173dcefd23a2384f4e6d63f7f7804c1c45 Mon Sep 17 00:00:00 2001
From: Spencer Abson 
Date: Mon, 16 Dec 2024 16:16:42 +
Subject: [PATCH] [Clang][AArch64] Add signed index/offset variants of sve2p1
 quadword stores

---
 clang/include/clang/Basic/arm_sve.td  |   4 +-
 clang/include/clang/Basic/arm_sve_sme_incl.td |   1 +
 .../sve2p1-intrinsics/acle_sve2p1_store.c | 352 ++
 clang/utils/TableGen/SveEmitter.cpp   |   4 +
 4 files changed, 360 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index e9396e34adad8f..ca295356985bac 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -474,7 +474,8 @@ let SVETargetGuard = "sve2p1", SMETargetGuard = InvalidMode 
in {
   def SVST1Q_SCATTER_U64BASE : MInst<"svst1q_scatter[_{2}base][_{d}]",  
"vPgd", "cUcsUsiUilUlfhdb", [IsScatterStore, IsByteIndexed], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_scalar_offset">;
 
   // Store one vector (scalar base + vector offset)
-  def SVST1Q_SCATTER_U64OFFSET : MInst<"svst1q_scatter_[{3}]offset[_{d}]", 
"vPpgd", "cUcsUsiUilUlfhdb", [IsScatterStore, IsByteIndexed], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_vector_offset">;
+  def SVST1Q_SCATTER_OFFSETS_U : MInst<"svst1q_scatter_[{3}]offset[_{d}]", 
"vPpgd", "cUcsUsiUilUlfhdb", [IsScatterStore, IsByteIndexed], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_vector_offset">;
+  def SVST1Q_SCATTER_OFFSETS_S : MInst<"svst1q_scatter_[{3}]offset[_{d}]", 
"vPp#d", "cUcsUsiUilUlfhdb", [IsScatterStore, IsByteIndexed], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_vector_offset">;
 
   // Store N vectors into N-element structure (scalar base)
   defm SVST2Q : StructStore<"svst2q[_{d}]", "vPc2", "aarch64_sve_st2q">;
@@ -488,6 +489,7 @@ let SVETargetGuard = "sve2p1", SMETargetGuard = InvalidMode 
in {
 
   // Scatter store quadwords (scalar base + vector index)
   def SVST1Q_SCATTER_INDICES_U : MInst<"svst1q_scatter_[{3}]index[_{d}]", 
"vPpgd", "sUsiUilUlbhfd", [IsScatterStore], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_index">;
+  def SVST1Q_SCATTER_INDICES_S : MInst<"svst1q_scatter_[{3}]index[_{d}]", 
"vPp#d", "sUsiUilUlbhfd", [IsScatterStore], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_index">;
 
   // Scatter store quadwords (vector base + scalar index)
   def SVST1Q_SCATTER_INDEX_S   : MInst<"svst1q_scatter[_{2}base]_index[_{d}]", 
"vPgld", "sUsiUilUlbhfd", [IsScatterStore], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_scalar_offset">;
diff --git a/clang/include/clang/Basic/arm_sve_sme_incl.td 
b/clang/include/clang/Basic/arm_sve_sme_incl.td
index ee899209ad832b..6ba0d49d303d75 100644
--- a/clang/include/clang/Basic/arm_sve_sme_incl.td
+++ b/clang/include/clang/Basic/arm_sve_sme_incl.td
@@ -101,6 +101,7 @@ include "arm_immcheck_incl.td"
 // [: svuint8_t
 // t: svint32_t
 // z: svuint32_t
+// #: svint64_t
 // g: svuint64_t
 // O: svfloat16_t
 // M: svfloat32_t
diff --git a/clang/test/CodeGen/AArch64/sve2p1-intrinsics/acle_sve2p1_store.c 
b/clang/test/CodeGen/AArch64/sve2p1-intrinsics/acle_sve2p1_store.c
index 657787e851ee20..b91780304dacbd 100644
--- a/clang/test/CodeGen/AArch64/sve2p1-intrinsics/acle_sve2p1_store.c
+++ b/clang/test/CodeGen/AArch64/sve2p1-intrinsics/acle_sve2p1_store.c
@@ -1931,6 +1931,22 @@ void test_svst1q_scatter_u64index_s16(svbool_t pg, 
int16_t *base, svuint64_t idx
   SVE_ACLE_FUNC(svst1q_scatter_, u64, index, _s16)(pg, base, idx, data);
 }
 
+// CHECK-LABEL: @test_svst1q_scatter_s64index_s16(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.aarch64.sve.convert.from.svbool.nxv1i1( [[PG:%.*]])
+// CHECK-NEXT:tail call void 
@llvm.aarch64.sve.st1q.scatter.index.nxv8i16( [[DATA:%.*]], 
 [[TMP0]], ptr [[BASE:%.*]],  [[IDX:%.*]])
+// CHECK-NEXT:ret void
+//
+// CPP-CHECK-LABEL: 
@_Z32test_svst1q_scatter_s64index_s16u10__SVBool_tPsu11__SVInt64_tu11__SVInt16_t(
+// CPP-CHECK-NEXT:  entry:
+// CPP-CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.aarch64.sve.convert.from.svbool.nxv1i1( [[PG:%.*]])
+// CPP-CHECK-NEXT:tail call void 
@llvm.aarch64.sve.st1q.scatter.index.nxv8i16( [[DATA:%.*]], 
 [[TMP0]], ptr [[BASE:%.*]],  [[IDX:%.*]])
+// CPP-CHECK-NEXT:ret void
+//
+void test_svst1q_scatter_s64index_s16(svbool_t pg, int16_t *base, svint64_t 
idx, svint16_t data) {
+  SVE_ACLE_FUNC(svst1q_scatter_, s64, index, _s16)(pg, base, idx, data);
+}
+
 // CHECK-LABEL: @test_svst1q_scatter_u64index_u16(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.aarch64.sve.convert.from.svbool.nxv1i1( [[PG:%.*]])
@@ -1947,6 +1963,22 @@ void test_svst1q_scatter_u64index_u16(svbool_t pg, 
uint16_t *base, svuint64_t id
   SVE_ACLE_FUNC

[clang] [Clang][AArch64] Add signed index/offset variants of sve2p1 qword stores (PR #120549)

2024-12-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (SpencerAbson)


Changes

This patch adds signed offset/index variants to the SVE2p1 quadword store 
intrinsics, in accordance with https://github.com/ARM-software/acle/pull/359.

---

Patch is 35.89 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/120549.diff


4 Files Affected:

- (modified) clang/include/clang/Basic/arm_sve.td (+3-1) 
- (modified) clang/include/clang/Basic/arm_sve_sme_incl.td (+1) 
- (modified) clang/test/CodeGen/AArch64/sve2p1-intrinsics/acle_sve2p1_store.c 
(+352) 
- (modified) clang/utils/TableGen/SveEmitter.cpp (+4) 


``diff
diff --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index e9396e34adad8f..ca295356985bac 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -474,7 +474,8 @@ let SVETargetGuard = "sve2p1", SMETargetGuard = InvalidMode 
in {
   def SVST1Q_SCATTER_U64BASE : MInst<"svst1q_scatter[_{2}base][_{d}]",  
"vPgd", "cUcsUsiUilUlfhdb", [IsScatterStore, IsByteIndexed], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_scalar_offset">;
 
   // Store one vector (scalar base + vector offset)
-  def SVST1Q_SCATTER_U64OFFSET : MInst<"svst1q_scatter_[{3}]offset[_{d}]", 
"vPpgd", "cUcsUsiUilUlfhdb", [IsScatterStore, IsByteIndexed], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_vector_offset">;
+  def SVST1Q_SCATTER_OFFSETS_U : MInst<"svst1q_scatter_[{3}]offset[_{d}]", 
"vPpgd", "cUcsUsiUilUlfhdb", [IsScatterStore, IsByteIndexed], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_vector_offset">;
+  def SVST1Q_SCATTER_OFFSETS_S : MInst<"svst1q_scatter_[{3}]offset[_{d}]", 
"vPp#d", "cUcsUsiUilUlfhdb", [IsScatterStore, IsByteIndexed], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_vector_offset">;
 
   // Store N vectors into N-element structure (scalar base)
   defm SVST2Q : StructStore<"svst2q[_{d}]", "vPc2", "aarch64_sve_st2q">;
@@ -488,6 +489,7 @@ let SVETargetGuard = "sve2p1", SMETargetGuard = InvalidMode 
in {
 
   // Scatter store quadwords (scalar base + vector index)
   def SVST1Q_SCATTER_INDICES_U : MInst<"svst1q_scatter_[{3}]index[_{d}]", 
"vPpgd", "sUsiUilUlbhfd", [IsScatterStore], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_index">;
+  def SVST1Q_SCATTER_INDICES_S : MInst<"svst1q_scatter_[{3}]index[_{d}]", 
"vPp#d", "sUsiUilUlbhfd", [IsScatterStore], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_index">;
 
   // Scatter store quadwords (vector base + scalar index)
   def SVST1Q_SCATTER_INDEX_S   : MInst<"svst1q_scatter[_{2}base]_index[_{d}]", 
"vPgld", "sUsiUilUlbhfd", [IsScatterStore], MemEltTyDefault, 
"aarch64_sve_st1q_scatter_scalar_offset">;
diff --git a/clang/include/clang/Basic/arm_sve_sme_incl.td 
b/clang/include/clang/Basic/arm_sve_sme_incl.td
index ee899209ad832b..6ba0d49d303d75 100644
--- a/clang/include/clang/Basic/arm_sve_sme_incl.td
+++ b/clang/include/clang/Basic/arm_sve_sme_incl.td
@@ -101,6 +101,7 @@ include "arm_immcheck_incl.td"
 // [: svuint8_t
 // t: svint32_t
 // z: svuint32_t
+// #: svint64_t
 // g: svuint64_t
 // O: svfloat16_t
 // M: svfloat32_t
diff --git a/clang/test/CodeGen/AArch64/sve2p1-intrinsics/acle_sve2p1_store.c 
b/clang/test/CodeGen/AArch64/sve2p1-intrinsics/acle_sve2p1_store.c
index 657787e851ee20..b91780304dacbd 100644
--- a/clang/test/CodeGen/AArch64/sve2p1-intrinsics/acle_sve2p1_store.c
+++ b/clang/test/CodeGen/AArch64/sve2p1-intrinsics/acle_sve2p1_store.c
@@ -1931,6 +1931,22 @@ void test_svst1q_scatter_u64index_s16(svbool_t pg, 
int16_t *base, svuint64_t idx
   SVE_ACLE_FUNC(svst1q_scatter_, u64, index, _s16)(pg, base, idx, data);
 }
 
+// CHECK-LABEL: @test_svst1q_scatter_s64index_s16(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.aarch64.sve.convert.from.svbool.nxv1i1( [[PG:%.*]])
+// CHECK-NEXT:tail call void 
@llvm.aarch64.sve.st1q.scatter.index.nxv8i16( [[DATA:%.*]], 
 [[TMP0]], ptr [[BASE:%.*]],  [[IDX:%.*]])
+// CHECK-NEXT:ret void
+//
+// CPP-CHECK-LABEL: 
@_Z32test_svst1q_scatter_s64index_s16u10__SVBool_tPsu11__SVInt64_tu11__SVInt16_t(
+// CPP-CHECK-NEXT:  entry:
+// CPP-CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.aarch64.sve.convert.from.svbool.nxv1i1( [[PG:%.*]])
+// CPP-CHECK-NEXT:tail call void 
@llvm.aarch64.sve.st1q.scatter.index.nxv8i16( [[DATA:%.*]], 
 [[TMP0]], ptr [[BASE:%.*]],  [[IDX:%.*]])
+// CPP-CHECK-NEXT:ret void
+//
+void test_svst1q_scatter_s64index_s16(svbool_t pg, int16_t *base, svint64_t 
idx, svint16_t data) {
+  SVE_ACLE_FUNC(svst1q_scatter_, s64, index, _s16)(pg, base, idx, data);
+}
+
 // CHECK-LABEL: @test_svst1q_scatter_u64index_u16(
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.aarch64.sve.convert.from.svbool.nxv1i1( [[PG:%.*]])
@@ -1947,6 +1963,22 @@ void test_svst1q_scatter_u64index_u16(svbool_t pg, 
uint16_t *base, svuint64_t id
   SVE_ACLE_FUNC(svst1q_scatter_, u64, index, _u16)(pg, base, idx, data);
 }
 
+// CHECK-LABEL: @test_svst1q_scatt

[clang] b41240b - [analyzer][NFC] Introduce APSIntPtr, a safe wrapper of APSInt (1/4) (#120435)

2024-12-19 Thread via cfe-commits

Author: Balazs Benics
Date: 2024-12-19T12:04:04+01:00
New Revision: b41240be6b9e58687011b2bd1b942c6625cbb5ad

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

LOG: [analyzer][NFC] Introduce APSIntPtr, a safe wrapper of APSInt (1/4) 
(#120435)

One could create dangling APSInt references in various ways in the past, that 
were sometimes assumed to be persisted in the BasicValueFactor.

One should always use BasicValueFactory to create persistent APSInts, that 
could be used by ConcreteInts or SymIntExprs and similar long-living objects.
If one used a temporary or local variables for this, these would dangle.
To enforce the contract of the analyzer BasicValueFactory and the uses of 
APSInts, let's have a dedicated strong-type for this.

The idea is that APSIntPtr is always owned by the BasicValueFactory, and that 
is the only component that can construct it.

These PRs are all NFC - besides fixing dangling APSInt references.

Added: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntPtr.h

Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h
clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntPtr.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntPtr.h
new file mode 100644
index 00..84a6bf1406ac6c
--- /dev/null
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntPtr.h
@@ -0,0 +1,64 @@
+//== APSIntPtr.h - Wrapper for APSInt objects owned separately -*- 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
+//
+//===--===//
+
+#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_APSIntPtr_H
+#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_APSIntPtr_H
+
+#include "llvm/ADT/APSInt.h"
+#include "llvm/Support/Compiler.h"
+
+namespace clang::ento {
+
+/// A safe wrapper around APSInt objects allocated and owned by
+/// \c BasicValueFactory. This just wraps a common llvm::APSInt.
+class APSIntPtr {
+  using APSInt = llvm::APSInt;
+
+public:
+  APSIntPtr() = delete;
+  APSIntPtr(const APSIntPtr &) = default;
+  APSIntPtr &operator=(const APSIntPtr &) & = default;
+  ~APSIntPtr() = default;
+
+  /// You should not use this API.
+  /// If do, ensure that the \p Ptr not going to dangle.
+  /// Prefer using \c BasicValueFactory::getValue() to get an APSIntPtr object.
+  static APSIntPtr unsafeConstructor(const APSInt *Ptr) {
+return APSIntPtr(Ptr);
+  }
+
+  LLVM_ATTRIBUTE_RETURNS_NONNULL
+  const APSInt *get() const { return Ptr; }
+  /*implicit*/ operator const APSInt &() const { return *get(); }
+
+  APSInt operator-() const { return -*Ptr; }
+  APSInt operator~() const { return ~*Ptr; }
+
+#define DEFINE_OPERATOR(OP)
\
+  bool operator OP(APSIntPtr Other) const { return (*Ptr)OP(*Other.Ptr); }
+  DEFINE_OPERATOR(>)
+  DEFINE_OPERATOR(>=)
+  DEFINE_OPERATOR(<)
+  DEFINE_OPERATOR(<=)
+  DEFINE_OPERATOR(==)
+  DEFINE_OPERATOR(!=)
+#undef DEFINE_OPERATOR
+
+  const APSInt &operator*() const { return *Ptr; }
+  const APSInt *operator->() const { return Ptr; }
+
+private:
+  explicit APSIntPtr(const APSInt *Ptr) : Ptr(Ptr) {}
+
+  /// Owned by \c BasicValueFactory.
+  const APSInt *Ptr;
+};
+
+} // namespace clang::ento
+
+#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_APSIntPtr_H

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
index ec503b41b381a5..ef04f9c485e88a 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
@@ -18,10 +18,11 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/Type.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/APSIntPtr.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
 #include "clang/StaticAnalyzer/Cor

[clang] [analyzer][NFC] Introduce APSIntPtr, a safe wrapper of APSInt (1/4) (PR #120435)

2024-12-19 Thread Balazs Benics via cfe-commits

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


[clang] [analyzer][NFC] Migrate nonloc::ConcreteInt to use APSIntPtr (2/4) (PR #120436)

2024-12-19 Thread Balazs Benics via cfe-commits

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


[clang] [analyzer][NFC] Migrate nonloc::ConcreteInt to use APSIntPtr (2/4) (PR #120436)

2024-12-19 Thread Balazs Benics via cfe-commits

https://github.com/steakhal updated 
https://github.com/llvm/llvm-project/pull/120436

>From 75579cb057f440a70352b6ed6cc99529cbb933e7 Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Wed, 18 Dec 2024 15:55:27 +0100
Subject: [PATCH] [analyzer][NFC] Migrate nonloc::ConcreteInt to use APSIntPtr
 (2/4)

---
 .../Core/PathSensitive/MemRegion.h|  2 +-
 .../StaticAnalyzer/Core/PathSensitive/SVals.h |  8 +++--
 .../Checkers/ArrayBoundCheckerV2.cpp  | 14 -
 .../Checkers/BasicObjCFoundationChecks.cpp|  2 +-
 .../Checkers/BitwiseShiftChecker.cpp  |  8 ++---
 .../Checkers/BuiltinFunctionChecker.cpp   |  8 +++--
 .../Checkers/CheckPlacementNew.cpp|  2 +-
 .../lib/StaticAnalyzer/Checkers/Iterator.cpp  | 14 -
 .../Checkers/IteratorModeling.cpp |  4 +--
 .../Checkers/MmapWriteExecChecker.cpp |  2 +-
 .../StaticAnalyzer/Checkers/StreamChecker.cpp |  2 +-
 .../Core/BugReporterVisitors.cpp  |  2 +-
 clang/lib/StaticAnalyzer/Core/MemRegion.cpp   |  8 ++---
 .../lib/StaticAnalyzer/Core/ProgramState.cpp  |  6 ++--
 clang/lib/StaticAnalyzer/Core/SValBuilder.cpp |  2 +-
 clang/lib/StaticAnalyzer/Core/SVals.cpp   | 10 +++
 .../Core/SimpleConstraintManager.cpp  |  2 +-
 .../StaticAnalyzer/Core/SimpleSValBuilder.cpp | 30 ++-
 18 files changed, 65 insertions(+), 61 deletions(-)

diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
index 0d9566285f5d4e..f88bf70d72398c 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
@@ -1206,7 +1206,7 @@ class ElementRegion : public TypedValueRegion {
   : TypedValueRegion(sReg, ElementRegionKind), ElementType(elementType),
 Index(Idx) {
 assert((!isa(Idx) ||
-Idx.castAs().getValue().isSigned()) &&
+Idx.castAs().getValue()->isSigned()) &&
"The index must be signed");
 assert(!elementType.isNull() && !elementType->isVoidType() &&
"Invalid region type!");
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
index a054a819a15a85..57d7514280f10f 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
@@ -17,6 +17,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/LLVM.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/APSIntPtr.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
 #include "llvm/ADT/APSInt.h"
 #include "llvm/ADT/FoldingSet.h"
@@ -298,9 +299,12 @@ class SymbolVal : public NonLoc {
 /// Value representing integer constant.
 class ConcreteInt : public NonLoc {
 public:
-  explicit ConcreteInt(const llvm::APSInt &V) : NonLoc(ConcreteIntKind, &V) {}
+  explicit ConcreteInt(APSIntPtr V) : NonLoc(ConcreteIntKind, V.get()) {}
 
-  const llvm::APSInt &getValue() const { return *castDataAs(); }
+  APSIntPtr getValue() const {
+// This is safe because in the ctor we take a safe APSIntPtr.
+return APSIntPtr::unsafeConstructor(castDataAs());
+  }
 
   static bool classof(SVal V) { return V.getKind() == ConcreteIntKind; }
 };
diff --git a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
index 3f837564cf47c4..6422933c8828a9 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -22,6 +22,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
+#include "llvm/ADT/APSInt.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/raw_ostream.h"
@@ -241,26 +242,25 @@ computeOffset(ProgramStateRef State, SValBuilder &SVB, 
SVal Location) {
 static std::pair
 getSimplifiedOffsets(NonLoc offset, nonloc::ConcreteInt extent,
  SValBuilder &svalBuilder) {
+  const llvm::APSInt &extentVal = extent.getValue();
   std::optional SymVal = offset.getAs();
   if (SymVal && SymVal->isExpression()) {
 if (const SymIntExpr *SIE = dyn_cast(SymVal->getSymbol())) {
-  llvm::APSInt constant =
-  APSIntType(extent.getValue()).convert(SIE->getRHS());
+  llvm::APSInt constant = APSIntType(extentVal).convert(SIE->getRHS());
   switch (SIE->getOpcode()) {
   case BO_Mul:
 // The constant should never be 0 here, becasue multiplication by zero
 // is simplified by the engine.
-if ((extent.getValue() % constant) != 0)
+if ((extentVal % constant) != 0)
   return std::pair(offset, extent);
 

[clang] [Clang][AArch64] Remove const from base pointers in sve2p1 stores (PR #120551)

2024-12-19 Thread Momchil Velikov via cfe-commits

https://github.com/momchil-velikov approved this pull request.


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


[clang] [Clang][AArch64] Add signed index/offset variants of sve2p1 qword stores (PR #120549)

2024-12-19 Thread Momchil Velikov via cfe-commits

https://github.com/momchil-velikov approved this pull request.


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


[clang-tools-extra] [clang-tidy] Sync ContainerSizeEmptyCheck with container-size-empty doc (PR #118459)

2024-12-19 Thread Niels Dekker via cfe-commits

N-Dekker wrote:

@HerrCai0907 Thanks again for your approval, _and_ for merging my very first 
LLVM PR (#117629). Can you please 🙏 merge this one as well?

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


[clang-tools-extra] [clangd] Allow specifying what headers are always included via "" or <> (PR #67749)

2024-12-19 Thread Travis Downs via cfe-commits

travisdowns wrote:

@kleinesfilmroellchen or @ADKaster it's been quiet for a while, do you think 
there's any hope for this one still, or is this PR abandoned? Great work to 
date, BTW, this would be a big win for a project I work on as well (which 
unconditionally uses <> for internal headers).

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


[clang] [compiler-rt] Move interceptors for libresolv functions to MSan (PR #119071)

2024-12-19 Thread Aaron Puchert via cfe-commits

aaronpuchert wrote:

That configuration output is from `compiler-rt`, but we need it in `llvm`. In 
`llvm/lib/ExecutionEngine/Orc/CMakeLists.txt`:
```cmake
if( CMAKE_HOST_UNIX AND HAVE_LIBRT )
  set(rt_lib rt)
endif()
```
We have `CMAKE_HOST_UNIX` = 1, but `HAVE_LIBRT` is empty. It comes from 
`check_library_exists(rt clock_gettime "" HAVE_LIBRT)` in 
`llvm/cmake/config-ix.cmake`. The corresponding output:
```
-- Looking for clock_gettime in rt
-- Looking for clock_gettime in rt - not found
```
This looks correct to me:
```
> readelf --dyn-syms --wide 
> /home/aaron/chrome-sysroot/usr/lib/x86_64-linux-gnu/librt.so | grep 
> clock_gettime
38:  0 FUNCGLOBAL DEFAULT  UND 
__clock_gettime@GLIBC_PRIVATE (7)
```
Instead it's in `libc.so.6`:
```
> readelf --dyn-syms --wide 
> /home/aaron/chrome-sysroot/lib/x86_64-linux-gnu/libc.so.6 | grep clock_gettime
   840: 000c3420   111 FUNCGLOBAL DEFAULT   13 
__clock_gettime@@GLIBC_PRIVATE
  1748: 000c3420   111 FUNCGLOBAL DEFAULT   13 
clock_gettime@GLIBC_2.2.5
  1751: 000c3420   111 FUNCGLOBAL DEFAULT   13 
clock_gettime@@GLIBC_2.17
```
On my system that's not an issue because `libc.so` has both `clock_gettime` and 
`shm_open`, so `librt.so` is never needed. Do you have any additional patches 
or why does this work for you?

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


[clang] [Darwin][Driver][clang] apple-none-macho orders the resource directory after internal-externc-isystem when nostdlibinc is used (PR #120507)

2024-12-19 Thread Jon Roelofs via cfe-commits


@@ -0,0 +1,55 @@
+// UNSUPPORTED: system-windows
+//   Windows is unsupported because we use the Unix path separator `/` in the 
test.
+

jroelofs wrote:

As written, this requires an `aarch64-registered-target`. I think you can avoid 
that though by turning these into `-###` style tests, and checking the include 
paths passed from the driver to cc1, instead of checking the user-facing 
diagnostics that `-v` dumps to stderr.

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


[clang] [Darwin][Driver][clang] apple-none-macho orders the resource directory after internal-externc-isystem when nostdlibinc is used (PR #120507)

2024-12-19 Thread Jon Roelofs via cfe-commits


@@ -0,0 +1,55 @@
+// UNSUPPORTED: system-windows
+//   Windows is unsupported because we use the Unix path separator `/` in the 
test.
+
+// Add default directories before running clang to check default
+// search paths.
+// RUN: rm -rf %t && mkdir -p %t
+// RUN: cp -R %S/Inputs/MacOSX15.1.sdk %t/
+// RUN: mkdir -p %t/MacOSX15.1.sdk/usr/include
+// RUN: mkdir -p %t/MacOSX15.1.sdk/usr/include/c++/v1
+// RUN: mkdir -p %t/MacOSX15.1.sdk/usr/local/include
+// RUN: mkdir -p %t/MacOSX15.1.sdk/embedded/usr/include
+// RUN: mkdir -p %t/MacOSX15.1.sdk/embedded/usr/local/include
+
+// Unlike the Darwin driver, the MachO driver doesn't add any framework search 
paths,
+// only the normal header ones.
+// RUN: %clang -xc %s -target arm64-apple-none-macho -isysroot 
%t/MacOSX15.1.sdk -E -v 2>&1 | FileCheck --check-prefix=CHECK-C %s
+//
+// CHECK-C: -isysroot [[SDKROOT:[^ ]*/MacOSX15.1.sdk]]
+// CHECK-C: #include <...> search starts here:
+// CHECK-C-NEXT:[[SDKROOT]]/usr/local/include
+// CHECK-C-NEXT:/clang/{{.*}}/include
+// CHECK-C-NEXT:[[SDKROOT]]/usr/include
+
+// Unlike the Darwin driver, the MachO driver doesn't default to libc++
+// RUN: %clang -xc++ %s -target arm64-apple-none-macho -isysroot 
%t/MacOSX15.1.sdk -E -v 2>&1 | FileCheck --check-prefix=CHECK-CXX %s
+//
+// CHECK-CXX:   -isysroot [[SDKROOT:[^ ]*/MacOSX15.1.sdk]]
+// CHECK-CXX:   #include <...> search starts here:
+// CHECK-CXX-NEXT:  [[SDKROOT]]/usr/local/include
+// CHECK-CXX-NEXT:  /clang/{{.*}}/include
+// CHECK-CXX-NEXT:  [[SDKROOT]]/usr/include
+
+// However, if the user requests libc++, the MachO driver should find the 
search path.
+// RUN: %clang -xc++ -stdlib=libc++ %s -target arm64-apple-none-macho 
-isysroot %t/MacOSX15.1.sdk -E -v 2>&1 | FileCheck --check-prefix=CHECK-LIBCXX 
%s
+//
+// CHECK-LIBCXX:-isysroot [[SDKROOT:[^ ]*/MacOSX15.1.sdk]]
+// CHECK-LIBCXX:#include <...> search starts here:
+// CHECK-LIBCXX-NEXT:   [[SDKROOT]]/usr/include/c++/v1
+// CHECK-LIBCXX-NEXT:   [[SDKROOT]]/usr/local/include
+// CHECK-LIBCXX-NEXT:   /clang/{{.*}}/include
+// CHECK-LIBCXX-NEXT:   [[SDKROOT]]/usr/include
+
+// Verify that embedded uses can swap in alternate usr/include and 
usr/local/include directories.
+// usr/local/include is specified in the driver as -internal-isystem, however, 
the driver generated
+// paths come before the paths in the driver arguments. In order to keep 
usr/local/include in the
+// same position, -isystem has to be used instead of -Xclang 
-internal-isystem. There isn't an
+// -externc-isystem, but it's ok to use -Xclang -internal-externc-isystem 
since the driver doesn't
+// use that if -nostdlibinc or -nostdinc is passed.
+// RUN: %clang -xc++ -stdlib=libc++ %s -target arm64-apple-none-macho 
-isysroot %t/MacOSX15.1.sdk -nostdlibinc -isystem 
%t/MacOSX15.1.sdk/embedded/usr/local/include -Xclang -internal-externc-isystem 
-Xclang %t/MacOSX15.1.sdk/embedded/usr/include -E -v 2>&1 | FileCheck 
--check-prefix=CHECK-EMBEDDED %s
+//
+// CHECK-EMBEDDED:  -isysroot [[SDKROOT:[^ ]*/MacOSX15.1.sdk]]

jroelofs wrote:

if you pass `"-DSDKROOT=%t/MacOSX15.1.sdk"` as a `FileCheck` argument, then 
this can be just `[[SDKROOT]]`, and it'll avoid issues with spaces in the path 
to the build directory.

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


[clang] [Darwin][Driver][clang] apple-none-macho orders the resource directory after internal-externc-isystem when nostdlibinc is used (PR #120507)

2024-12-19 Thread Jon Roelofs via cfe-commits


@@ -0,0 +1,55 @@
+// UNSUPPORTED: system-windows
+//   Windows is unsupported because we use the Unix path separator `/` in the 
test.
+
+// Add default directories before running clang to check default
+// search paths.
+// RUN: rm -rf %t && mkdir -p %t
+// RUN: cp -R %S/Inputs/MacOSX15.1.sdk %t/
+// RUN: mkdir -p %t/MacOSX15.1.sdk/usr/include
+// RUN: mkdir -p %t/MacOSX15.1.sdk/usr/include/c++/v1
+// RUN: mkdir -p %t/MacOSX15.1.sdk/usr/local/include
+// RUN: mkdir -p %t/MacOSX15.1.sdk/embedded/usr/include
+// RUN: mkdir -p %t/MacOSX15.1.sdk/embedded/usr/local/include
+
+// Unlike the Darwin driver, the MachO driver doesn't add any framework search 
paths,
+// only the normal header ones.

jroelofs wrote:

Is there a `CHECK-C-NOT:` you could add to enforce what the comment describes?

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


[clang] [llvm] [InstCombine] Infer nuw for gep inbounds from base of object (PR #119225)

2024-12-19 Thread Nikita Popov via cfe-commits

nikic wrote:

@fmayer The `withoutNoUnsignedSignedWrap()` API already removed the inbounds 
flag as well (because inbounds requires nusw). So I think the effect of your 
change is to drop inbounds in case all indices are negative, which should 
generally not be necessary.

It's pretty likely that the root cause here is indeed incorrect inbounds 
preservation somewhere, but I think the logic in that transform is correct.

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


[clang] [libclang/python] Add a few things to the python api (PR #120590)

2024-12-19 Thread via cfe-commits

github-actions[bot] wrote:



Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write 
permissions for the repository. In which case you can instead tag reviewers by 
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a 
review by "ping"ing the PR by adding a comment “Ping”. The common courtesy 
"ping" rate is once a week. Please remember that you are asking for valuable 
time from other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] [libclang/python] Add a few things to the python api (PR #120590)

2024-12-19 Thread Mathias Stearn via cfe-commits

https://github.com/RedBeard0531 created 
https://github.com/llvm/llvm-project/pull/120590

I modified a local copy of cindex.py to add these when working on something and 
wanted to upstream the improvements.

>From 1c68440616b555c376a3c227338f23ca80a2c777 Mon Sep 17 00:00:00 2001
From: Mathias Stearn 
Date: Thu, 19 Dec 2024 16:22:04 +0100
Subject: [PATCH] [libclang/python] Add a few things to the python api

---
 clang/bindings/python/clang/cindex.py | 24 +++-
 1 file changed, 23 insertions(+), 1 deletion(-)

diff --git a/clang/bindings/python/clang/cindex.py 
b/clang/bindings/python/clang/cindex.py
index f8a20a1e224724..2d0c2214ec9260 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -1552,6 +1552,9 @@ def from_location(tu, location):
 
 return cursor
 
+def __hash__(self):
+return self.hash
+
 def __eq__(self, other):
 return conf.lib.clang_equalCursors(self, other)  # type: ignore 
[no-any-return]
 
@@ -1797,7 +1800,7 @@ def mangled_name(self):
 return self._mangled_name
 
 @property
-def location(self):
+def location(self) -> SourceLocation:
 """
 Return the source location (the starting character) of the entity
 pointed at by the cursor.
@@ -2022,6 +2025,14 @@ def lexical_parent(self):
 
 return self._lexical_parent
 
+@property
+def specialized_template(self):
+"""Return the base template that this cursor is a specialization of, 
if any."""
+return Cursor.from_cursor_result(
+conf.lib.clang_getSpecializedCursorTemplate(self),
+self
+)
+
 @property
 def translation_unit(self):
 """Returns the TranslationUnit to which this Cursor belongs."""
@@ -2143,6 +2154,9 @@ def get_bitfield_width(self):
 """
 return conf.lib.clang_getFieldDeclBitWidth(self)  # type: ignore 
[no-any-return]
 
+def has_attrs(self):
+return bool(conf.lib.clang_Cursor_hasAttrs(self))
+
 @staticmethod
 def from_result(res, arg):
 assert isinstance(res, Cursor)
@@ -3401,6 +3415,12 @@ def __str__(self):
 def __repr__(self):
 return "" % (self.name)
 
+def __eq__(self, other):
+return isinstance(other, File) and 
bool(conf.lib.clang_File_isEqual(self, other))
+
+def __ne__(self, other):
+return not self.__eq__(other)
+
 @staticmethod
 def from_result(res, arg):
 assert isinstance(res, c_object_p)
@@ -3795,6 +3815,7 @@ def write_main_file_to_stdout(self):
 ("clang_getCursorType", [Cursor], Type),
 ("clang_getCursorUSR", [Cursor], _CXString),
 ("clang_Cursor_getMangling", [Cursor], _CXString),
+("clang_Cursor_hasAttrs", [Cursor], c_uint),
 # ("clang_getCXTUResourceUsage",
 #  [TranslationUnit],
 #  CXTUResourceUsage),
@@ -3819,6 +3840,7 @@ def write_main_file_to_stdout(self):
 ("clang_getFile", [TranslationUnit, c_interop_string], c_object_p),
 ("clang_getFileName", [File], _CXString),
 ("clang_getFileTime", [File], c_uint),
+("clang_File_isEqual", [File, File], c_int),
 ("clang_getIBOutletCollectionType", [Cursor], Type),
 ("clang_getIncludedFile", [Cursor], c_object_p),
 (

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


[clang] [libclang/python] Add a few things to the python api (PR #120590)

2024-12-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Mathias Stearn (RedBeard0531)


Changes

I modified a local copy of cindex.py to add these when working on something and 
wanted to upstream the improvements.

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


1 Files Affected:

- (modified) clang/bindings/python/clang/cindex.py (+23-1) 


``diff
diff --git a/clang/bindings/python/clang/cindex.py 
b/clang/bindings/python/clang/cindex.py
index f8a20a1e224724..2d0c2214ec9260 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -1552,6 +1552,9 @@ def from_location(tu, location):
 
 return cursor
 
+def __hash__(self):
+return self.hash
+
 def __eq__(self, other):
 return conf.lib.clang_equalCursors(self, other)  # type: ignore 
[no-any-return]
 
@@ -1797,7 +1800,7 @@ def mangled_name(self):
 return self._mangled_name
 
 @property
-def location(self):
+def location(self) -> SourceLocation:
 """
 Return the source location (the starting character) of the entity
 pointed at by the cursor.
@@ -2022,6 +2025,14 @@ def lexical_parent(self):
 
 return self._lexical_parent
 
+@property
+def specialized_template(self):
+"""Return the base template that this cursor is a specialization of, 
if any."""
+return Cursor.from_cursor_result(
+conf.lib.clang_getSpecializedCursorTemplate(self),
+self
+)
+
 @property
 def translation_unit(self):
 """Returns the TranslationUnit to which this Cursor belongs."""
@@ -2143,6 +2154,9 @@ def get_bitfield_width(self):
 """
 return conf.lib.clang_getFieldDeclBitWidth(self)  # type: ignore 
[no-any-return]
 
+def has_attrs(self):
+return bool(conf.lib.clang_Cursor_hasAttrs(self))
+
 @staticmethod
 def from_result(res, arg):
 assert isinstance(res, Cursor)
@@ -3401,6 +3415,12 @@ def __str__(self):
 def __repr__(self):
 return "" % (self.name)
 
+def __eq__(self, other):
+return isinstance(other, File) and 
bool(conf.lib.clang_File_isEqual(self, other))
+
+def __ne__(self, other):
+return not self.__eq__(other)
+
 @staticmethod
 def from_result(res, arg):
 assert isinstance(res, c_object_p)
@@ -3795,6 +3815,7 @@ def write_main_file_to_stdout(self):
 ("clang_getCursorType", [Cursor], Type),
 ("clang_getCursorUSR", [Cursor], _CXString),
 ("clang_Cursor_getMangling", [Cursor], _CXString),
+("clang_Cursor_hasAttrs", [Cursor], c_uint),
 # ("clang_getCXTUResourceUsage",
 #  [TranslationUnit],
 #  CXTUResourceUsage),
@@ -3819,6 +3840,7 @@ def write_main_file_to_stdout(self):
 ("clang_getFile", [TranslationUnit, c_interop_string], c_object_p),
 ("clang_getFileName", [File], _CXString),
 ("clang_getFileTime", [File], c_uint),
+("clang_File_isEqual", [File, File], c_int),
 ("clang_getIBOutletCollectionType", [Cursor], Type),
 ("clang_getIncludedFile", [Cursor], c_object_p),
 (

``




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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-19 Thread Dmitry Chestnykh via cfe-commits

https://github.com/chestnykh created 
https://github.com/llvm/llvm-project/pull/120591

There are a few functions that emit warnings related to positional arguments in 
format strings. These functions use `getLocationOfByte()` which has O(n) 
complexity and may lead to silent hang of compilation in some cases. But such 
warnings is not widely used and actually don't emit if user didn't pass the 
appropriate `-W...` flag, so if the flag is not passed dont make the call
to `EmitFormatDiagnostic` for such diags.

Fix #120462

>From 5b61245bbdc9d1874684f29bba880f6b5a4cfe82 Mon Sep 17 00:00:00 2001
From: Dmitry Chestnykh 
Date: Thu, 19 Dec 2024 18:35:35 +0300
Subject: [PATCH] [Clang][Sema] Process warnings conditionally

There are a few functions that emit warnings
related to positional arguments in format strings.
These functions use `getLocationOfByte()` which has O(n)
complexity and may lead to silent hang of compilation in some cases.
But such warnings is not widely used and actually don't emit
if user didn't pass the appropriate `-W...` flag, so
if the flag is not passed dont make the call
to `EmitFormatDiagnostic` for such diags.

Fix #120462
---
 clang/lib/Sema/SemaChecking.cpp | 30 ++
 1 file changed, 18 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index be5d3694aec152..a745250988feeb 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -6612,27 +6612,33 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_non_standard_positional_arg, 
SourceLocation())) {
+
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
+getLocationOfByte(startPos),
+/*IsStringLocation*/true,
+getSpecifierRange(startPos, posLen));
+  }
 }
 
 void CheckFormatHandler::HandleInvalidPosition(
 const char *startSpecifier, unsigned specifierLen,
 analyze_format_string::PositionContext p) {
-  EmitFormatDiagnostic(
-  S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
-  getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
-  getSpecifierRange(startSpecifier, specifierLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_invalid_positional_specifier, 
SourceLocation())) {
+EmitFormatDiagnostic(
+S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
+getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
+getSpecifierRange(startSpecifier, specifierLen));
+  }
 }
 
 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier, 
SourceLocation())) {
+EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
+getLocationOfByte(startPos),
+/*IsStringLocation*/true,
+getSpecifierRange(startPos, posLen));
+  }
 }
 
 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {

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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-19 Thread Dmitry Chestnykh via cfe-commits

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


[clang] 1f2d934 - [clang][bytecode] Support pointers in __builtin_mem{move,cpy} (#120560)

2024-12-19 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-12-19T16:38:58+01:00
New Revision: 1f2d934525833c4aae5f0436fd99551c776fd246

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

LOG: [clang][bytecode] Support pointers in __builtin_mem{move,cpy} (#120560)

Unfortunately, that means we can't use the __builtin_bit_cast
implementation for this.

Added: 


Modified: 
clang/lib/AST/ByteCode/InterpBuiltin.cpp
clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
clang/lib/AST/ByteCode/InterpBuiltinBitCast.h
clang/lib/AST/ByteCode/Pointer.h
clang/test/AST/ByteCode/builtin-functions.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index d6b33c8aeeaac3..2ae91feb2d9e8e 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1862,10 +1862,10 @@ static bool interp__builtin_memcpy(InterpState &S, 
CodePtr OpPC,
   }
 
   QualType ElemType;
-  if (SrcPtr.getFieldDesc()->isArray())
-ElemType = SrcPtr.getFieldDesc()->getElemQualType();
+  if (DestPtr.getFieldDesc()->isArray())
+ElemType = DestPtr.getFieldDesc()->getElemQualType();
   else
-ElemType = SrcPtr.getType();
+ElemType = DestPtr.getType();
 
   unsigned ElemSize =
   S.getASTContext().getTypeSizeInChars(ElemType).getQuantity();
@@ -1876,6 +1876,18 @@ static bool interp__builtin_memcpy(InterpState &S, 
CodePtr OpPC,
 return false;
   }
 
+  QualType SrcElemType;
+  if (SrcPtr.getFieldDesc()->isArray())
+SrcElemType = SrcPtr.getFieldDesc()->getElemQualType();
+  else
+SrcElemType = SrcPtr.getType();
+
+  if (!S.getASTContext().hasSameUnqualifiedType(ElemType, SrcElemType)) {
+S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_memcpy_type_pun)
+<< Move << SrcElemType << ElemType;
+return false;
+  }
+
   // Check for overlapping memory regions.
   if (!Move && Pointer::pointToSameBlock(SrcPtr, DestPtr)) {
 unsigned SrcIndex = SrcPtr.getIndex() * SrcPtr.elemSize();
@@ -1893,8 +1905,8 @@ static bool interp__builtin_memcpy(InterpState &S, 
CodePtr OpPC,
   // As a last resort, reject dummy pointers.
   if (DestPtr.isDummy() || SrcPtr.isDummy())
 return false;
-
-  if (!DoBitCastPtr(S, OpPC, SrcPtr, DestPtr, Size.getZExtValue()))
+  assert(Size.getZExtValue() % ElemSize == 0);
+  if (!DoMemcpy(S, OpPC, SrcPtr, DestPtr, Bytes(Size.getZExtValue()).toBits()))
 return false;
 
   S.Stk.push(DestPtr);

diff  --git a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
index 07f76943708216..0fc94e1694822a 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
@@ -448,3 +448,34 @@ bool clang::interp::DoBitCastPtr(InterpState &S, CodePtr 
OpPC,
 
   return Success;
 }
+
+bool clang::interp::DoMemcpy(InterpState &S, CodePtr OpPC,
+ const Pointer &SrcPtr, const Pointer &DestPtr,
+ Bits Size) {
+  assert(SrcPtr.isBlockPointer());
+  assert(DestPtr.isBlockPointer());
+
+  unsigned SrcStartOffset = SrcPtr.getByteOffset();
+  unsigned DestStartOffset = DestPtr.getByteOffset();
+
+  enumeratePointerFields(SrcPtr, S.getContext(), Size,
+ [&](const Pointer &P, PrimType T, Bits BitOffset,
+ Bits FullBitWidth, bool PackedBools) -> bool {
+   unsigned SrcOffsetDiff =
+   P.getByteOffset() - SrcStartOffset;
+
+   Pointer DestP =
+   Pointer(DestPtr.asBlockPointer().Pointee,
+   DestPtr.asBlockPointer().Base,
+   DestStartOffset + SrcOffsetDiff);
+
+   TYPE_SWITCH(T, {
+ DestP.deref() = P.deref();
+ DestP.initialize();
+   });
+
+   return true;
+ });
+
+  return true;
+}

diff  --git a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.h 
b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.h
index b45613b2f21e20..a0191bab693c45 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.h
+++ b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.h
@@ -33,6 +33,10 @@ bool DoBitCastPtr(InterpState &S, CodePtr OpPC, const 
Pointer &FromPtr,
   Pointer &ToPtr, size_t Size);
 bool readPointerToBuffer(const Context &Ctx, const Pointer &FromPtr,
  BitcastBuffer &Buffer, bool ReturnOnUninit);
+
+bool DoMemcpy(InterpState &S, CodePtr OpPC, const Pointer &SrcPtr,
+  const Pointer &DestPtr, Bits Size);
+
 } // namespace interp
 } // namespace c

[clang] [clang][bytecode] Support pointers in __builtin_mem{move, cpy} (PR #120560)

2024-12-19 Thread Timm Baeder via cfe-commits

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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Dmitry Chestnykh (chestnykh)


Changes

There are a few functions that emit warnings related to positional arguments in 
format strings. These functions use `getLocationOfByte()` which has O(n) 
complexity and may lead to silent hang of compilation in some cases. But such 
warnings is not widely used and actually don't emit if user didn't pass the 
appropriate `-W...` flag, so if the flag is not passed dont make the call to 
`EmitFormatDiagnostic` for such diags.

Fix #120462

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


1 Files Affected:

- (modified) clang/lib/Sema/SemaChecking.cpp (+18-12) 


``diff
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index be5d3694aec152..a745250988feeb 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -6612,27 +6612,33 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_non_standard_positional_arg, 
SourceLocation())) {
+
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
+getLocationOfByte(startPos),
+/*IsStringLocation*/true,
+getSpecifierRange(startPos, posLen));
+  }
 }
 
 void CheckFormatHandler::HandleInvalidPosition(
 const char *startSpecifier, unsigned specifierLen,
 analyze_format_string::PositionContext p) {
-  EmitFormatDiagnostic(
-  S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
-  getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
-  getSpecifierRange(startSpecifier, specifierLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_invalid_positional_specifier, 
SourceLocation())) {
+EmitFormatDiagnostic(
+S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
+getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
+getSpecifierRange(startSpecifier, specifierLen));
+  }
 }
 
 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier, 
SourceLocation())) {
+EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
+getLocationOfByte(startPos),
+/*IsStringLocation*/true,
+getSpecifierRange(startPos, posLen));
+  }
 }
 
 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {

``




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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-19 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff 6f8afafd308d37d9abc4af0801dd5a4451c13718 
5b61245bbdc9d1874684f29bba880f6b5a4cfe82 --extensions cpp -- 
clang/lib/Sema/SemaChecking.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index a745250988..b0076c2686 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -6612,18 +6612,20 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_non_standard_positional_arg, 
SourceLocation())) {
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_non_standard_positional_arg, SourceLocation())) {
 
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-getLocationOfByte(startPos),
-/*IsStringLocation*/true,
-getSpecifierRange(startPos, posLen));
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
   }
 }
 
 void CheckFormatHandler::HandleInvalidPosition(
 const char *startSpecifier, unsigned specifierLen,
 analyze_format_string::PositionContext p) {
-  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_invalid_positional_specifier, 
SourceLocation())) {
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_invalid_positional_specifier, SourceLocation())) {
 EmitFormatDiagnostic(
 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
@@ -6633,11 +6635,12 @@ void CheckFormatHandler::HandleInvalidPosition(
 
 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
 unsigned posLen) {
-  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier, 
SourceLocation())) {
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
+SourceLocation())) {
 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
-getLocationOfByte(startPos),
-/*IsStringLocation*/true,
-getSpecifierRange(startPos, posLen));
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
   }
 }
 

``




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


[clang] [libclang/python] Add python binding for clang_Cursor_isAnonymousRecordDecl (PR #120483)

2024-12-19 Thread Jannick Kremer via cfe-commits

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


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


[clang] [Clang][Sema] Process warnings conditionally (PR #120591)

2024-12-19 Thread Dmitry Chestnykh via cfe-commits

https://github.com/chestnykh updated 
https://github.com/llvm/llvm-project/pull/120591

>From 5b61245bbdc9d1874684f29bba880f6b5a4cfe82 Mon Sep 17 00:00:00 2001
From: Dmitry Chestnykh 
Date: Thu, 19 Dec 2024 18:35:35 +0300
Subject: [PATCH 1/2] [Clang][Sema] Process warnings conditionally

There are a few functions that emit warnings
related to positional arguments in format strings.
These functions use `getLocationOfByte()` which has O(n)
complexity and may lead to silent hang of compilation in some cases.
But such warnings is not widely used and actually don't emit
if user didn't pass the appropriate `-W...` flag, so
if the flag is not passed dont make the call
to `EmitFormatDiagnostic` for such diags.

Fix #120462
---
 clang/lib/Sema/SemaChecking.cpp | 30 ++
 1 file changed, 18 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index be5d3694aec152..a745250988feeb 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -6612,27 +6612,33 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_non_standard_positional_arg, 
SourceLocation())) {
+
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
+getLocationOfByte(startPos),
+/*IsStringLocation*/true,
+getSpecifierRange(startPos, posLen));
+  }
 }
 
 void CheckFormatHandler::HandleInvalidPosition(
 const char *startSpecifier, unsigned specifierLen,
 analyze_format_string::PositionContext p) {
-  EmitFormatDiagnostic(
-  S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
-  getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
-  getSpecifierRange(startSpecifier, specifierLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_invalid_positional_specifier, 
SourceLocation())) {
+EmitFormatDiagnostic(
+S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
+getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
+getSpecifierRange(startSpecifier, specifierLen));
+  }
 }
 
 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
 unsigned posLen) {
-  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
-   getLocationOfByte(startPos),
-   /*IsStringLocation*/true,
-   getSpecifierRange(startPos, posLen));
+  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier, 
SourceLocation())) {
+EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
+getLocationOfByte(startPos),
+/*IsStringLocation*/true,
+getSpecifierRange(startPos, posLen));
+  }
 }
 
 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {

>From 7f93928a842888ab848a97bd5fbd981523c9c4d9 Mon Sep 17 00:00:00 2001
From: Dmitry Chestnykh 
Date: Thu, 19 Dec 2024 18:50:04 +0300
Subject: [PATCH 2/2] [clang][Sema] Fix code style

---
 clang/lib/Sema/SemaChecking.cpp | 21 -
 1 file changed, 12 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index a745250988feeb..b0076c2686a35b 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -6612,18 +6612,20 @@ void 
CheckFormatHandler::HandleNonStandardConversionSpecifier(
 
 void CheckFormatHandler::HandlePosition(const char *startPos,
 unsigned posLen) {
-  if 
(!S.getDiagnostics().isIgnored(diag::warn_format_non_standard_positional_arg, 
SourceLocation())) {
+  if (!S.getDiagnostics().isIgnored(
+  diag::warn_format_non_standard_positional_arg, SourceLocation())) {
 
EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
-getLocationOfByte(startPos),
-/*IsStringLocation*/true,
-getSpecifierRange(startPos, posLen));
+ getLocationOfByte(startPos),
+ /*IsStringLocation*/ true,
+ getSpecifierRange(startPos, posLen));
   }
 }
 
 void CheckFormatHandler::HandleInvalidPosition(
 const char *startSpecifier, unsi

[clang-tools-extra] Added options to readability-implicit-bool-conversion (PR #120087)

2024-12-19 Thread via cfe-commits


@@ -319,10 +319,9 @@ Changes in existing checks
   diagnostic.
 
 - Improved :doc:`readability-implicit-bool-conversion
-  ` check
-  by adding the option `UseUpperCaseLiteralSuffix` to select the
-  case of the literal suffix in fixes and fixing false positive for implicit
-  conversion of comparison result in C23.
+  ` check by adding the
+   options:
+   
`UseUpperCaseLiteralSuffix`,`CheckConversionsToBool`,`CheckConversionsFromBool`.

EugeneZelenko wrote:

Please merge with previous line.

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


[clang] [libclang/python] Add python bindings for PrintingPolicy (PR #120494)

2024-12-19 Thread Jannick Kremer via cfe-commits


@@ -981,3 +983,13 @@ def test_from_result_null(self):
 def test_from_cursor_result_null(self):
 tu = get_tu("")
 self.assertEqual(tu.cursor.semantic_parent, None)
+
+def test_pretty_print(self):
+tu = get_tu("struct X { int x; }; void f(bool x) { }", lang="cpp")
+f = get_cursor(tu, "f")
+
+self.assertEqual(f.displayname, "f(bool)")
+pp = PrintingPolicy.create(f)
+self.assertEqual(f.pretty_printed(pp), "void f(bool x) {\n}\n")
+pp.set_property(PrintingPolicyProperty.Bool, False)
+self.assertEqual(f.pretty_printed(pp), "void f(_Bool x) {\n}\n")

DeinAlptraum wrote:

Please ensure that all interface functions are tested, i.e. in this case 
`PrintingPolicy.get_property`

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


[clang] [libclang/python] Add python bindings for PrintingPolicy (PR #120494)

2024-12-19 Thread Jannick Kremer via cfe-commits

https://github.com/DeinAlptraum commented:

Thanks for the PR! Two minor comments and formatting, otherwise LGTM!

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


[clang] [libclang/python] Add python bindings for PrintingPolicy (PR #120494)

2024-12-19 Thread Jannick Kremer via cfe-commits

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


[clang] [libclang/python] Add python bindings for PrintingPolicy (PR #120494)

2024-12-19 Thread Jannick Kremer via cfe-commits


@@ -3685,6 +3695,71 @@ def write_main_file_to_stdout(self):
 conf.lib.clang_CXRewriter_writeMainFileToStdOut(self)
 
 
+class PrintingPolicyProperty(BaseEnumeration):
+
+"""
+A PrintingPolicyProperty identifies a property of a PrintingPolicy.
+"""
+Indentation = 0
+SuppressSpecifiers = 1
+SuppressTagKeyword = 2
+IncludeTagDefinition = 3
+SuppressScope = 4
+SuppressUnwrittenScope = 5
+SuppressInitializers = 6
+ConstantArraySizeAsWritten = 7
+AnonymousTagLocations = 8
+SuppressStrongLifetime = 9
+SuppressLifetimeQualifiers = 10
+SuppressTemplateArgsInCXXConstructors = 11
+Bool = 12
+Restrict = 13
+Alignof = 14
+UnderscoreAlignof = 15
+UseVoidForZeroParams = 16
+TerseOutput = 17
+PolishForDeclaration = 18
+Half = 19
+MSWChar = 20
+IncludeNewlines = 21
+MSVCFormatting = 22
+ConstantsAsWritten = 23
+SuppressImplicitBase = 24
+FullyQualifiedName = 25
+
+
+class PrintingPolicy(ClangObject):
+"""
+The PrintingPolicy is a wrapper class around clang::PrintingPolicy
+
+It allows specifying how declarations, expressions, and types should be
+pretty-printed.
+"""
+
+@staticmethod
+def create(cu):

DeinAlptraum wrote:

I would appreciate a more telling parameter name (e.g. `cursor`)

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


[clang] [analyzer] Handle [[assume(cond)]] as __builtin_assume(cond) (PR #116462)

2024-12-19 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

> I made the followup for this one in #120572

Please severt and reland with followup. Followup is good way to go for trivial 
cases which can be landed with quick or no review

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


[clang] [clang analyzer]consume `llvm::Error` (PR #120597)

2024-12-19 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 created 
https://github.com/llvm/llvm-project/pull/120597

`llvm::Error` must be consumed, otherwise it will cause trap during destructor


>From de02085e535f21c74e8a7efb26272590398b Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Fri, 20 Dec 2024 00:10:03 +0800
Subject: [PATCH] [clang analyzer]consume `llvm::Error`

`llvm::Error` must be consumed, otherwise it will cause trap during destructor
---
 clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp 
b/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
index 71268af22e2424..e8cf367b833467 100644
--- a/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
+++ b/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
@@ -81,7 +81,7 @@ class TextDiagnostics : public PathDiagnosticConsumer {
 
 if (llvm::Error Err = Repls.add(Repl)) {
   llvm::errs() << "Error applying replacement " << Repl.toString()
-   << ": " << Err << "\n";
+   << ": " << llvm::toString(std::move(Err)) << "\n";
 }
   }
 };

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


[clang] [clang analyzer]consume `llvm::Error` (PR #120597)

2024-12-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Congcong Cai (HerrCai0907)


Changes

`llvm::Error` must be consumed, otherwise it will cause trap during destructor


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


1 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp (+1-1) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp 
b/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
index 71268af22e2424..e8cf367b833467 100644
--- a/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
+++ b/clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
@@ -81,7 +81,7 @@ class TextDiagnostics : public PathDiagnosticConsumer {
 
 if (llvm::Error Err = Repls.add(Repl)) {
   llvm::errs() << "Error applying replacement " << Repl.toString()
-   << ": " << Err << "\n";
+   << ": " << llvm::toString(std::move(Err)) << "\n";
 }
   }
 };

``




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


[clang] [libclang] Add API to query more information about base classes. (PR #120300)

2024-12-19 Thread Jannick Kremer via cfe-commits

https://github.com/DeinAlptraum commented:

I'm only familiar with the Python-side of the bindings, so only reviewed those. 
Minor comments, otherwise LGTM!

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


[clang] [libclang] Add API to query more information about base classes. (PR #120300)

2024-12-19 Thread Jannick Kremer via cfe-commits


@@ -437,6 +437,8 @@ LLVM_19 {
 LLVM_20 {
   global:
 clang_isBeforeInTranslationUnit;
+clang_getOffsetOfBase;
+clang_visitCXXBaseClasses;

DeinAlptraum wrote:

Not sure if this actually matters, but since all the other entries follow an 
alphabetic order, please keep it that way.

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


[clang] [libclang] Add API to query more information about base classes. (PR #120300)

2024-12-19 Thread Jannick Kremer via cfe-commits


@@ -1,4 +1,5 @@
 import os
+import clang.cindex

DeinAlptraum wrote:

This import seems to be unused

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


[clang] [libclang] Add API to query more information about base classes. (PR #120300)

2024-12-19 Thread Jannick Kremer via cfe-commits

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


[clang] [libclang] Add API to query more information about base classes. (PR #120300)

2024-12-19 Thread Jannick Kremer via cfe-commits


@@ -2663,6 +2671,21 @@ def visitor(field, children):
 conf.lib.clang_Type_visitFields(self, fields_visit_callback(visitor), 
fields)
 return iter(fields)
 
+def get_bases(self):
+"""Return an iterator for accessing the base classes of this type."""
+
+def visitor(field, children):
+assert field != conf.lib.clang_getNullCursor()
+
+# Create reference to TU so it isn't GC'd before Cursor.
+field._tu = self._tu
+fields.append(field)
+return 1  # continue
+
+fields: list[Cursor] = []

DeinAlptraum wrote:

Shouldn't `fields` be named differently here? E.g. `base_classes` or similar

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


[clang] [libclang] Add API to query more information about base classes. (PR #120300)

2024-12-19 Thread Jannick Kremer via cfe-commits


@@ -2663,6 +2671,21 @@ def visitor(field, children):
 conf.lib.clang_Type_visitFields(self, fields_visit_callback(visitor), 
fields)
 return iter(fields)
 
+def get_bases(self):
+"""Return an iterator for accessing the base classes of this type."""
+
+def visitor(field, children):
+assert field != conf.lib.clang_getNullCursor()
+
+# Create reference to TU so it isn't GC'd before Cursor.
+field._tu = self._tu
+fields.append(field)
+return 1  # continue
+
+fields: list[Cursor] = []
+conf.lib.clang_visitCXXBaseClasses(self, 
fields_visit_callback(visitor), fields)

DeinAlptraum wrote:

Since it is used for different purposes as well now, it might be sensible to 
change the name of `fields_visit_callback` to something more generic.

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


[clang] [HLSL] Make fast math the default for HLSL (PR #119820)

2024-12-19 Thread Sarah Spall via cfe-commits

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


  1   2   3   4   5   6   >