[clang] [clang-format] Allow decltype in requires clause (PR #78847)

2024-01-20 Thread Emilia Kond via cfe-commits


@@ -1071,6 +1071,16 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsRequiresClausesAndConcepts) {
 "concept C = (!Foo) && Bar;");
   ASSERT_EQ(Tokens.size(), 19u) << Tokens;
   EXPECT_TOKEN(Tokens[15], tok::ampamp, TT_BinaryOperator);
+
+  Tokens = annotate("void f() & requires(C) {}");
+  ASSERT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::amp, TT_PointerOrReference);
+  EXPECT_TOKEN(Tokens[5], tok::kw_requires, TT_RequiresClause);
+
+  Tokens = annotate("auto f() -> int& requires(C) {}");
+  ASSERT_EQ(Tokens.size(), 20u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::amp, TT_PointerOrReference);
+  EXPECT_TOKEN(Tokens[7], tok::kw_requires, TT_RequiresClause);
 }

rymiel wrote:

Thanks, but this test input never actually runs parseRequires(), but I 
constructed another case which does, I'll add both

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


[libclc] libclc: add some missing AMD gfx9 and gfx10 symlinks (PR #78884)

2024-01-20 Thread Zoltán Böszörményi via cfe-commits

https://github.com/zboszor updated 
https://github.com/llvm/llvm-project/pull/78884

From 26e8eaaa9b0be1fdc146b5b4e8d285a2e8a2edbb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Zolt=C3=A1n=20B=C3=B6sz=C3=B6rm=C3=A9nyi?=
 
Date: Sun, 21 Jan 2024 07:59:02 +0100
Subject: [PATCH 1/2] libclc: add some missing AMD gfx9 and gfx10 symlinks
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Zoltán Böszörményi 
---
 libclc/CMakeLists.txt | 15 +++
 1 file changed, 15 insertions(+)

diff --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt
index 9daef8265c16f2..aa7acd4797602b 100644
--- a/libclc/CMakeLists.txt
+++ b/libclc/CMakeLists.txt
@@ -154,6 +154,21 @@ if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "6.99.99" )
set( tahiti_aliases ${tahiti_aliases} gfx904 gfx906 )
 endif()
 
+# Support for gfx909, gfx1010, gfx1011 and gfx1012 was added in LLVM 10 
(r345120)
+if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "9.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} gfx909 gfx1010 gfx1011 gfx1012 )
+endif()
+
+# Support for gfx908 was added in LLVM 11 (r373411)
+if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "10.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} gfx908 )
+endif()
+
+# Support for gfx90c, gfx1030, gfx1031, gfx1032, gfx1033 was added in LLVM 12
+if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "11.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} gfx90c gfx1030 gfx1031 gfx1032 
gfx1033 )
+endif()
+
 # pkg-config file
 configure_file( libclc.pc.in libclc.pc @ONLY )
 install( FILES ${CMAKE_CURRENT_BINARY_DIR}/libclc.pc DESTINATION 
"${CMAKE_INSTALL_DATADIR}/pkgconfig" )

From 3d35866b080093babea5a12d9dd8a31381107286 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Zolt=C3=A1n=20B=C3=B6sz=C3=B6rm=C3=A9nyi?=
 
Date: Sun, 21 Jan 2024 08:48:09 +0100
Subject: [PATCH 2/2] libclc: add the remaining missing AMD gfx symlinks
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Zoltán Böszörményi 
---
 libclc/CMakeLists.txt | 25 +
 1 file changed, 25 insertions(+)

diff --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt
index aa7acd4797602b..f9792a331589a2 100644
--- a/libclc/CMakeLists.txt
+++ b/libclc/CMakeLists.txt
@@ -169,6 +169,31 @@ if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "11.99.99" )
set( tahiti_aliases ${tahiti_aliases} gfx90c gfx1030 gfx1031 gfx1032 
gfx1033 )
 endif()
 
+# Support for tongapro, gfx602, gfx705, gfx805 was added in LLVM 13
+if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "12.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} tongapro gfx602 gfx705 gfx805 )
+endif()
+
+# Support for gfx90a, gfx1013, gfx1034, gfx1035 was added in LLVM 14
+if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "13.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} gfx90a gfx1013 gfx1034 gfx1035 )
+endif()
+
+# Support for gfx940, gfx1036, gfx1100, gfx1101, gfx1102, gfx1103 was added in 
LLVM 16
+if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "15.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} gfx940 gfx1036 gfx1100 gfx1101 
gfx1102 gfx1103 )
+endif()
+
+# Support for gfx941, gfx942, gfx1150, gfx1151 was added in LLVM 18
+if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "17.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} gfx941 gfx942 gfx1150 gfx1151 )
+endif()
+
+# Support for gfx1200, gfx1201 was added in LLVM 19
+if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "18.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} gfx1200 gfx1201 )
+endif()
+
 # pkg-config file
 configure_file( libclc.pc.in libclc.pc @ONLY )
 install( FILES ${CMAKE_CURRENT_BINARY_DIR}/libclc.pc DESTINATION 
"${CMAKE_INSTALL_DATADIR}/pkgconfig" )

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


[clang] [clang-format] NEVER allow && to be an unary operator. (PR #78852)

2024-01-20 Thread Emilia Kond via cfe-commits

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


[clang-tools-extra] [libc] [clang] [flang] [llvm] [libcxx] [compiler-rt] [lld] [mlir] [libc++][hardening] Don't trigger redundant checks in the fast mode. (PR #77176)

2024-01-20 Thread Konstantin Varlamov via cfe-commits

https://github.com/var-const updated 
https://github.com/llvm/llvm-project/pull/77176

>From f86839d0bfc8b2070127dc3b2c609c2b3f7239ad Mon Sep 17 00:00:00 2001
From: Konstantin Varlamov 
Date: Fri, 5 Jan 2024 20:08:27 -0800
Subject: [PATCH 1/2] [libc++][hardening] Don't trigger redundant checks in the
 fast mode.

Sometimes we essentially check the same condition twice -- for example,
a class might check that an index into its vector member variable is
valid before accessing it, but `vector::operator[]` contains the same
check. These "redundant" checks allow catching errors closer to the
source and providing a better error message, but they also impose
additional overhead. Marking the "early" checks as redundant allows
ignoring them in the fast mode (while still getting a guaranteed trap)
while still getting better error messages in the extensive mode and
above. Introducing a separate wrapper macro allows making the concept of
redundant assertions orthogonal to assertion categories and retaining
the actual category of a check.

This is a follow-up to https://github.com/llvm/llvm-project/pull/75918,
specifically to [this 
discussion](https://github.com/llvm/llvm-project/pull/75918#discussion_r1434493455).
---
 libcxx/include/__config | 16 
 .../include/__filesystem/directory_iterator.h   |  3 ++-
 libcxx/include/__iterator/next.h|  5 +++--
 libcxx/include/__iterator/prev.h|  5 +++--
 libcxx/include/__mdspan/layout_left.h   |  5 +++--
 libcxx/include/__mdspan/layout_right.h  |  5 +++--
 libcxx/include/__mdspan/layout_stride.h |  5 +++--
 libcxx/include/__ranges/chunk_by_view.h | 17 +++--
 libcxx/include/__ranges/drop_while_view.h   |  9 +
 libcxx/include/__ranges/filter_view.h   |  5 +++--
 libcxx/include/regex|  3 ++-
 11 files changed, 54 insertions(+), 24 deletions(-)

diff --git a/libcxx/include/__config b/libcxx/include/__config
index 082c73e672c7492..b20e8abed0939cc 100644
--- a/libcxx/include/__config
+++ b/libcxx/include/__config
@@ -290,6 +290,18 @@
 //   user input.
 //
 // - `_LIBCPP_ASSERT_UNCATEGORIZED` -- for assertions that haven't been 
properly classified yet.
+//
+// In addition to these categories, `_LIBCPP_REDUNDANT_ASSERTION` should be 
used to wrap assertions that duplicate other
+// assertions (for example, a range view might check that its `optional` data 
member holds a value before dereferencing
+// it, but this is already checked by `optional` itself). Redundant assertions 
incur an additional performance overhead
+// and don't provide any extra security benefit, but catching an error earlier 
allows halting the program closer to the
+// root cause and giving the user an error message that contains more context. 
Due to these tradeoffs, redundant
+// assertions are disabled in the fast mode but are enabled in the extensive 
mode and above. Thus, going back to the
+// example above, if a view attempts to dereference an empty optional member 
variable:
+// - in the fast mode, the program will only perform one check and will trap 
inside the optional (with an error
+//   amounting to "Attempting to dereference an empty optional");
+// - in the extensive mode, the program will normally perform two checks (in 
the non-error case), and if the optional is
+//   empty, it will trap inside the view (with an error like "`foo_view` 
doesn't have a valid predicate").
 
 // clang-format off
 #  define _LIBCPP_HARDENING_MODE_NONE  (1 << 1)
@@ -331,6 +343,7 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message) 
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_INTERNAL(expression, message) 
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_UNCATEGORIZED(expression, message)
_LIBCPP_ASSUME(expression)
+#define _LIBCPP_REDUNDANT_ASSERTION(expression)  
_LIBCPP_ASSUME(expression)
 
 // Extensive hardening mode checks.
 
@@ -344,6 +357,7 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_UNCATEGORIZED(expression, message)
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message) 
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_REDUNDANT_ASSERTION(expression)  
expression
 // Disabled checks.
 #define _LIBCPP_ASSERT_INTERNAL(expression, message) 
_LIBCPP_ASSUME(expression)
 
@@ -360,6 +374,7 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_INTERNAL(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_UNCATEGORIZED(expression, 

[libcxx] [clang-tools-extra] [clang] [llvm] [libc++][hardening] Categorize assertions related to strict weak ordering (PR #77405)

2024-01-20 Thread Konstantin Varlamov via cfe-commits

https://github.com/var-const updated 
https://github.com/llvm/llvm-project/pull/77405

>From f6a3ba6f2fb00b17182b405312eca4e837fe8977 Mon Sep 17 00:00:00 2001
From: Konstantin Varlamov 
Date: Mon, 8 Jan 2024 19:09:37 -0800
Subject: [PATCH] [libc++][hardening] Categorize assertions related to strict
 weak ordering

If a user passes a comparator that doesn't satisfy strict weak ordering
(see https://eel.is/c++draft/algorithms#alg.sorting.general) to
a sorting algorithm, this can produce an incorrect result or even lead
to an out-of-bounds access. Unfortunately, comprehensively validating
that a given comparator indeed satisfies the strict weak ordering
requirement is prohibitively expensive (see 
https://discourse.llvm.org/t/rfc-strict-weak-ordering-checks-in-the-debug-libc/70217).
As a result, we have three independent sets of checks, in order from
least to most expensive:

- assertions that catch out-of-bounds accesses within the algorithms'
  implementation. These are relatively cheap; however, they cannot catch
  the underlying cause and cannot prevent the case where an invalid
  comparator would result in an uncorrectly-sorted sequence without
  producing an OOB access;

- debug comparators that wrap a given comparator and on each comparison
  check that if `(a < b)`, then `!(b < a)`, where `<` stands for the
  user-provided comparator. This performs up to 2x number of comparisons
  but doesn't affect the algorithmic complexity. While this approach can
  find more issues, it is still a heuristic;

- a comprehensive check of the comparator that validates up to 100
  elements in the resulting sorted sequence (see the RFC above for
  details), imposing a significant performance overhead.

Accordingly, the first set of checks is enabled in the fast hardening
mode, the second in the extensive mode, and the third only in the debug
mode.

For the most expensive checks, introduce a new category
`_LIBCPP_ASSERT_INTRUSIVE`. This category is intended for expensive
checks that perform intrusive, extensive validation within the
implementation (either of the user input or of invariants or
postconditions of a function).

See https://reviews.llvm.org/D150264 for additional background.
---
 libcxx/include/__algorithm/comp_ref_type.h|  9 
 libcxx/include/__algorithm/nth_element.h  |  8 +++
 libcxx/include/__algorithm/sort.h | 22 +-
 .../__algorithm/three_way_comp_ref_type.h | 10 
 libcxx/include/__config   | 23 +++
 .../strict_weak_ordering_check.h  | 10 
 6 files changed, 53 insertions(+), 29 deletions(-)

diff --git a/libcxx/include/__algorithm/comp_ref_type.h 
b/libcxx/include/__algorithm/comp_ref_type.h
index 15f4a535a30bf0d..2583eec63eef665 100644
--- a/libcxx/include/__algorithm/comp_ref_type.h
+++ b/libcxx/include/__algorithm/comp_ref_type.h
@@ -44,7 +44,7 @@ struct __debug_less {
   _LIBCPP_CONSTEXPR_SINCE_CXX14 inline _LIBCPP_HIDE_FROM_ABI 
decltype((void)std::declval<_Compare&>()(
   std::declval<_LHS&>(), std::declval<_RHS&>()))
   __do_compare_assert(int, _LHS& __l, _RHS& __r) {
-_LIBCPP_ASSERT_UNCATEGORIZED(!__comp_(__l, __r), "Comparator does not 
induce a strict weak ordering");
+_LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(!__comp_(__l, __r), "Comparator does 
not induce a strict weak ordering");
 (void)__l;
 (void)__r;
   }
@@ -53,10 +53,9 @@ struct __debug_less {
   _LIBCPP_CONSTEXPR_SINCE_CXX14 inline _LIBCPP_HIDE_FROM_ABI void 
__do_compare_assert(long, _LHS&, _RHS&) {}
 };
 
-// Pass the comparator by lvalue reference. Or in debug mode, using a
-// debugging wrapper that stores a reference.
-#if _LIBCPP_HARDENING_MODE == _LIBCPP_HARDENING_MODE_DEBUG
-template 
+// Pass the comparator by lvalue reference. Or in the extensive hardening mode 
and above, using a debugging wrapper that
+// stores a reference.
+#if _LIBCPP_HARDENING_MODE == _LIBCPP_HARDENING_MODE_EXTENSIVE || 
_LIBCPP_HARDENING_MODE == _LIBCPP_HARDENING_MODE_DEBUG
 using __comp_ref_type = __debug_less<_Comp>;
 #else
 template 
diff --git a/libcxx/include/__algorithm/nth_element.h 
b/libcxx/include/__algorithm/nth_element.h
index a05970512595181..37ddfbdacf044d0 100644
--- a/libcxx/include/__algorithm/nth_element.h
+++ b/libcxx/include/__algorithm/nth_element.h
@@ -114,12 +114,12 @@ __nth_element(
 while (true) {
   while (!__comp(*__first, *__i)) {
 ++__i;
-_LIBCPP_ASSERT_UNCATEGORIZED(
+_LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(
 __i != __last,
 "Would read out of bounds, does your comparator satisfy the 
strict-weak ordering requirement?");
   }
   do {
-_LIBCPP_ASSERT_UNCATEGORIZED(
+_LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(
 __j != __first,
 "Would read out of bounds, does your comparator satisfy the 
strict-weak ordering requirement?");
 --__j;
@@ 

[clang-tools-extra] [libc] [clang] [flang] [llvm] [libcxx] [compiler-rt] [lld] [mlir] [libc++][hardening] Classify assertions related to leaks and syscalls. (PR #77164)

2024-01-20 Thread Konstantin Varlamov via cfe-commits

https://github.com/var-const updated 
https://github.com/llvm/llvm-project/pull/77164

>From e28e7b3e1337cb960cdc8028a70a43740fa7d636 Mon Sep 17 00:00:00 2001
From: Konstantin Varlamov 
Date: Thu, 21 Dec 2023 14:36:47 -0800
Subject: [PATCH 1/4] [libc++][hardening] Classify assertions related to leaks
 and syscalls.

Introduce two new categories:
- `_LIBCPP_ASSERT_VALID_DEALLOCATION`;
- `_LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL`.
---
 libcxx/include/__config  | 16 
 libcxx/include/__coroutine/coroutine_handle.h| 16 
 .../__memory_resource/polymorphic_allocator.h|  3 ++-
 libcxx/src/filesystem/operations.cpp |  8 +---
 libcxx/src/memory_resource.cpp   |  3 ++-
 libcxx/src/mutex.cpp |  8 +---
 6 files changed, 38 insertions(+), 16 deletions(-)

diff --git a/libcxx/include/__config b/libcxx/include/__config
index 082c73e672c749..4d74b564864272 100644
--- a/libcxx/include/__config
+++ b/libcxx/include/__config
@@ -280,6 +280,14 @@
 // - `_LIBCPP_ASSERT_NON_OVERLAPPING_RANGES` -- for functions that take 
several ranges as arguments, checks that the
 //   given ranges do not overlap.
 //
+// - `_LIBCPP_ASSERT_VALID_DEALLOCATION` -- checks that an attempt to 
deallocate memory is valid (e.g. the given object
+//   was allocated by the given allocator). Violating this category typically 
results in a memory leak.
+//
+// - `_LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL` -- checks that a call to an 
external API (e.g. a syscall) doesn't fail in
+//   an unexpected manner. This includes triggering documented cases of 
undefined behavior in an external library (like
+//   attempting to unlock an unlocked mutex in pthreads). We generally don't 
expect these failures to compromize memory
+//   safety or otherwise create an immediate security issue.
+//
 // - `_LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR` -- checks any operations that 
exchange nodes between containers to make sure
 //   the containers have compatible allocators.
 //
@@ -327,6 +335,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 // Overlapping ranges will make algorithms produce incorrect results but don't 
directly lead to a security
 // vulnerability.
 #define _LIBCPP_ASSERT_NON_OVERLAPPING_RANGES(expression, message)   
_LIBCPP_ASSUME(expression)
+#define _LIBCPP_ASSERT_VALID_DEALLOCATION(expression, message)   
_LIBCPP_ASSUME(expression)
+#define _LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL(expression, message)  
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message) 
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message) 
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_INTERNAL(expression, message) 
_LIBCPP_ASSUME(expression)
@@ -341,6 +351,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_NULL(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_OVERLAPPING_RANGES(expression, message)   
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_DEALLOCATION(expression, message)   
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_UNCATEGORIZED(expression, message)
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message) 
_LIBCPP_ASSERT(expression, message)
@@ -356,6 +368,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_NULL(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_OVERLAPPING_RANGES(expression, message)
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_DEALLOCATION(expression, message)
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL(expression, message)   
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_INTERNAL(expression, message)  
_LIBCPP_ASSERT(expression, message)
@@ -370,6 +384,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(expression, message)  
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_NON_NULL(expression, message)  
_LIBCPP_ASSUME(expression)
 #

[clang-tools-extra] [libc] [clang] [flang] [llvm] [libcxx] [compiler-rt] [lld] [mlir] [libc++][hardening] Categorize assertions that produce incorrect results (PR #77183)

2024-01-20 Thread Konstantin Varlamov via cfe-commits

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


[clang-tools-extra] [libc] [clang] [flang] [llvm] [libcxx] [compiler-rt] [lld] [mlir] [libc++][hardening] Categorize assertions that produce incorrect results (PR #77183)

2024-01-20 Thread Konstantin Varlamov via cfe-commits

https://github.com/var-const updated 
https://github.com/llvm/llvm-project/pull/77183

>From 2d62194c2c30b5072c8d42bf30d3b5163b1eb844 Mon Sep 17 00:00:00 2001
From: Konstantin Varlamov 
Date: Fri, 5 Jan 2024 23:34:42 -0800
Subject: [PATCH 1/2] [libc++][hardening] Categorize assertions that produce
 incorrect results

Introduce a new `argument-within-domain` category that covers cases
where the given arguments make it impossible to produce a correct result
(or create a valid object in case of constructors). While the incorrect
result doesn't create an immediate problem within the library (like e.g.
a null pointer dereference would), it always indicates a logic error in
user code and is highly likely to lead to a bug in the program once the
value is used.
---
 libcxx/include/__algorithm/clamp.h   |  2 +-
 libcxx/include/__algorithm/ranges_clamp.h|  5 +++--
 libcxx/include/__bit/bit_ceil.h  |  2 +-
 libcxx/include/__config  | 14 +-
 libcxx/include/__hash_table  |  2 +-
 libcxx/include/__memory/assume_aligned.h |  3 ++-
 libcxx/include/__numeric/gcd_lcm.h   |  2 +-
 libcxx/include/barrier   | 12 ++--
 libcxx/include/latch | 10 +-
 libcxx/include/semaphore |  8 
 libcxx/include/string_view   |  7 +--
 libcxx/src/filesystem/operations.cpp |  5 ++---
 libcxx/src/include/to_chars_floating_point.h |  2 +-
 13 files changed, 45 insertions(+), 29 deletions(-)

diff --git a/libcxx/include/__algorithm/clamp.h 
b/libcxx/include/__algorithm/clamp.h
index 1631b2673c3faf..003bf70dd4f01d 100644
--- a/libcxx/include/__algorithm/clamp.h
+++ b/libcxx/include/__algorithm/clamp.h
@@ -26,7 +26,7 @@ clamp(_LIBCPP_LIFETIMEBOUND const _Tp& __v,
   _LIBCPP_LIFETIMEBOUND const _Tp& __lo,
   _LIBCPP_LIFETIMEBOUND const _Tp& __hi,
   _Compare __comp) {
-  _LIBCPP_ASSERT_UNCATEGORIZED(!__comp(__hi, __lo), "Bad bounds passed to 
std::clamp");
+  _LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(!__comp(__hi, __lo), "Bad bounds 
passed to std::clamp");
   return __comp(__v, __lo) ? __lo : __comp(__hi, __v) ? __hi : __v;
 }
 
diff --git a/libcxx/include/__algorithm/ranges_clamp.h 
b/libcxx/include/__algorithm/ranges_clamp.h
index e6c86207254a19..a1185e7278f0ed 100644
--- a/libcxx/include/__algorithm/ranges_clamp.h
+++ b/libcxx/include/__algorithm/ranges_clamp.h
@@ -34,8 +34,9 @@ struct __fn {
 indirect_strict_weak_order> _Comp = 
ranges::less>
   _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr const _Type& 
operator()(
   const _Type& __value, const _Type& __low, const _Type& __high, _Comp 
__comp = {}, _Proj __proj = {}) const {
-_LIBCPP_ASSERT_UNCATEGORIZED(!bool(std::invoke(__comp, std::invoke(__proj, 
__high), std::invoke(__proj, __low))),
- "Bad bounds passed to std::ranges::clamp");
+_LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(
+!bool(std::invoke(__comp, std::invoke(__proj, __high), 
std::invoke(__proj, __low))),
+"Bad bounds passed to std::ranges::clamp");
 
 auto&& __projected = std::invoke(__proj, __value);
 if (std::invoke(__comp, std::forward(__projected), 
std::invoke(__proj, __low)))
diff --git a/libcxx/include/__bit/bit_ceil.h b/libcxx/include/__bit/bit_ceil.h
index 17fe06aa41ccd8..77fa739503bc58 100644
--- a/libcxx/include/__bit/bit_ceil.h
+++ b/libcxx/include/__bit/bit_ceil.h
@@ -28,7 +28,7 @@ _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr _Tp 
__bit_ceil(_Tp __t) no
   if (__t < 2)
 return 1;
   const unsigned __n = numeric_limits<_Tp>::digits - 
std::__countl_zero((_Tp)(__t - 1u));
-  _LIBCPP_ASSERT_UNCATEGORIZED(__n != numeric_limits<_Tp>::digits, "Bad input 
to bit_ceil");
+  _LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(__n != numeric_limits<_Tp>::digits, 
"Bad input to bit_ceil");
 
   if constexpr (sizeof(_Tp) >= sizeof(unsigned))
 return _Tp{1} << __n;
diff --git a/libcxx/include/__config b/libcxx/include/__config
index 082c73e672c749..9ba4fce834132f 100644
--- a/libcxx/include/__config
+++ b/libcxx/include/__config
@@ -283,6 +283,14 @@
 // - `_LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR` -- checks any operations that 
exchange nodes between containers to make sure
 //   the containers have compatible allocators.
 //
+// - `_LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN` -- checks that the given argument 
is within the domain of valid arguments
+//   for the function. Violating this typically produces an incorrect result 
(e.g. the clamp algorithm returns the
+//   original value without clamping it due to incorrect functors) or puts an 
object into an invalid state (e.g.
+//   a string view where only a subset of elements is possible to access). 
This doesn't cause an immediate issue within
+//   the library but is always a logic bug and is likely to cause problems 
within user code.
+//   This is somewhat of a catch-all (or fallback) category -- it 

[libcxx] [clang-tools-extra] [clang] [llvm] [libc++][hardening] Categorize assertions that produce incorrect results (PR #77183)

2024-01-20 Thread Konstantin Varlamov via cfe-commits

https://github.com/var-const updated 
https://github.com/llvm/llvm-project/pull/77183

>From 2d62194c2c30b5072c8d42bf30d3b5163b1eb844 Mon Sep 17 00:00:00 2001
From: Konstantin Varlamov 
Date: Fri, 5 Jan 2024 23:34:42 -0800
Subject: [PATCH 1/2] [libc++][hardening] Categorize assertions that produce
 incorrect results

Introduce a new `argument-within-domain` category that covers cases
where the given arguments make it impossible to produce a correct result
(or create a valid object in case of constructors). While the incorrect
result doesn't create an immediate problem within the library (like e.g.
a null pointer dereference would), it always indicates a logic error in
user code and is highly likely to lead to a bug in the program once the
value is used.
---
 libcxx/include/__algorithm/clamp.h   |  2 +-
 libcxx/include/__algorithm/ranges_clamp.h|  5 +++--
 libcxx/include/__bit/bit_ceil.h  |  2 +-
 libcxx/include/__config  | 14 +-
 libcxx/include/__hash_table  |  2 +-
 libcxx/include/__memory/assume_aligned.h |  3 ++-
 libcxx/include/__numeric/gcd_lcm.h   |  2 +-
 libcxx/include/barrier   | 12 ++--
 libcxx/include/latch | 10 +-
 libcxx/include/semaphore |  8 
 libcxx/include/string_view   |  7 +--
 libcxx/src/filesystem/operations.cpp |  5 ++---
 libcxx/src/include/to_chars_floating_point.h |  2 +-
 13 files changed, 45 insertions(+), 29 deletions(-)

diff --git a/libcxx/include/__algorithm/clamp.h 
b/libcxx/include/__algorithm/clamp.h
index 1631b2673c3faf4..003bf70dd4f01db 100644
--- a/libcxx/include/__algorithm/clamp.h
+++ b/libcxx/include/__algorithm/clamp.h
@@ -26,7 +26,7 @@ clamp(_LIBCPP_LIFETIMEBOUND const _Tp& __v,
   _LIBCPP_LIFETIMEBOUND const _Tp& __lo,
   _LIBCPP_LIFETIMEBOUND const _Tp& __hi,
   _Compare __comp) {
-  _LIBCPP_ASSERT_UNCATEGORIZED(!__comp(__hi, __lo), "Bad bounds passed to 
std::clamp");
+  _LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(!__comp(__hi, __lo), "Bad bounds 
passed to std::clamp");
   return __comp(__v, __lo) ? __lo : __comp(__hi, __v) ? __hi : __v;
 }
 
diff --git a/libcxx/include/__algorithm/ranges_clamp.h 
b/libcxx/include/__algorithm/ranges_clamp.h
index e6c86207254a19f..a1185e7278f0ed4 100644
--- a/libcxx/include/__algorithm/ranges_clamp.h
+++ b/libcxx/include/__algorithm/ranges_clamp.h
@@ -34,8 +34,9 @@ struct __fn {
 indirect_strict_weak_order> _Comp = 
ranges::less>
   _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr const _Type& 
operator()(
   const _Type& __value, const _Type& __low, const _Type& __high, _Comp 
__comp = {}, _Proj __proj = {}) const {
-_LIBCPP_ASSERT_UNCATEGORIZED(!bool(std::invoke(__comp, std::invoke(__proj, 
__high), std::invoke(__proj, __low))),
- "Bad bounds passed to std::ranges::clamp");
+_LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(
+!bool(std::invoke(__comp, std::invoke(__proj, __high), 
std::invoke(__proj, __low))),
+"Bad bounds passed to std::ranges::clamp");
 
 auto&& __projected = std::invoke(__proj, __value);
 if (std::invoke(__comp, std::forward(__projected), 
std::invoke(__proj, __low)))
diff --git a/libcxx/include/__bit/bit_ceil.h b/libcxx/include/__bit/bit_ceil.h
index 17fe06aa41ccd87..77fa739503bc58c 100644
--- a/libcxx/include/__bit/bit_ceil.h
+++ b/libcxx/include/__bit/bit_ceil.h
@@ -28,7 +28,7 @@ _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr _Tp 
__bit_ceil(_Tp __t) no
   if (__t < 2)
 return 1;
   const unsigned __n = numeric_limits<_Tp>::digits - 
std::__countl_zero((_Tp)(__t - 1u));
-  _LIBCPP_ASSERT_UNCATEGORIZED(__n != numeric_limits<_Tp>::digits, "Bad input 
to bit_ceil");
+  _LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(__n != numeric_limits<_Tp>::digits, 
"Bad input to bit_ceil");
 
   if constexpr (sizeof(_Tp) >= sizeof(unsigned))
 return _Tp{1} << __n;
diff --git a/libcxx/include/__config b/libcxx/include/__config
index 082c73e672c7492..9ba4fce834132f1 100644
--- a/libcxx/include/__config
+++ b/libcxx/include/__config
@@ -283,6 +283,14 @@
 // - `_LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR` -- checks any operations that 
exchange nodes between containers to make sure
 //   the containers have compatible allocators.
 //
+// - `_LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN` -- checks that the given argument 
is within the domain of valid arguments
+//   for the function. Violating this typically produces an incorrect result 
(e.g. the clamp algorithm returns the
+//   original value without clamping it due to incorrect functors) or puts an 
object into an invalid state (e.g.
+//   a string view where only a subset of elements is possible to access). 
This doesn't cause an immediate issue within
+//   the library but is always a logic bug and is likely to cause problems 
within user code.
+//   This is somewhat of a catch-all (or fallback) 

[clang] [clang-format] Add SpacesInParensOption for attributes and filtering for repeated parens (PR #77522)

2024-01-20 Thread Owen Pan via cfe-commits

owenca wrote:

> The code is [self-hosted](https://git.rtems.org/rtems/) and [mirrored on 
> GitHub](https://github.com/RTEMS/rtems) with a [documented style 
> guide](https://docs.rtems.org/branches/master/eng/coding-formatting.html). In 
> addition, I have been and will continue to be willing to provide bug fix and 
> other maintenance support to clang-format based on the changes submitted to 
> support these style needs.
> 
> At the moment, I need to satisfy a particular style rule that requires me to 
> add spaces inside of conditional and compound expressions.

It seems the RTEMS style guide you linked above doesn't have any examples for 
conditional expressions and compound expressions, and by _conditional 
expressions_ I assume it means conditionals of control statements rather than 
ternary [conditional 
expressions](https://www.ibm.com/docs/en/zos/3.1.0?topic=operators-conditional-expressions).

Would `__attribute__((noreturn))`, `if ((i = j))`, `decltype((x))`, and `while 
(((i + 1) * j - 2) * k > 3)` be formatted as `__attribute__(( noreturn ))`, `if 
(( i = j ))`, `decltype(( x ))`, and `while ( ( ( i + 1 ) * j - 2 ) * k > 3 )`, 
respectively?

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


[clang] [clang][analyzer][NFC] Simplify argument range in StdLibraryFunctionsChecker (PR #78886)

2024-01-20 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-static-analyzer-1

Author: Ben Shi (benshi001)


Changes



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


1 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
(+1-1) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index d0eb5091444f6b6..79bf0d0ec3c0249 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -2219,7 +2219,7 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
ArgumentCondition(0, WithinRange, {{0, UCharRangeMax}})},
   ErrnoMustNotBeChecked, GenericSuccessMsg)
 .Case({ReturnValueCondition(WithinRange, SingleValue(EOFv)),
-   ArgumentCondition(0, WithinRange, {{EOFv, EOFv}})},
+   ArgumentCondition(0, WithinRange, SingleValue(EOFv))},
   ErrnoNEZeroIrrelevant,
   "Assuming that 'ungetc' fails because EOF was passed as "
   "character")

``




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


[clang] [clang][analyzer][NFC] Simplify argument range in StdLibraryFunctionsChecker (PR #78886)

2024-01-20 Thread Ben Shi via cfe-commits

https://github.com/benshi001 created 
https://github.com/llvm/llvm-project/pull/78886

None

>From 7d0c3f5ce7f6a8d753bf6d5a2020baefeef35703 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Sun, 21 Jan 2024 15:20:24 +0800
Subject: [PATCH] [clang][analyzer][NFC] Simplify argument range in
 StdLibraryFunctionsChecker

---
 .../lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp  | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index d0eb5091444f6b..79bf0d0ec3c024 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -2219,7 +2219,7 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
ArgumentCondition(0, WithinRange, {{0, UCharRangeMax}})},
   ErrnoMustNotBeChecked, GenericSuccessMsg)
 .Case({ReturnValueCondition(WithinRange, SingleValue(EOFv)),
-   ArgumentCondition(0, WithinRange, {{EOFv, EOFv}})},
+   ArgumentCondition(0, WithinRange, SingleValue(EOFv))},
   ErrnoNEZeroIrrelevant,
   "Assuming that 'ungetc' fails because EOF was passed as "
   "character")

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


[libclc] libclc: add some missing AMD gfx9 and gfx10 symlinks (PR #78884)

2024-01-20 Thread Zoltán Böszörményi via cfe-commits

https://github.com/zboszor updated 
https://github.com/llvm/llvm-project/pull/78884

From 26e8eaaa9b0be1fdc146b5b4e8d285a2e8a2edbb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Zolt=C3=A1n=20B=C3=B6sz=C3=B6rm=C3=A9nyi?=
 
Date: Sun, 21 Jan 2024 07:59:02 +0100
Subject: [PATCH] libclc: add some missing AMD gfx9 and gfx10 symlinks
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Zoltán Böszörményi 
---
 libclc/CMakeLists.txt | 15 +++
 1 file changed, 15 insertions(+)

diff --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt
index 9daef8265c16f2..aa7acd4797602b 100644
--- a/libclc/CMakeLists.txt
+++ b/libclc/CMakeLists.txt
@@ -154,6 +154,21 @@ if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "6.99.99" )
set( tahiti_aliases ${tahiti_aliases} gfx904 gfx906 )
 endif()
 
+# Support for gfx909, gfx1010, gfx1011 and gfx1012 was added in LLVM 10 
(r345120)
+if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "9.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} gfx909 gfx1010 gfx1011 gfx1012 )
+endif()
+
+# Support for gfx908 was added in LLVM 11 (r373411)
+if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "10.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} gfx908 )
+endif()
+
+# Support for gfx90c, gfx1030, gfx1031, gfx1032, gfx1033 was added in LLVM 12
+if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "11.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} gfx90c gfx1030 gfx1031 gfx1032 
gfx1033 )
+endif()
+
 # pkg-config file
 configure_file( libclc.pc.in libclc.pc @ONLY )
 install( FILES ${CMAKE_CURRENT_BINARY_DIR}/libclc.pc DESTINATION 
"${CMAKE_INSTALL_DATADIR}/pkgconfig" )

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


[libclc] libclc: add some missing AMD gfx9 and gfx10 symlinks (PR #78884)

2024-01-20 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/78884
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libclc] libclc: add some missing AMD gfx9 and gfx10 symlinks (PR #78884)

2024-01-20 Thread Zoltán Böszörményi via cfe-commits

https://github.com/zboszor created 
https://github.com/llvm/llvm-project/pull/78884

Fixes #44186 

From fc8990d5fdfa07ea389fbb4682f06fc7d54d28c2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Zolt=C3=A1n=20B=C3=B6sz=C3=B6rm=C3=A9nyi?=
 
Date: Sun, 21 Jan 2024 07:59:02 +0100
Subject: [PATCH] libclc: add some missing AMD gfx9 and gfx10 symlinks
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Signed-off-by: Zoltán Böszörményi 
---
 libclc/CMakeLists.txt | 15 +++
 1 file changed, 15 insertions(+)

diff --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt
index 9daef8265c16f2..f0ac9914073a48 100644
--- a/libclc/CMakeLists.txt
+++ b/libclc/CMakeLists.txt
@@ -154,6 +154,21 @@ if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "6.99.99" )
set( tahiti_aliases ${tahiti_aliases} gfx904 gfx906 )
 endif()
 
+# Support for gfx909, gfx1010, gfx1011 and gfx1012 was added in LLVM 10 
(r345120)
+if( ${LLVM_VERSION} VERSION_GREATER "9.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} gfx909 gfx1010 gfx1011 gfx1012 )
+endif()
+
+# Support for gfx908 was added in LLVM 11 (r373411)
+if( ${LLVM_VERSION} VERSION_GREATER "10.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} gfx908 )
+endif()
+
+# Support for gfx90c, gfx1030, gfx1031, gfx1032, gfx1033 was added in LLVM 12
+if( ${LLVM_VERSION} VERSION_GREATER "11.99.99" )
+   set( tahiti_aliases ${tahiti_aliases} gfx90c gfx1030 gfx1031 gfx1032 
gfx1033 )
+endif()
+
 # pkg-config file
 configure_file( libclc.pc.in libclc.pc @ONLY )
 install( FILES ${CMAKE_CURRENT_BINARY_DIR}/libclc.pc DESTINATION 
"${CMAKE_INSTALL_DATADIR}/pkgconfig" )

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


[llvm] [clang] [CMake][PGO] Build Sema.cpp to generate profdata for PGO builds (PR #77347)

2024-01-20 Thread Tom Stellard via cfe-commits

tstellar wrote:

I split the new configuration option out into a separate PR: #78879, because it 
seems useful regardless of what the default is.  We can continue to discuss the 
best default on this PR.

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


[llvm] [clang] [CMake][PGO] Add option for using an external project to generate profile data (PR #78879)

2024-01-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Tom Stellard (tstellar)


Changes

 The new CLANG_PGO_TRAINING_DATA_SOURCE_DIR allows users to specify a CMake 
project to use for generating the profile data.  For example, to use the 
llvm-test-suite to generate profile data you would do:

$ cmake -G Ninja -B build -S llvm -C path to 
source/clang/cmake/caches/PGO.cmake \ 
-DBOOTSTRAP_CLANG_PGO_TRAINING_DATA_SOURCE_DIR=path to 
llvm-test-suite \
-DBOOTSTRAP_CLANG_PERF_TRAINING_DEPS=runtimes


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


4 Files Affected:

- (modified) clang/cmake/caches/PGO.cmake (+1-1) 
- (modified) clang/utils/perf-training/CMakeLists.txt (+11-2) 
- (modified) clang/utils/perf-training/perf-helper.py (+9-7) 
- (modified) llvm/docs/AdvancedBuilds.rst (+23) 


``diff
diff --git a/clang/cmake/caches/PGO.cmake b/clang/cmake/caches/PGO.cmake
index e1d0585e453f825..15bc755d110d19a 100644
--- a/clang/cmake/caches/PGO.cmake
+++ b/clang/cmake/caches/PGO.cmake
@@ -2,7 +2,7 @@ set(CMAKE_BUILD_TYPE RELEASE CACHE STRING "")
 set(CLANG_ENABLE_BOOTSTRAP ON CACHE BOOL "")
 
 set(LLVM_ENABLE_PROJECTS "clang;lld" CACHE STRING "")
-set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi" CACHE STRING "")
+set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING 
"")
 
 set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
 set(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED ON CACHE BOOL "")
diff --git a/clang/utils/perf-training/CMakeLists.txt 
b/clang/utils/perf-training/CMakeLists.txt
index c6d51863fb1b5c2..f9d673b2e92e775 100644
--- a/clang/utils/perf-training/CMakeLists.txt
+++ b/clang/utils/perf-training/CMakeLists.txt
@@ -1,6 +1,10 @@
+include(LLVMExternalProjectUtils)
+
 set(CLANG_PGO_TRAINING_DATA "${CMAKE_CURRENT_SOURCE_DIR}" CACHE PATH
   "The path to a lit testsuite containing samples for PGO and order file 
generation"
   )
+set(CLANG_PGO_TRAINING_DATA_SOURCE_DIR OFF CACHE STRING "Path to source 
directory containing cmake project with source files to use for generating pgo 
data")
+set(CLANG_PERF_TRAINING_DEPS "" CACHE STRING "Extra dependencies needed to 
build the PGO training data.")
 
 if(LLVM_BUILD_INSTRUMENTED)
   configure_lit_site_cfg(
@@ -15,7 +19,7 @@ if(LLVM_BUILD_INSTRUMENTED)
 )
 
   add_custom_target(clear-profraw
-COMMAND "${Python3_EXECUTABLE}" ${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py 
clean ${CMAKE_CURRENT_BINARY_DIR} profraw
+COMMAND "${Python3_EXECUTABLE}" ${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py 
clean ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_BINARY_DIR}/profiles/ profraw
 COMMENT "Clearing old profraw data")
 
   if(NOT LLVM_PROFDATA)
@@ -26,9 +30,14 @@ if(LLVM_BUILD_INSTRUMENTED)
 message(STATUS "To enable merging PGO data LLVM_PROFDATA has to point to 
llvm-profdata")
   else()
 add_custom_target(generate-profdata
-  COMMAND "${Python3_EXECUTABLE}" 
${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py merge ${LLVM_PROFDATA} 
${CMAKE_CURRENT_BINARY_DIR}/clang.profdata ${CMAKE_CURRENT_BINARY_DIR}
+  COMMAND "${Python3_EXECUTABLE}" 
${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py merge ${LLVM_PROFDATA} 
${CMAKE_CURRENT_BINARY_DIR}/clang.profdata ${CMAKE_CURRENT_BINARY_DIR} 
${CMAKE_BINARY_DIR}/profiles/
   COMMENT "Merging profdata"
   DEPENDS generate-profraw)
+if (CLANG_PGO_TRAINING_DATA_SOURCE_DIR)
+  llvm_ExternalProject_Add(generate-profraw-external 
${CLANG_PGO_TRAINING_DATA_SOURCE_DIR}
+  USE_TOOLCHAIN EXLUDE_FROM_ALL NO_INSTALL DEPENDS 
generate-profraw)
+  add_dependencies(generate-profdata generate-profraw-external)
+endif()
   endif()
 endif()
 
diff --git a/clang/utils/perf-training/perf-helper.py 
b/clang/utils/perf-training/perf-helper.py
index 99d6ab6ef08..844aa274f049aaa 100644
--- a/clang/utils/perf-training/perf-helper.py
+++ b/clang/utils/perf-training/perf-helper.py
@@ -30,26 +30,28 @@ def findFilesWithExtension(path, extension):
 
 
 def clean(args):
-if len(args) != 2:
+if len(args) < 2:
 print(
-"Usage: %s clean  \n" % __file__
+"Usage: %s clean  \n" % __file__
 + "\tRemoves all files with extension from ."
 )
 return 1
-for filename in findFilesWithExtension(args[0], args[1]):
-os.remove(filename)
+for path in args[1:-1]:
+for filename in findFilesWithExtension(path, args[-1]):
+os.remove(filename)
 return 0
 
 
 def merge(args):
-if len(args) != 3:
+if len(args) < 3:
 print(
-"Usage: %s merge   \n" % __file__
+"Usage: %s merge   \n" % __file__
 + "\tMerges all profraw files from path into output."
 )
 return 1
 cmd = [args[0], "merge", "-o", args[1]]
-cmd.extend(findFilesWithExtension(args[2], "profraw"))
+for i in range(2, len(args)):
+cmd.extend(findFilesWithExtension(args[i], "profraw"))
 subprocess.check_call(cmd)
 return 0
 
diff 

[llvm] [clang] [CMake][PGO] Add option for using an external project to generate profile data (PR #78879)

2024-01-20 Thread Tom Stellard via cfe-commits

https://github.com/tstellar created 
https://github.com/llvm/llvm-project/pull/78879

 The new CLANG_PGO_TRAINING_DATA_SOURCE_DIR allows users to specify a CMake 
project to use for generating the profile data.  For example, to use the 
llvm-test-suite to generate profile data you would do:

$ cmake -G Ninja -B build -S llvm -C /clang/cmake/caches/PGO.cmake \ 
-DBOOTSTRAP_CLANG_PGO_TRAINING_DATA_SOURCE_DIR= \
-DBOOTSTRAP_CLANG_PERF_TRAINING_DEPS=runtimes


>From 0719f49ecc6dd69ae4698c3e84dbf175a1bf2ed3 Mon Sep 17 00:00:00 2001
From: Tom Stellard 
Date: Sun, 21 Jan 2024 00:25:47 +
Subject: [PATCH 1/2] [CMake][PGO] Add libunwind to list of stage1 runtimes

This fixes the build since 8f90e6937a1fac80873bb2dab5f382c82ba1ba4e
which made libcxxabi use llvm's libunwind by default.
---
 clang/cmake/caches/PGO.cmake | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/cmake/caches/PGO.cmake b/clang/cmake/caches/PGO.cmake
index e1d0585e453f825..15bc755d110d19a 100644
--- a/clang/cmake/caches/PGO.cmake
+++ b/clang/cmake/caches/PGO.cmake
@@ -2,7 +2,7 @@ set(CMAKE_BUILD_TYPE RELEASE CACHE STRING "")
 set(CLANG_ENABLE_BOOTSTRAP ON CACHE BOOL "")
 
 set(LLVM_ENABLE_PROJECTS "clang;lld" CACHE STRING "")
-set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi" CACHE STRING "")
+set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING 
"")
 
 set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
 set(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED ON CACHE BOOL "")

>From 5c602233ef4e54e850f6c8a17c25968bc706b898 Mon Sep 17 00:00:00 2001
From: Tom Stellard 
Date: Sat, 6 Jan 2024 07:46:01 +
Subject: [PATCH 2/2] [CMake][PGO] Add option for using an external project to
 generate profile data.

The new CLANG_PGO_TRAINING_DATA_SOURCE_DIR allows users to specify a CMake
project to use for generating the profile data.

For example, to use the llvm-test-suite to generate profile data you
would do:

$ cmake -G Ninja -B build -S llvm -C /clang/cmake/caches/PGO.cmake \
-DBOOTSTRAP_CLANG_PGO_TRAINING_DATA_SOURCE_DIR= \
-DBOOTSTRAP_CLANG_PERF_TRAINING_DEPS=runtimes
---
 clang/utils/perf-training/CMakeLists.txt | 13 +++--
 clang/utils/perf-training/perf-helper.py | 16 +---
 llvm/docs/AdvancedBuilds.rst | 23 +++
 3 files changed, 43 insertions(+), 9 deletions(-)

diff --git a/clang/utils/perf-training/CMakeLists.txt 
b/clang/utils/perf-training/CMakeLists.txt
index c6d51863fb1b5c2..f9d673b2e92e775 100644
--- a/clang/utils/perf-training/CMakeLists.txt
+++ b/clang/utils/perf-training/CMakeLists.txt
@@ -1,6 +1,10 @@
+include(LLVMExternalProjectUtils)
+
 set(CLANG_PGO_TRAINING_DATA "${CMAKE_CURRENT_SOURCE_DIR}" CACHE PATH
   "The path to a lit testsuite containing samples for PGO and order file 
generation"
   )
+set(CLANG_PGO_TRAINING_DATA_SOURCE_DIR OFF CACHE STRING "Path to source 
directory containing cmake project with source files to use for generating pgo 
data")
+set(CLANG_PERF_TRAINING_DEPS "" CACHE STRING "Extra dependencies needed to 
build the PGO training data.")
 
 if(LLVM_BUILD_INSTRUMENTED)
   configure_lit_site_cfg(
@@ -15,7 +19,7 @@ if(LLVM_BUILD_INSTRUMENTED)
 )
 
   add_custom_target(clear-profraw
-COMMAND "${Python3_EXECUTABLE}" ${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py 
clean ${CMAKE_CURRENT_BINARY_DIR} profraw
+COMMAND "${Python3_EXECUTABLE}" ${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py 
clean ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_BINARY_DIR}/profiles/ profraw
 COMMENT "Clearing old profraw data")
 
   if(NOT LLVM_PROFDATA)
@@ -26,9 +30,14 @@ if(LLVM_BUILD_INSTRUMENTED)
 message(STATUS "To enable merging PGO data LLVM_PROFDATA has to point to 
llvm-profdata")
   else()
 add_custom_target(generate-profdata
-  COMMAND "${Python3_EXECUTABLE}" 
${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py merge ${LLVM_PROFDATA} 
${CMAKE_CURRENT_BINARY_DIR}/clang.profdata ${CMAKE_CURRENT_BINARY_DIR}
+  COMMAND "${Python3_EXECUTABLE}" 
${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py merge ${LLVM_PROFDATA} 
${CMAKE_CURRENT_BINARY_DIR}/clang.profdata ${CMAKE_CURRENT_BINARY_DIR} 
${CMAKE_BINARY_DIR}/profiles/
   COMMENT "Merging profdata"
   DEPENDS generate-profraw)
+if (CLANG_PGO_TRAINING_DATA_SOURCE_DIR)
+  llvm_ExternalProject_Add(generate-profraw-external 
${CLANG_PGO_TRAINING_DATA_SOURCE_DIR}
+  USE_TOOLCHAIN EXLUDE_FROM_ALL NO_INSTALL DEPENDS 
generate-profraw)
+  add_dependencies(generate-profdata generate-profraw-external)
+endif()
   endif()
 endif()
 
diff --git a/clang/utils/perf-training/perf-helper.py 
b/clang/utils/perf-training/perf-helper.py
index 99d6ab6ef08..844aa274f049aaa 100644
--- a/clang/utils/perf-training/perf-helper.py
+++ b/clang/utils/perf-training/perf-helper.py
@@ -30,26 +30,28 @@ def findFilesWithExtension(path, extension):
 
 
 def clean(args):
-if len(args) != 2:
+if len(args) < 2:
 print(
-"Usage: %s clean  

[lld] [libcxx] [mlir] [lldb] [flang] [clang] [llvm] [clang-tools-extra] [compiler-rt] [clang-format] Add ShortReturnTypeColumn option. (PR #78011)

2024-01-20 Thread via cfe-commits

rmarker wrote:

@mydeveloperday, do you have an opinion on this pull request?
It addresses #78010 with minimal changes, or are you interested in exploring 
other possibilities?

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


[flang] [clang] [llvm] [clang-tools-extra] [lldb] [lld] [openmp] [compiler-rt] [libc] [mlir] [libcxx] [libc++][variant] P2637R3: Member `visit` (`std::variant`) (PR #76447)

2024-01-20 Thread Hristo Hristov via cfe-commits

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


[flang] [clang] [llvm] [clang-tools-extra] [lldb] [lld] [openmp] [compiler-rt] [libc] [mlir] [libcxx] [libc++][variant] P2637R3: Member `visit` (`std::variant`) (PR #76447)

2024-01-20 Thread Hristo Hristov via cfe-commits

Zingam wrote:

The FreeBSD CI failure is unrelated and should be fixed upstream. Merging.

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


[flang] [clang] [llvm] [lld] [clang-tools-extra] [lldb] [mlir] [compiler-rt] [libcxx] [clang-format] Add ShortReturnTypeColumn option. (PR #78011)

2024-01-20 Thread via cfe-commits

rmarker wrote:

Merged main and fixed conflicts.

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


[flang] [clang] [llvm] [lld] [clang-tools-extra] [lldb] [mlir] [compiler-rt] [libcxx] [clang-format] Add ShortReturnTypeColumn option. (PR #78011)

2024-01-20 Thread via cfe-commits

https://github.com/rmarker updated 
https://github.com/llvm/llvm-project/pull/78011

>From c4d28f82e108f9f12ccd0375e2a3502025b8c1e8 Mon Sep 17 00:00:00 2001
From: rmarker 
Date: Thu, 11 Jan 2024 15:01:18 +1030
Subject: [PATCH 1/3] [clang-format] Add ShortReturnTypeLength option.

---
 clang/docs/ClangFormatStyleOptions.rst |  8 
 clang/docs/ReleaseNotes.rst|  1 +
 clang/include/clang/Format/Format.h|  8 
 clang/lib/Format/ContinuationIndenter.cpp  |  3 +-
 clang/lib/Format/Format.cpp|  2 +
 clang/unittests/Format/ConfigParseTest.cpp |  1 +
 clang/unittests/Format/FormatTest.cpp  | 44 ++
 7 files changed, 66 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index ac9a0b70ed5daa4..3255ceb0aba75b4 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -4994,6 +4994,14 @@ the configuration (without a prefix: ``Auto``).
int bar;   int bar;
  } // namespace b   } // namespace b
 
+.. _ShortReturnTypeLength:
+
+**ShortReturnTypeLength** (``Unsigned``) :versionbadge:`clang-format 18` 
:ref:`¶ `
+  When AlwaysBreakAfterReturnType is None, line breaks are prevented after
+  short return types. This configures the character limit for a type to be
+  regarded as short. Note that this isn't the length of the type itself,
+  but the column where it finishes. I.e. it includes indentation, etc.
+
 .. _SortIncludes:
 
 **SortIncludes** (``SortIncludesOptions``) :versionbadge:`clang-format 3.8` 
:ref:`¶ `
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3cbce1be1594376..04bf5cd4e768f34 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1131,6 +1131,7 @@ clang-format
 - Add ``BreakAdjacentStringLiterals`` option.
 - Add ``ObjCPropertyAttributeOrder`` which can be used to sort ObjC property
   attributes (like ``nonatomic, strong, nullable``).
+- Add ``ShortReturnTypeLength`` option.
 - Add ``.clang-format-ignore`` files.
 - Add ``AlignFunctionPointers`` sub-option for 
``AlignConsecutiveDeclarations``.
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 5ffd63ee73fc361..f94d68f2cf2a853 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -3928,6 +3928,13 @@ struct FormatStyle {
   /// \version 13
   unsigned ShortNamespaceLines;
 
+  /// When AlwaysBreakAfterReturnType is None, line breaks are prevented after
+  /// short return types. This configures the character limit for a type to be
+  /// regarded as short. Note that this isn't the length of the type itself,
+  /// but the column where it finishes. I.e. it includes indentation, etc.
+  /// \version 18
+  unsigned ShortReturnTypeLength;
+
   /// Include sorting options.
   enum SortIncludesOptions : int8_t {
 /// Includes are never sorted.
@@ -4890,6 +4897,7 @@ struct FormatStyle {
RequiresExpressionIndentation == R.RequiresExpressionIndentation &&
SeparateDefinitionBlocks == R.SeparateDefinitionBlocks &&
ShortNamespaceLines == R.ShortNamespaceLines &&
+   ShortReturnTypeLength == R.ShortReturnTypeLength &&
SortIncludes == R.SortIncludes &&
SortJavaStaticImport == R.SortJavaStaticImport &&
SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 102504182c4505b..bc0748ec52e6769 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -328,7 +328,8 @@ bool ContinuationIndenter::canBreak(const LineState ) 
{
 
   // Don't break after very short return types (e.g. "void") as that is often
   // unexpected.
-  if (Current.is(TT_FunctionDeclarationName) && State.Column < 6) {
+  if (Current.is(TT_FunctionDeclarationName) &&
+  State.Column <= Style.ShortReturnTypeLength) {
 if (Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None)
   return false;
   }
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index ff5ed6c306f383b..20ffbeef7e9a6e9 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1083,6 +1083,7 @@ template <> struct MappingTraits {
Style.RequiresExpressionIndentation);
 IO.mapOptional("SeparateDefinitionBlocks", Style.SeparateDefinitionBlocks);
 IO.mapOptional("ShortNamespaceLines", Style.ShortNamespaceLines);
+IO.mapOptional("ShortReturnTypeLength", Style.ShortReturnTypeLength);
 IO.mapOptional("SortIncludes", Style.SortIncludes);
 IO.mapOptional("SortJavaStaticImport", Style.SortJavaStaticImport);
 IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
@@ -1554,6 +1555,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 

[clang] [libclang/python] Expose Rewriter to the python binding (PR #77269)

2024-01-20 Thread Jimmy Z via cfe-commits

jimmy-zx wrote:

> Looks good overall. It's good that you wrote your own tests, but it would 
> also be nice to mirror tests in `clang/unittests/libclang/LibclangTest.cpp` 
> which test the same API. This way we can identify issues in binding layer 
> itself (when C++ tests pass, but Python tests don't, or vise versa,)

I have reviewed the tests for libclang and it appears that there are already 
tests for the rewriter, which are more extensive than the ones I wrote. 
Therefore, I have decided to mirror the tests from libclang in the Python 
binding. Please let me know if this approach is appropriate.

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


[clang] [libclang/python] Expose Rewriter to the python binding (PR #77269)

2024-01-20 Thread Jimmy Z via cfe-commits

https://github.com/jimmy-zx updated 
https://github.com/llvm/llvm-project/pull/77269

>From a5379ca876d9531d48b37b9ad9c864db98c7dcd6 Mon Sep 17 00:00:00 2001
From: Jimmy Z <51149050+jimmy...@users.noreply.github.com>
Date: Mon, 8 Jan 2024 04:36:27 +
Subject: [PATCH 1/3] [libclang/python] Expose Rewriter to the python binding

---
 clang/bindings/python/clang/cindex.py | 62 +++
 .../python/tests/cindex/test_rewrite.py   | 75 +++
 2 files changed, 137 insertions(+)
 create mode 100644 clang/bindings/python/tests/cindex/test_rewrite.py

diff --git a/clang/bindings/python/clang/cindex.py 
b/clang/bindings/python/clang/cindex.py
index d780ee353a133c..ced449180d98fc 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -3531,6 +3531,61 @@ def cursor(self):
 return cursor
 
 
+class Rewriter(ClangObject):
+"""
+The Rewriter is a wrapper class around clang::Rewriter
+
+It enables rewriting buffers.
+"""
+
+@staticmethod
+def create(tu):
+"""
+Creates a new Rewriter
+Parameters:
+tu -- The translation unit for the target AST.
+"""
+return Rewriter(conf.lib.clang_CXRewriter_create(tu))
+
+def __init__(self, ptr):
+ClangObject.__init__(self, ptr)
+
+def __del__(self):
+conf.lib.clang_CXRewriter_dispose(self)
+
+def insertTextBefore(self, loc, insert):
+"""
+Insert the specified string at the specified location in the original 
buffer.
+"""
+conf.lib.clang_CXRewriter_insertTextBefore(self, loc, insert)
+
+def replaceText(self, toBeReplaced, replacement):
+"""
+This method replaces a range of characters in the input buffer with a 
new string.
+"""
+conf.lib.clang_CXRewriter_replaceText(self, toBeReplaced, replacement)
+
+def removeText(self, toBeRemoved):
+"""
+Remove the specified text region.
+"""
+conf.lib.clang_CXRewriter_removeText(self, toBeRemoved)
+
+def overwriteChangedFiles(self):
+"""
+Save all changed files to disk.
+
+Returns 1 if any files were not saved successfully, returns 0 
otherwise.
+"""
+return conf.lib.clang_CXRewriter_overwriteChangedFiles(self)
+
+def writeMainFileToStdOut(self):
+"""
+Writes the main file to stdout.
+"""
+conf.lib.clang_CXRewriter_writeMainFileToStdOut(self)
+
+
 # Now comes the plumbing to hook up the C library.
 
 # Register callback types in common container.
@@ -3596,6 +3651,13 @@ def cursor(self):
 ("clang_codeCompleteGetNumDiagnostics", [CodeCompletionResults], c_int),
 ("clang_createIndex", [c_int, c_int], c_object_p),
 ("clang_createTranslationUnit", [Index, c_interop_string], c_object_p),
+("clang_CXRewriter_create", [TranslationUnit], c_object_p),
+("clang_CXRewriter_dispose", [Rewriter]),
+("clang_CXRewriter_insertTextBefore", [Rewriter, SourceLocation, 
c_interop_string]),
+("clang_CXRewriter_overwriteChangedFiles", [Rewriter], c_int),
+("clang_CXRewriter_removeText", [Rewriter, SourceRange]),
+("clang_CXRewriter_replaceText", [Rewriter, SourceRange, 
c_interop_string]),
+("clang_CXRewriter_writeMainFileToStdOut", [Rewriter]),
 ("clang_CXXConstructor_isConvertingConstructor", [Cursor], bool),
 ("clang_CXXConstructor_isCopyConstructor", [Cursor], bool),
 ("clang_CXXConstructor_isDefaultConstructor", [Cursor], bool),
diff --git a/clang/bindings/python/tests/cindex/test_rewrite.py 
b/clang/bindings/python/tests/cindex/test_rewrite.py
new file mode 100644
index 00..2c5f904ce50bdc
--- /dev/null
+++ b/clang/bindings/python/tests/cindex/test_rewrite.py
@@ -0,0 +1,75 @@
+import sys
+import io
+import unittest
+import tempfile
+
+from clang.cindex import (
+Rewriter,
+TranslationUnit,
+Config,
+File,
+SourceLocation,
+SourceRange,
+)
+
+
+class TestRewrite(unittest.TestCase):
+code = """
+int test1;
+
+void test2(void);
+
+int f(int c) {
+return c;
+}
+"""
+
+def setUp(self):
+self.tmp = tempfile.NamedTemporaryFile(suffix=".cpp", buffering=0)
+self.tmp.write(TestRewrite.code.encode("utf-8"))
+self.tmp.flush()
+self.tu = TranslationUnit.from_source(self.tmp.name)
+self.rew = Rewriter.create(self.tu)
+self.file = File.from_name(self.tu, self.tmp.name)
+
+def tearDown(self):
+self.tmp.close()
+
+def test_insert(self):
+snip = "#include \n"
+
+beginning = SourceLocation.from_offset(self.tu, self.file, 0)
+self.rew.insertTextBefore(beginning, snip)
+self.rew.overwriteChangedFiles()
+
+with open(self.tmp.name, "r", encoding="utf-8") as f:
+self.assertEqual(f.read(), snip + TestRewrite.code)
+
+def test_replace(self):
+pattern = "test2"
+replacement = "func"
+
+

[clang] [Clang][Sema] Diagnose function/variable templates that shadow their own template parameters (PR #78274)

2024-01-20 Thread David Blaikie via cfe-commits

dwblaikie wrote:

> @zmodem template parameter shadowing is an extension with 
> `-fms-compatibility`, if that works

Given the prevalence (wellr, given how quickly folks have tripped over it 
probably indicates it's fairly prevalent), I think it'll need to be/should be 
pulled out into its own warning group (which can be a default error) for now at 
least.

Probably worth reverting while the right path forward is discussed further?

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


[clang-tools-extra] [clang] [clangd] Add support to rename Objective-C selectors (PR #78872)

2024-01-20 Thread Alex Hoppen via cfe-commits

https://github.com/ahoppen updated 
https://github.com/llvm/llvm-project/pull/78872

>From 26d9d1a5a342df34cde921f7d9921e7b94dadd87 Mon Sep 17 00:00:00 2001
From: Alex Hoppen 
Date: Tue, 19 Dec 2023 15:54:40 -0800
Subject: [PATCH 1/5] [Refactoring] Add capabilities to `SymbolName` to
 represent Objective-C selector names

---
 .../Tooling/Refactoring/Rename/SymbolName.h   | 30 +++-
 clang/lib/Tooling/Refactoring/CMakeLists.txt  |  1 +
 .../Refactoring/Rename/RenamingAction.cpp |  4 +-
 .../Refactoring/Rename/USRLocFinder.cpp   |  4 +-
 clang/lib/Tooling/Refactoring/SymbolName.cpp  | 46 +++
 clang/tools/clang-rename/CMakeLists.txt   |  1 +
 6 files changed, 70 insertions(+), 16 deletions(-)
 create mode 100644 clang/lib/Tooling/Refactoring/SymbolName.cpp

diff --git a/clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h 
b/clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h
index 6c28d40f3679c2..077f315f657e77 100644
--- a/clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h
+++ b/clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h
@@ -15,6 +15,9 @@
 #include "llvm/ADT/StringRef.h"
 
 namespace clang {
+
+class LangOptions;
+
 namespace tooling {
 
 /// A name of a symbol.
@@ -27,19 +30,22 @@ namespace tooling {
 /// //   ^~ string 0 ~ ^~ string 1 ~
 /// \endcode
 class SymbolName {
+  llvm::SmallVector NamePieces;
+
 public:
-  explicit SymbolName(StringRef Name) {
-// While empty symbol names are valid (Objective-C selectors can have empty
-// name pieces), occurrences Objective-C selectors are created using an
-// array of strings instead of just one string.
-assert(!Name.empty() && "Invalid symbol name!");
-this->Name.push_back(Name.str());
-  }
-
-  ArrayRef getNamePieces() const { return Name; }
-
-private:
-  llvm::SmallVector Name;
+  /// Create a new \c SymbolName with the specified pieces.
+  explicit SymbolName(ArrayRef NamePieces);
+
+  /// Creates a \c SymbolName from the given string representation.
+  ///
+  /// For Objective-C symbol names, this splits a selector into multiple pieces
+  /// on `:`. For all other languages the name is used as the symbol name.
+  SymbolName(StringRef Name, bool IsObjectiveCSelector);
+  SymbolName(StringRef Name, const LangOptions );
+
+  ArrayRef getNamePieces() const { return NamePieces; }
+
+  void print(raw_ostream ) const;
 };
 
 } // end namespace tooling
diff --git a/clang/lib/Tooling/Refactoring/CMakeLists.txt 
b/clang/lib/Tooling/Refactoring/CMakeLists.txt
index d3077be8810aad..a4a80ce8344313 100644
--- a/clang/lib/Tooling/Refactoring/CMakeLists.txt
+++ b/clang/lib/Tooling/Refactoring/CMakeLists.txt
@@ -13,6 +13,7 @@ add_clang_library(clangToolingRefactoring
   Rename/USRFinder.cpp
   Rename/USRFindingAction.cpp
   Rename/USRLocFinder.cpp
+  SymbolName.cpp
 
   LINK_LIBS
   clangAST
diff --git a/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp 
b/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
index 72598601d47d67..4965977d1f7aa4 100644
--- a/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
+++ b/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
@@ -82,7 +82,7 @@ 
RenameOccurrences::createSourceReplacements(RefactoringRuleContext ) {
   if (!Occurrences)
 return Occurrences.takeError();
   // FIXME: Verify that the new name is valid.
-  SymbolName Name(NewName);
+  SymbolName Name(NewName, /*IsObjectiveCSelector=*/false);
   return createRenameReplacements(
   *Occurrences, Context.getASTContext().getSourceManager(), Name);
 }
@@ -219,7 +219,7 @@ class RenamingASTConsumer : public ASTConsumer {
 }
 // FIXME: Support multi-piece names.
 // FIXME: better error handling (propagate error out).
-SymbolName NewNameRef(NewName);
+SymbolName NewNameRef(NewName, /*IsObjectiveCSelector=*/false);
 Expected> Change =
 createRenameReplacements(Occurrences, SourceMgr, NewNameRef);
 if (!Change) {
diff --git a/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp 
b/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
index c18f9290471fe4..43e48f24caa9ea 100644
--- a/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
+++ b/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
@@ -60,8 +60,8 @@ class USRLocFindingASTVisitor
const ASTContext )
   : RecursiveSymbolVisitor(Context.getSourceManager(),
Context.getLangOpts()),
-USRSet(USRs.begin(), USRs.end()), PrevName(PrevName), Context(Context) 
{
-  }
+USRSet(USRs.begin(), USRs.end()),
+PrevName(PrevName, /*IsObjectiveCSelector=*/false), Context(Context) {}
 
   bool visitSymbolOccurrence(const NamedDecl *ND,
  ArrayRef NameRanges) {
diff --git a/clang/lib/Tooling/Refactoring/SymbolName.cpp 
b/clang/lib/Tooling/Refactoring/SymbolName.cpp
new file mode 100644
index 00..7fd50b2c4df7bd
--- /dev/null
+++ 

[clang] f523a55 - [Sema] Use llvm::all_of (NFC)

2024-01-20 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2024-01-20T18:57:35-08:00
New Revision: f523a5522be221e4657daa111431106083e1c053

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

LOG: [Sema] Use llvm::all_of (NFC)

Added: 


Modified: 
clang/lib/Sema/Sema.cpp

Removed: 




diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 70832d1a14552d..2d4e6d1d058cd7 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -2758,7 +2758,7 @@ bool Sema::isDeclaratorFunctionLike(Declarator ) {
 return false;
 
   LookupQualifiedName(LR, DC);
-  bool Result = std::all_of(LR.begin(), LR.end(), [](Decl *Dcl) {
+  bool Result = llvm::all_of(LR, [](Decl *Dcl) {
 if (NamedDecl *ND = dyn_cast(Dcl)) {
   ND = ND->getUnderlyingDecl();
   return isa(ND) || isa(ND) ||



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


[clang] 9b2c25c - [clang] Use SmallString::operator std::string (NFC)

2024-01-20 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2024-01-20T18:57:30-08:00
New Revision: 9b2c25c70466d6f081a2915e661840f965b6056a

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

LOG: [clang] Use SmallString::operator std::string (NFC)

Added: 


Modified: 
clang/lib/ARCMigrate/FileRemapper.cpp
clang/lib/ARCMigrate/ObjCMT.cpp
clang/lib/AST/Expr.cpp
clang/lib/AST/Mangle.cpp
clang/lib/Basic/FileManager.cpp
clang/lib/CodeGen/CGCUDANV.cpp
clang/lib/CrossTU/CrossTranslationUnit.cpp
clang/lib/Lex/ModuleMap.cpp
clang/lib/Tooling/ASTDiff/ASTDiff.cpp
clang/lib/Tooling/CompilationDatabase.cpp
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
clang/lib/Tooling/Tooling.cpp
clang/utils/TableGen/ClangAttrEmitter.cpp
clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
clang/utils/TableGen/MveEmitter.cpp

Removed: 




diff  --git a/clang/lib/ARCMigrate/FileRemapper.cpp 
b/clang/lib/ARCMigrate/FileRemapper.cpp
index 7abc862ceecc237..84024c3bafdca01 100644
--- a/clang/lib/ARCMigrate/FileRemapper.cpp
+++ b/clang/lib/ARCMigrate/FileRemapper.cpp
@@ -43,7 +43,7 @@ std::string FileRemapper::getRemapInfoFile(StringRef 
outputDir) {
   assert(!outputDir.empty());
   SmallString<128> InfoFile = outputDir;
   llvm::sys::path::append(InfoFile, "remap");
-  return std::string(InfoFile.str());
+  return std::string(InfoFile);
 }
 
 bool FileRemapper::initFromDisk(StringRef outputDir, DiagnosticsEngine ,

diff  --git a/clang/lib/ARCMigrate/ObjCMT.cpp b/clang/lib/ARCMigrate/ObjCMT.cpp
index ed363a46a200443..0786c81516b2d14 100644
--- a/clang/lib/ARCMigrate/ObjCMT.cpp
+++ b/clang/lib/ARCMigrate/ObjCMT.cpp
@@ -2201,7 +2201,7 @@ static std::string applyEditsToTemp(FileEntryRef FE,
   TmpOut.write(NewText.data(), NewText.size());
   TmpOut.close();
 
-  return std::string(TempPath.str());
+  return std::string(TempPath);
 }
 
 bool arcmt::getFileRemappingsFromFileList(

diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index ade403da65dd959..f1efa98e175edf5 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -690,7 +690,7 @@ std::string PredefinedExpr::ComputeName(PredefinedIdentKind 
IK,
 
 if (!Buffer.empty() && Buffer.front() == '\01')
   return std::string(Buffer.substr(1));
-return std::string(Buffer.str());
+return std::string(Buffer);
   }
   return std::string(ND->getIdentifier()->getName());
 }
@@ -986,7 +986,7 @@ std::string FixedPointLiteral::getValueAsString(unsigned 
Radix) const {
   SmallString<64> S;
   FixedPointValueToString(
   S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
-  return std::string(S.str());
+  return std::string(S);
 }
 
 void CharacterLiteral::print(unsigned Val, CharacterLiteralKind Kind,

diff  --git a/clang/lib/AST/Mangle.cpp b/clang/lib/AST/Mangle.cpp
index d3a6b61fd2bec9c..30cff1ba2e6f379 100644
--- a/clang/lib/AST/Mangle.cpp
+++ b/clang/lib/AST/Mangle.cpp
@@ -464,7 +464,7 @@ class ASTNameGenerator::Implementation {
   SmallString<40> Mangled;
   auto Prefix = getClassSymbolPrefix(Kind, OCD->getASTContext());
   llvm::Mangler::getNameWithPrefix(Mangled, Prefix + ClassName, DL);
-  return std::string(Mangled.str());
+  return std::string(Mangled);
 };
 
 return {

diff  --git a/clang/lib/Basic/FileManager.cpp b/clang/lib/Basic/FileManager.cpp
index d16626b10652136..974c8c22598f630 100644
--- a/clang/lib/Basic/FileManager.cpp
+++ b/clang/lib/Basic/FileManager.cpp
@@ -532,7 +532,7 @@ void FileManager::fillRealPathName(FileEntry *UFE, 
llvm::StringRef FileName) {
   // misleading. We need to clean up the interface here.
   makeAbsolutePath(AbsPath);
   llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
-  UFE->RealPathName = std::string(AbsPath.str());
+  UFE->RealPathName = std::string(AbsPath);
 }
 
 llvm::ErrorOr>

diff  --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp
index 353370f1d761b92..5b43272bfa62f40 100644
--- a/clang/lib/CodeGen/CGCUDANV.cpp
+++ b/clang/lib/CodeGen/CGCUDANV.cpp
@@ -893,7 +893,7 @@ llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
 llvm::raw_svector_ostream OS(ModuleID);
 OS << ModuleIDPrefix << llvm::format("%" PRIx64, FatbinWrapper->getGUID());
 llvm::Constant *ModuleIDConstant = makeConstantArray(
-std::string(ModuleID.str()), "", ModuleIDSectionName, 32, 
/*AddNull=*/true);
+std::string(ModuleID), "", ModuleIDSectionName, 32, /*AddNull=*/true);
 
 // Create an alias for the FatbinWrapper that nvcc will look for.
 llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage,

diff  --git 

[clang] [Coverage] Map regions from system headers (PR #76950)

2024-01-20 Thread Petr Hosek via cfe-commits

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


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


[clang-tools-extra] [llvm] [clang] [Clang][Builtin] add __builtin_exit (PR #74803)

2024-01-20 Thread via cfe-commits

https://github.com/W-50243 updated 
https://github.com/llvm/llvm-project/pull/74803

>From bcaaab24a927624669200113857fee842103d325 Mon Sep 17 00:00:00 2001
From: W-50243 
Date: Thu, 7 Dec 2023 19:42:29 +0800
Subject: [PATCH 1/2] [Clang][Builtin] add __builtin_exit

---
 clang/include/clang/Basic/Builtins.def | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index ec39e926889b93..8b73e9c5e3594e 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -948,6 +948,7 @@ BUILTIN(__sync_fetch_and_umin, "UiUiD*Ui", "n")
 BUILTIN(__sync_fetch_and_umax, "UiUiD*Ui", "n")
 
 // Random libc builtins.
+BUILTIN(__builtin_exit, "vi", "Fnr")
 BUILTIN(__builtin_abort, "v", "Fnr")
 BUILTIN(__builtin_index, "c*cC*i", "Fn")
 BUILTIN(__builtin_rindex, "c*cC*i", "Fn")

>From 2a664f504045b560feb9ebb6b37132ebe0a863a6 Mon Sep 17 00:00:00 2001
From: W-50243 
Date: Thu, 7 Dec 2023 19:42:29 +0800
Subject: [PATCH 2/2] [Clang][Builtin] add __builtin_exit

---
 clang/include/clang/Basic/Builtins.def | 1 +
 clang/test/CodeGen/builtin-exit-test.c | 9 +
 2 files changed, 10 insertions(+)
 create mode 100644 clang/test/CodeGen/builtin-exit-test.c

diff --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index ec39e926889b93..8b73e9c5e3594e 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -948,6 +948,7 @@ BUILTIN(__sync_fetch_and_umin, "UiUiD*Ui", "n")
 BUILTIN(__sync_fetch_and_umax, "UiUiD*Ui", "n")
 
 // Random libc builtins.
+BUILTIN(__builtin_exit, "vi", "Fnr")
 BUILTIN(__builtin_abort, "v", "Fnr")
 BUILTIN(__builtin_index, "c*cC*i", "Fn")
 BUILTIN(__builtin_rindex, "c*cC*i", "Fn")
diff --git a/clang/test/CodeGen/builtin-exit-test.c 
b/clang/test/CodeGen/builtin-exit-test.c
new file mode 100644
index 00..1ece90de1aa4fd
--- /dev/null
+++ b/clang/test/CodeGen/builtin-exit-test.c
@@ -0,0 +1,9 @@
+//RUN: %clang_cc1 -no-opaque-pointers -emit-llvm -Wno-strict-prototypes 
-triple aarch64-target-linux-gnu %s -o - | FileCheck %s
+
+//CHECK: define dso_local void @test() #0 {
+//CHECK: call void @exit(i32 noundef 1)
+//CHECK: unreachable
+
+void test(void){
+   __builtin_exit(1);
+}

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


[clang-tools-extra] [clang-tidy] Ignore user-defined literals in google-runtime-int (PR #78859)

2024-01-20 Thread Félix-Antoine Constantin via cfe-commits


@@ -56,11 +56,14 @@ void IntegerTypesCheck::registerMatchers(MatchFinder 
*Finder) {
   // http://google.github.io/styleguide/cppguide.html#64-bit_Portability
   // "Where possible, avoid passing arguments of types specified by
   // bitwidth typedefs to printf-based APIs."
-  Finder->addMatcher(typeLoc(loc(isInteger()),
- unless(hasAncestor(callExpr(
- 
callee(functionDecl(hasAttr(attr::Format)))
- .bind("tl"),
- this);
+  Finder->addMatcher(
+  typeLoc(loc(isInteger()),
+  unless(anyOf(hasAncestor(callExpr(
+   callee(functionDecl(hasAttr(attr::Format),
+   hasParent(parmVarDecl(hasAncestor(functionDecl(
+   matchesName("operator\"\".*$"

felix642 wrote:

Thank you, didn't think about this 

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


[clang-tools-extra] [clang-tidy] Ignore user-defined literals in google-runtime-int (PR #78859)

2024-01-20 Thread Félix-Antoine Constantin via cfe-commits

https://github.com/felix642 updated 
https://github.com/llvm/llvm-project/pull/78859

From 8ea205ae2324d67f9adaf30d5662d2cde2096534 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Sat, 20 Jan 2024 15:29:06 -0500
Subject: [PATCH 1/2] [clang-tidy] Ignore user-defined literals in
 google-runtime-int

User-defined literals do not accept u?intXX(_t)? variables.
So the check should not emit a warning.

Fixes #54546 #25214
---
 .../clang-tidy/google/IntegerTypesCheck.cpp | 13 -
 clang-tools-extra/docs/ReleaseNotes.rst |  3 +++
 .../test/clang-tidy/checkers/google/runtime-int.cpp | 10 ++
 3 files changed, 17 insertions(+), 9 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp 
b/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
index bb4e1de8cc4b15..b60f2d0ed63112 100644
--- a/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
+++ b/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
@@ -56,11 +56,14 @@ void IntegerTypesCheck::registerMatchers(MatchFinder 
*Finder) {
   // http://google.github.io/styleguide/cppguide.html#64-bit_Portability
   // "Where possible, avoid passing arguments of types specified by
   // bitwidth typedefs to printf-based APIs."
-  Finder->addMatcher(typeLoc(loc(isInteger()),
- unless(hasAncestor(callExpr(
- 
callee(functionDecl(hasAttr(attr::Format)))
- .bind("tl"),
- this);
+  Finder->addMatcher(
+  typeLoc(loc(isInteger()),
+  unless(anyOf(hasAncestor(callExpr(
+   callee(functionDecl(hasAttr(attr::Format),
+   hasParent(parmVarDecl(hasAncestor(functionDecl(
+   matchesName("operator\"\".*$"
+  .bind("tl"),
+  this);
   IdentTable = std::make_unique(getLangOpts());
 }
 
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index a235a7d02592e8..5c857824c2b021 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -359,6 +359,9 @@ Changes in existing checks
   to ignore unused parameters when they are marked as unused and parameters of
   deleted functions and constructors.
 
+- Improved :doc:`google-runtime-int` check to ignore
+  false positives on user defined-literals.
+
 - Improved :doc:`llvm-namespace-comment
   ` check to provide fixes for
   ``inline`` namespaces in the same format as :program:`clang-format`.
diff --git a/clang-tools-extra/test/clang-tidy/checkers/google/runtime-int.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/google/runtime-int.cpp
index 4bb739876b7f4c..88f0b519e9cbee 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/google/runtime-int.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/google/runtime-int.cpp
@@ -59,11 +59,13 @@ void qux() {
 // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'short' with 
'int16'
 }
 
-// FIXME: This shouldn't warn, as UD-literal operators require one of a handful
-// of types as an argument.
 struct some_value {};
-constexpr some_value operator"" _some_literal(unsigned long long int i);
-// CHECK-MESSAGES: [[@LINE-1]]:47: warning: consider replacing 'unsigned long 
long'
+constexpr some_value operator"" _some_literal(unsigned long long int i)
+{
+  short j;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'short' with 
'int16'
+  return some_value();
+}
 
 struct A { A& operator=(const A&); };
 class B { A a[0]; };

From b54e033b0a4cbc72d345521c9b5e2ff96211d589 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Sat, 20 Jan 2024 21:02:42 -0500
Subject: [PATCH 2/2] fixup! [clang-tidy] Ignore user-defined literals in
 google-runtime-int

Fixed Documentation
Improved ast matcher to use getLiteralIdentifier
---
 .../clang-tidy/google/IntegerTypesCheck.cpp| 10 --
 clang-tools-extra/docs/ReleaseNotes.rst|  4 ++--
 2 files changed, 10 insertions(+), 4 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp 
b/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
index b60f2d0ed63112..ef511e9108f2ee 100644
--- a/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
+++ b/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
@@ -36,6 +36,12 @@ static Token getTokenAtLoc(SourceLocation Loc,
   return Tok;
 }
 
+namespace {
+AST_MATCHER(FunctionDecl, isUserDefineLiteral) {
+  return Node.getLiteralIdentifier() != nullptr;
+}
+} // namespace
+
 namespace tidy::google::runtime {
 
 IntegerTypesCheck::IntegerTypesCheck(StringRef Name, ClangTidyContext *Context)
@@ -60,8 +66,8 @@ void IntegerTypesCheck::registerMatchers(MatchFinder *Finder) 
{
   typeLoc(loc(isInteger()),
   unless(anyOf(hasAncestor(callExpr(

[clang-tools-extra] [clang] [clangd] Add support to rename Objective-C selectors (PR #78872)

2024-01-20 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 b9a1e2ab8dead4863834f70cdae56104ec92d041 
048d6f062e8a683af8ebcecf85b5c50bfb02454c -- 
clang/lib/Tooling/Refactoring/SymbolName.cpp 
clang-tools-extra/clangd/ClangdLSPServer.cpp 
clang-tools-extra/clangd/ClangdLSPServer.h 
clang-tools-extra/clangd/ClangdServer.cpp clang-tools-extra/clangd/Protocol.cpp 
clang-tools-extra/clangd/Protocol.h clang-tools-extra/clangd/SourceCode.cpp 
clang-tools-extra/clangd/SourceCode.h 
clang-tools-extra/clangd/index/SymbolCollector.cpp 
clang-tools-extra/clangd/refactor/Rename.cpp 
clang-tools-extra/clangd/refactor/Rename.h 
clang-tools-extra/clangd/unittests/RenameTests.cpp 
clang-tools-extra/clangd/unittests/SourceCodeTests.cpp 
clang/include/clang/Tooling/Refactoring/Rename/RenamingAction.h 
clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h 
clang/include/clang/Tooling/Syntax/Tokens.h 
clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp 
clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp 
clang/lib/Tooling/Syntax/Tokens.cpp 
clang/unittests/Tooling/RefactoringActionRulesTest.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang-tools-extra/clangd/unittests/RenameTests.cpp 
b/clang-tools-extra/clangd/unittests/RenameTests.cpp
index ff64e17645..9bf3b94120 100644
--- a/clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ b/clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -887,11 +887,10 @@ TEST(RenameTest, ObjCWithinFileRename) {
 /// fail.
 std::optional Expected;
   };
-  TestCase Tests[] = {
-// Simple rename
-{
-  // Input
-  R"cpp(
+  TestCase Tests[] = {// Simple rename
+  {
+  // Input
+  R"cpp(
 @interface Foo
 - (int)performA^ction:(int)action w^ith:(int)value;
 @end
@@ -901,10 +900,10 @@ TEST(RenameTest, ObjCWithinFileRename) {
 }
 @end
   )cpp",
-  // New name
-  "performNewAction:by:",
-  // Expected
-  R"cpp(
+  // New name
+  "performNewAction:by:",
+  // Expected
+  R"cpp(
 @interface Foo
 - (int)performNewAction:(int)action by:(int)value;
 @end
@@ -914,11 +913,11 @@ TEST(RenameTest, ObjCWithinFileRename) {
 }
 @end
   )cpp",
-},
-// Rename selector with macro
-{
-  // Input
-  R"cpp(
+  },
+  // Rename selector with macro
+  {
+  // Input
+  R"cpp(
 #define mySelector - (int)performAction:(int)action with:(int)value
 @interface Foo
 ^mySelector;
@@ -929,15 +928,15 @@ TEST(RenameTest, ObjCWithinFileRename) {
 }
 @end
   )cpp",
-  // New name
-  "performNewAction:by:",
-  // Expected error
-  std::nullopt,
-},
-// Rename selector in macro definition
-{
-  // Input
-  R"cpp(
+  // New name
+  "performNewAction:by:",
+  // Expected error
+  std::nullopt,
+  },
+  // Rename selector in macro definition
+  {
+  // Input
+  R"cpp(
 #define mySelector - (int)perform^Action:(int)action with:(int)value
 @interface Foo
 mySelector;
@@ -948,18 +947,20 @@ TEST(RenameTest, ObjCWithinFileRename) {
 }
 @end
   )cpp",
-  // New name
-  "performNewAction:by:",
-  // Expected error
-  std::nullopt,
-},
-// Don't rename `@selector`
-// `@selector` is not tied to a single selector. Eg. there might be 
multiple
-// classes in the codebase that implement that selector. It's thus more 
like
-// a string literal and we shouldn't rename it.
-{
-  // Input
-  R"cpp(
+  // New name
+  "performNewAction:by:",
+  // Expected error
+  std::nullopt,
+  },
+  // Don't rename `@selector`
+  // `@selector` is not tied to a single selector. Eg. 
there
+  // might be multiple
+  // classes in the codebase that implement that selector.
+  // It's thus more like
+  // a string literal and we shouldn't rename it.
+  {
+  // Input
+  R"cpp(
 @interface Foo
 - (void)performA^ction:(int)action with:(int)value;
 @end
@@ -969,10 

[clang-tools-extra] [clang] [clangd] Add support to rename Objective-C selectors (PR #78872)

2024-01-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tools-extra

Author: Alex Hoppen (ahoppen)


Changes

This adds support to rename Objective-C method declarations and calls to clangd.

---

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


24 Files Affected:

- (modified) clang-tools-extra/clangd/ClangdLSPServer.cpp (+3-2) 
- (modified) clang-tools-extra/clangd/ClangdLSPServer.h (+1-1) 
- (modified) clang-tools-extra/clangd/ClangdServer.cpp (+1-2) 
- (modified) clang-tools-extra/clangd/Protocol.cpp (+4) 
- (modified) clang-tools-extra/clangd/Protocol.h (+11) 
- (modified) clang-tools-extra/clangd/SourceCode.cpp (+9-9) 
- (modified) clang-tools-extra/clangd/SourceCode.h (+3-3) 
- (modified) clang-tools-extra/clangd/index/SymbolCollector.cpp (+24-3) 
- (modified) clang-tools-extra/clangd/refactor/Rename.cpp (+110-37) 
- (modified) clang-tools-extra/clangd/refactor/Rename.h (+26-13) 
- (modified) clang-tools-extra/clangd/unittests/RenameTests.cpp (+342-9) 
- (modified) clang-tools-extra/clangd/unittests/SourceCodeTests.cpp (+2-2) 
- (modified) clang/include/clang/Tooling/Refactoring/Rename/RenamingAction.h 
(+21) 
- (modified) clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h 
(+40-10) 
- (modified) clang/include/clang/Tooling/Syntax/Tokens.h (+13) 
- (modified) clang/lib/Tooling/Refactoring/CMakeLists.txt (+2) 
- (modified) clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp (+96-2) 
- (modified) clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp (+2-2) 
- (added) clang/lib/Tooling/Refactoring/SymbolName.cpp (+70) 
- (modified) clang/lib/Tooling/Syntax/Tokens.cpp (+7) 
- (modified) clang/tools/clang-refactor/CMakeLists.txt (+1) 
- (modified) clang/tools/clang-rename/CMakeLists.txt (+1) 
- (modified) clang/tools/libclang/CMakeLists.txt (+1) 
- (modified) clang/unittests/Tooling/RefactoringActionRulesTest.cpp (+3-3) 


``diff
diff --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index a87da252b7a7e9b..5dfd12045b65738 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -844,14 +844,15 @@ void ClangdLSPServer::onWorkspaceSymbol(
 }
 
 void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams ,
-  Callback> Reply) {
+  Callback Reply) {
   Server->prepareRename(
   Params.textDocument.uri.file(), Params.position, /*NewName*/ 
std::nullopt,
   Opts.Rename,
   [Reply = std::move(Reply)](llvm::Expected Result) mutable {
 if (!Result)
   return Reply(Result.takeError());
-return Reply(std::move(Result->Target));
+PrepareRenameResult PrepareResult{Result->Target, Result->OldName};
+return Reply(std::move(PrepareResult));
   });
 }
 
diff --git a/clang-tools-extra/clangd/ClangdLSPServer.h 
b/clang-tools-extra/clangd/ClangdLSPServer.h
index 79579c22b788a9c..6a9f097d551ae6d 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.h
+++ b/clang-tools-extra/clangd/ClangdLSPServer.h
@@ -134,7 +134,7 @@ class ClangdLSPServer : private ClangdServer::Callbacks,
   void onWorkspaceSymbol(const WorkspaceSymbolParams &,
  Callback>);
   void onPrepareRename(const TextDocumentPositionParams &,
-   Callback>);
+   Callback);
   void onRename(const RenameParams &, Callback);
   void onHover(const TextDocumentPositionParams &,
Callback>);
diff --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index 6fb2641e8793db1..b04ebc7049c6619 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -578,8 +578,7 @@ void ClangdServer::prepareRename(PathRef File, Position Pos,
 // prepareRename is latency-sensitive: we don't query the index, as we
 // only need main-file references
 auto Results =
-clangd::rename({Pos, NewName.value_or("__clangd_rename_placeholder"),
-InpAST->AST, File, /*FS=*/nullptr,
+clangd::rename({Pos, NewName, InpAST->AST, File, /*FS=*/nullptr,
 /*Index=*/nullptr, RenameOpts});
 if (!Results) {
   // LSP says to return null on failure, but that will result in a generic
diff --git a/clang-tools-extra/clangd/Protocol.cpp 
b/clang-tools-extra/clangd/Protocol.cpp
index a6370649f5ad1cf..0291e5d71d65c88 100644
--- a/clang-tools-extra/clangd/Protocol.cpp
+++ b/clang-tools-extra/clangd/Protocol.cpp
@@ -905,6 +905,10 @@ llvm::json::Value toJSON(const DocumentSymbol ) {
   return std::move(Result);
 }
 
+llvm::json::Value toJSON(const PrepareRenameResult ) {
+  return llvm::json::Object{{"range", R.range}, {"placeholder", 
R.placeholder}};
+}
+
 llvm::json::Value toJSON(const WorkspaceEdit ) {
   llvm::json::Object Result;
   if (WE.changes) {

[clang] [clang-tools-extra] [clangd] Add support to rename Objective-C selectors (PR #78872)

2024-01-20 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clangd

@llvm/pr-subscribers-clang

Author: Alex Hoppen (ahoppen)


Changes

This adds support to rename Objective-C method declarations and calls to clangd.

---

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


24 Files Affected:

- (modified) clang-tools-extra/clangd/ClangdLSPServer.cpp (+3-2) 
- (modified) clang-tools-extra/clangd/ClangdLSPServer.h (+1-1) 
- (modified) clang-tools-extra/clangd/ClangdServer.cpp (+1-2) 
- (modified) clang-tools-extra/clangd/Protocol.cpp (+4) 
- (modified) clang-tools-extra/clangd/Protocol.h (+11) 
- (modified) clang-tools-extra/clangd/SourceCode.cpp (+9-9) 
- (modified) clang-tools-extra/clangd/SourceCode.h (+3-3) 
- (modified) clang-tools-extra/clangd/index/SymbolCollector.cpp (+24-3) 
- (modified) clang-tools-extra/clangd/refactor/Rename.cpp (+110-37) 
- (modified) clang-tools-extra/clangd/refactor/Rename.h (+26-13) 
- (modified) clang-tools-extra/clangd/unittests/RenameTests.cpp (+342-9) 
- (modified) clang-tools-extra/clangd/unittests/SourceCodeTests.cpp (+2-2) 
- (modified) clang/include/clang/Tooling/Refactoring/Rename/RenamingAction.h 
(+21) 
- (modified) clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h 
(+40-10) 
- (modified) clang/include/clang/Tooling/Syntax/Tokens.h (+13) 
- (modified) clang/lib/Tooling/Refactoring/CMakeLists.txt (+2) 
- (modified) clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp (+96-2) 
- (modified) clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp (+2-2) 
- (added) clang/lib/Tooling/Refactoring/SymbolName.cpp (+70) 
- (modified) clang/lib/Tooling/Syntax/Tokens.cpp (+7) 
- (modified) clang/tools/clang-refactor/CMakeLists.txt (+1) 
- (modified) clang/tools/clang-rename/CMakeLists.txt (+1) 
- (modified) clang/tools/libclang/CMakeLists.txt (+1) 
- (modified) clang/unittests/Tooling/RefactoringActionRulesTest.cpp (+3-3) 


``diff
diff --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index a87da252b7a7e9b..5dfd12045b65738 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -844,14 +844,15 @@ void ClangdLSPServer::onWorkspaceSymbol(
 }
 
 void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams ,
-  Callback> Reply) {
+  Callback Reply) {
   Server->prepareRename(
   Params.textDocument.uri.file(), Params.position, /*NewName*/ 
std::nullopt,
   Opts.Rename,
   [Reply = std::move(Reply)](llvm::Expected Result) mutable {
 if (!Result)
   return Reply(Result.takeError());
-return Reply(std::move(Result->Target));
+PrepareRenameResult PrepareResult{Result->Target, Result->OldName};
+return Reply(std::move(PrepareResult));
   });
 }
 
diff --git a/clang-tools-extra/clangd/ClangdLSPServer.h 
b/clang-tools-extra/clangd/ClangdLSPServer.h
index 79579c22b788a9c..6a9f097d551ae6d 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.h
+++ b/clang-tools-extra/clangd/ClangdLSPServer.h
@@ -134,7 +134,7 @@ class ClangdLSPServer : private ClangdServer::Callbacks,
   void onWorkspaceSymbol(const WorkspaceSymbolParams &,
  Callback>);
   void onPrepareRename(const TextDocumentPositionParams &,
-   Callback>);
+   Callback);
   void onRename(const RenameParams &, Callback);
   void onHover(const TextDocumentPositionParams &,
Callback>);
diff --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index 6fb2641e8793db1..b04ebc7049c6619 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -578,8 +578,7 @@ void ClangdServer::prepareRename(PathRef File, Position Pos,
 // prepareRename is latency-sensitive: we don't query the index, as we
 // only need main-file references
 auto Results =
-clangd::rename({Pos, NewName.value_or("__clangd_rename_placeholder"),
-InpAST->AST, File, /*FS=*/nullptr,
+clangd::rename({Pos, NewName, InpAST->AST, File, /*FS=*/nullptr,
 /*Index=*/nullptr, RenameOpts});
 if (!Results) {
   // LSP says to return null on failure, but that will result in a generic
diff --git a/clang-tools-extra/clangd/Protocol.cpp 
b/clang-tools-extra/clangd/Protocol.cpp
index a6370649f5ad1cf..0291e5d71d65c88 100644
--- a/clang-tools-extra/clangd/Protocol.cpp
+++ b/clang-tools-extra/clangd/Protocol.cpp
@@ -905,6 +905,10 @@ llvm::json::Value toJSON(const DocumentSymbol ) {
   return std::move(Result);
 }
 
+llvm::json::Value toJSON(const PrepareRenameResult ) {
+  return llvm::json::Object{{"range", R.range}, {"placeholder", 
R.placeholder}};
+}
+
 llvm::json::Value toJSON(const WorkspaceEdit ) {
   llvm::json::Object Result;
   if 

[clang] [clang-tools-extra] [clangd] Add support to rename Objective-C selectors (PR #78872)

2024-01-20 Thread Alex Hoppen via cfe-commits

https://github.com/ahoppen created 
https://github.com/llvm/llvm-project/pull/78872

This adds support to rename Objective-C method declarations and calls to clangd.

>From 26d9d1a5a342df34cde921f7d9921e7b94dadd87 Mon Sep 17 00:00:00 2001
From: Alex Hoppen 
Date: Tue, 19 Dec 2023 15:54:40 -0800
Subject: [PATCH 1/5] [Refactoring] Add capabilities to `SymbolName` to
 represent Objective-C selector names

---
 .../Tooling/Refactoring/Rename/SymbolName.h   | 30 +++-
 clang/lib/Tooling/Refactoring/CMakeLists.txt  |  1 +
 .../Refactoring/Rename/RenamingAction.cpp |  4 +-
 .../Refactoring/Rename/USRLocFinder.cpp   |  4 +-
 clang/lib/Tooling/Refactoring/SymbolName.cpp  | 46 +++
 clang/tools/clang-rename/CMakeLists.txt   |  1 +
 6 files changed, 70 insertions(+), 16 deletions(-)
 create mode 100644 clang/lib/Tooling/Refactoring/SymbolName.cpp

diff --git a/clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h 
b/clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h
index 6c28d40f3679c2..077f315f657e77 100644
--- a/clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h
+++ b/clang/include/clang/Tooling/Refactoring/Rename/SymbolName.h
@@ -15,6 +15,9 @@
 #include "llvm/ADT/StringRef.h"
 
 namespace clang {
+
+class LangOptions;
+
 namespace tooling {
 
 /// A name of a symbol.
@@ -27,19 +30,22 @@ namespace tooling {
 /// //   ^~ string 0 ~ ^~ string 1 ~
 /// \endcode
 class SymbolName {
+  llvm::SmallVector NamePieces;
+
 public:
-  explicit SymbolName(StringRef Name) {
-// While empty symbol names are valid (Objective-C selectors can have empty
-// name pieces), occurrences Objective-C selectors are created using an
-// array of strings instead of just one string.
-assert(!Name.empty() && "Invalid symbol name!");
-this->Name.push_back(Name.str());
-  }
-
-  ArrayRef getNamePieces() const { return Name; }
-
-private:
-  llvm::SmallVector Name;
+  /// Create a new \c SymbolName with the specified pieces.
+  explicit SymbolName(ArrayRef NamePieces);
+
+  /// Creates a \c SymbolName from the given string representation.
+  ///
+  /// For Objective-C symbol names, this splits a selector into multiple pieces
+  /// on `:`. For all other languages the name is used as the symbol name.
+  SymbolName(StringRef Name, bool IsObjectiveCSelector);
+  SymbolName(StringRef Name, const LangOptions );
+
+  ArrayRef getNamePieces() const { return NamePieces; }
+
+  void print(raw_ostream ) const;
 };
 
 } // end namespace tooling
diff --git a/clang/lib/Tooling/Refactoring/CMakeLists.txt 
b/clang/lib/Tooling/Refactoring/CMakeLists.txt
index d3077be8810aad..a4a80ce8344313 100644
--- a/clang/lib/Tooling/Refactoring/CMakeLists.txt
+++ b/clang/lib/Tooling/Refactoring/CMakeLists.txt
@@ -13,6 +13,7 @@ add_clang_library(clangToolingRefactoring
   Rename/USRFinder.cpp
   Rename/USRFindingAction.cpp
   Rename/USRLocFinder.cpp
+  SymbolName.cpp
 
   LINK_LIBS
   clangAST
diff --git a/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp 
b/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
index 72598601d47d67..4965977d1f7aa4 100644
--- a/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
+++ b/clang/lib/Tooling/Refactoring/Rename/RenamingAction.cpp
@@ -82,7 +82,7 @@ 
RenameOccurrences::createSourceReplacements(RefactoringRuleContext ) {
   if (!Occurrences)
 return Occurrences.takeError();
   // FIXME: Verify that the new name is valid.
-  SymbolName Name(NewName);
+  SymbolName Name(NewName, /*IsObjectiveCSelector=*/false);
   return createRenameReplacements(
   *Occurrences, Context.getASTContext().getSourceManager(), Name);
 }
@@ -219,7 +219,7 @@ class RenamingASTConsumer : public ASTConsumer {
 }
 // FIXME: Support multi-piece names.
 // FIXME: better error handling (propagate error out).
-SymbolName NewNameRef(NewName);
+SymbolName NewNameRef(NewName, /*IsObjectiveCSelector=*/false);
 Expected> Change =
 createRenameReplacements(Occurrences, SourceMgr, NewNameRef);
 if (!Change) {
diff --git a/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp 
b/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
index c18f9290471fe4..43e48f24caa9ea 100644
--- a/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
+++ b/clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
@@ -60,8 +60,8 @@ class USRLocFindingASTVisitor
const ASTContext )
   : RecursiveSymbolVisitor(Context.getSourceManager(),
Context.getLangOpts()),
-USRSet(USRs.begin(), USRs.end()), PrevName(PrevName), Context(Context) 
{
-  }
+USRSet(USRs.begin(), USRs.end()),
+PrevName(PrevName, /*IsObjectiveCSelector=*/false), Context(Context) {}
 
   bool visitSymbolOccurrence(const NamedDecl *ND,
  ArrayRef NameRanges) {
diff --git a/clang/lib/Tooling/Refactoring/SymbolName.cpp 

[clang] [CMake][PGO] Add libunwind to list of stage1 runtimes (PR #78869)

2024-01-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Tom Stellard (tstellar)


Changes

This fixes the build since 8f90e6937a1fac80873bb2dab5f382c82ba1ba4e which made 
libcxxabi use llvm's libunwind by default.

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


1 Files Affected:

- (modified) clang/cmake/caches/PGO.cmake (+1-1) 


``diff
diff --git a/clang/cmake/caches/PGO.cmake b/clang/cmake/caches/PGO.cmake
index e1d0585e453f82..15bc755d110d19 100644
--- a/clang/cmake/caches/PGO.cmake
+++ b/clang/cmake/caches/PGO.cmake
@@ -2,7 +2,7 @@ set(CMAKE_BUILD_TYPE RELEASE CACHE STRING "")
 set(CLANG_ENABLE_BOOTSTRAP ON CACHE BOOL "")
 
 set(LLVM_ENABLE_PROJECTS "clang;lld" CACHE STRING "")
-set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi" CACHE STRING "")
+set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING 
"")
 
 set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
 set(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED ON CACHE BOOL "")

``




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


[clang] [CMake][PGO] Add libunwind to list of stage1 runtimes (PR #78869)

2024-01-20 Thread Tom Stellard via cfe-commits

https://github.com/tstellar created 
https://github.com/llvm/llvm-project/pull/78869

This fixes the build since 8f90e6937a1fac80873bb2dab5f382c82ba1ba4e which made 
libcxxabi use llvm's libunwind by default.

>From 0719f49ecc6dd69ae4698c3e84dbf175a1bf2ed3 Mon Sep 17 00:00:00 2001
From: Tom Stellard 
Date: Sun, 21 Jan 2024 00:25:47 +
Subject: [PATCH] [CMake][PGO] Add libunwind to list of stage1 runtimes

This fixes the build since 8f90e6937a1fac80873bb2dab5f382c82ba1ba4e
which made libcxxabi use llvm's libunwind by default.
---
 clang/cmake/caches/PGO.cmake | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/cmake/caches/PGO.cmake b/clang/cmake/caches/PGO.cmake
index e1d0585e453f82..15bc755d110d19 100644
--- a/clang/cmake/caches/PGO.cmake
+++ b/clang/cmake/caches/PGO.cmake
@@ -2,7 +2,7 @@ set(CMAKE_BUILD_TYPE RELEASE CACHE STRING "")
 set(CLANG_ENABLE_BOOTSTRAP ON CACHE BOOL "")
 
 set(LLVM_ENABLE_PROJECTS "clang;lld" CACHE STRING "")
-set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi" CACHE STRING "")
+set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING 
"")
 
 set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
 set(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED ON CACHE BOOL "")

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


[compiler-rt] [clang] [llvm] [lldb] [flang] [lld] [libcxx] [clang-tools-extra] [libc] [lld-macho] Find objects in library search path (PR #78628)

2024-01-20 Thread via cfe-commits


@@ -0,0 +1,14 @@
+# REQUIRES: x86
+# RUN: mkdir -p %t
+# RUN: llvm-mc -filetype=obj -triple=x86_64-apple-darwin %p/Inputs/libhello.s 
-o %t/hello.o
+# RUN: llvm-mc -filetype=obj -triple=x86_64-apple-darwin %s -o %t/main.o
+# RUN: %lld -L %t %t/main.o %t/hello.o -o %t/a.out

OldWorldOrdr wrote:

I fixed it in my branch but the pr is already merged

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


[compiler-rt] [clang] [llvm] [lldb] [flang] [lld] [libcxx] [clang-tools-extra] [libc] [lld-macho] Find objects in library search path (PR #78628)

2024-01-20 Thread via cfe-commits


@@ -0,0 +1,14 @@
+# REQUIRES: x86
+# RUN: mkdir -p %t
+# RUN: llvm-mc -filetype=obj -triple=x86_64-apple-darwin %p/Inputs/libhello.s 
-o %t/hello.o
+# RUN: llvm-mc -filetype=obj -triple=x86_64-apple-darwin %s -o %t/main.o
+# RUN: %lld -L %t %t/main.o %t/hello.o -o %t/a.out

OldWorldOrdr wrote:

AHH

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


[clang] [llvm] [CMake][Release] Add option for enabling PGO to release cache file. (PR #78823)

2024-01-20 Thread Petr Hosek via cfe-commits

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


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


[clang] [llvm] [CMake][Release] Add option for enabling PGO to release cache file. (PR #78823)

2024-01-20 Thread Tom Stellard via cfe-commits

https://github.com/tstellar updated 
https://github.com/llvm/llvm-project/pull/78823

>From b23e23f862bec32e42fa7aa96da1fe0c4ed38a54 Mon Sep 17 00:00:00 2001
From: Tom Stellard 
Date: Sat, 6 Jan 2024 06:44:32 +
Subject: [PATCH 1/2] [CMake][Release] Add option for enabling PGO to release
 cache file.

The option is LLVM_RELEASE_ENABLE_PGO and it's turned on by default.
---
 clang/cmake/caches/Release.cmake   | 73 +++---
 llvm/utils/release/test-release.sh |  4 +-
 2 files changed, 59 insertions(+), 18 deletions(-)

diff --git a/clang/cmake/caches/Release.cmake b/clang/cmake/caches/Release.cmake
index a7b9a8d0e29f88..0d114c3734a82d 100644
--- a/clang/cmake/caches/Release.cmake
+++ b/clang/cmake/caches/Release.cmake
@@ -4,27 +4,53 @@
 
 # General Options
 set(LLVM_RELEASE_ENABLE_LTO THIN CACHE STRING "")
+set(LLVM_RELEASE_ENABLE_PGO ON CACHE BOOL "")
 
 set(CMAKE_BUILD_TYPE RELEASE CACHE STRING "")
 
 # Stage 1 Bootstrap Setup
 set(CLANG_ENABLE_BOOTSTRAP ON CACHE BOOL "")
-set(CLANG_BOOTSTRAP_TARGETS
-  clang
-  check-all
-  check-llvm
-  check-clang
-  test-suite
-  stage3
-  stage3-clang
-  stage3-check-all
-  stage3-check-llvm
-  stage3-check-clang
-  stage3-install
-  stage3-test-suite CACHE STRING "")
+if (LLVM_RELEASE_ENABLE_PGO)
+  set(CLANG_BOOTSTRAP_TARGETS
+generate-profdata
+stage2
+stage2-clang
+stage2-distribution
+stage2-install
+stage2-install-distribution
+stage2-install-distribution-toolchain
+stage2-check-all
+stage2-check-llvm
+stage2-check-clang
+stage2-test-suite CACHE STRING "")
+else()
+  set(CLANG_BOOTSTRAP_TARGETS
+clang
+check-all
+check-llvm
+check-clang
+test-suite
+stage3
+stage3-clang
+stage3-check-all
+stage3-check-llvm
+stage3-check-clang
+stage3-install
+stage3-test-suite CACHE STRING "")
+endif()
 
 # Stage 1 Options
-set(LLVM_ENABLE_PROJECTS "clang" CACHE STRING "")
+set(STAGE1_PROJECTS "clang")
+set(STAGE1_RUNTIMES "")
+
+if (LLVM_RELEASE_ENABLE_PGO)
+  list(APPEND STAGE1_PROJECTS "lld")
+  list(APPEND STAGE1_RUNTIMES "compiler-rt")
+endif()
+
+set(LLVM_ENABLE_RUNTIMES ${STAGE1_RUNTIMES} CACHE STRING "")
+set(LLVM_ENABLE_PROJECTS ${STAGE1_PROJECTS} CACHE STRING "")
+
 set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
 
 # Stage 2 Bootstrap Setup
@@ -37,11 +63,26 @@ set(BOOTSTRAP_CLANG_BOOTSTRAP_TARGETS
 
 # Stage 2 Options
 set(STAGE2_PROJECTS "clang")
-if (LLVM_RELEASE_ENABLE_LTO)
+set(STAGE2_RUNTIMES "")
+
+if (LLVM_RELEASE_ENABLE_LTO OR LLVM_RELEASE_ENABLE_PGO)
  list(APPEND STAGE2_PROJECTS "lld")
 endif()
+
+if (LLVM_RELEASE_ENABLE_PGO)
+  set(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED ON CACHE BOOL "")
+  list(APPEND STAGE2_RUNTIMES "compiler-rt")
+  set(BOOTSTRAP_LLVM_ENABLE_LTO ${LLVM_RELEASE_ENABLE_LTO})
+  if (LLVM_RELEASE_ENABLE_LTO)
+set(BOOTSTRAP_LLVM_ENABLE_LLD ON CACHE BOOL "")
+  endif()
+endif()
+
 set(BOOTSTRAP_LLVM_ENABLE_PROJECTS ${STAGE2_PROJECTS} CACHE STRING "")
-set(BOOTSTRAP_LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
+set(BOOTSTRAP_LLVM_ENABLE_RUNTIMES ${STAGE2_RUNTIMES} CACHE STRING "")
+if (NOT LLVM_RELEASE_ENABLE_PGO)
+  set(BOOTSTRAP_LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
+endif()
 
 # Stage 3 Options
 set(BOOTSTRAP_BOOTSTRAP_LLVM_ENABLE_RUNTIMES 
"compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING "")
diff --git a/llvm/utils/release/test-release.sh 
b/llvm/utils/release/test-release.sh
index 544d4bfdd799ce..5b1945df47d24a 100755
--- a/llvm/utils/release/test-release.sh
+++ b/llvm/utils/release/test-release.sh
@@ -359,11 +359,11 @@ function build_with_cmake_cache() {
 $ExtraConfigureFlags
 2>&1 | tee $LogDir/llvm.configure-$Flavor.log
 
-  ${MAKE} $J_ARG $Verbose -C $CMakeBuildDir stage3-check-all \
+  ${MAKE} $J_ARG $Verbose -C $CMakeBuildDir stage2-check-all \
   2>&1 | tee $LogDir/llvm.make-$Flavor.log > $redir
 
   DESTDIR="${InstallDir}" \
-  ${MAKE} -C $CMakeBuildDir stage3-install \
+  ${MAKE} -C $CMakeBuildDir stage2-install \
   2>&1 | tee $LogDir/llvm.install-$Flavor.log > $redir
 
  mkdir -p $BuildDir/Release

>From db6cc2ea33fc19f1359cbf38ff10059ac3aa1832 Mon Sep 17 00:00:00 2001
From: Tom Stellard 
Date: Sat, 20 Jan 2024 17:10:29 -0800
Subject: [PATCH 2/2] Update clang/cmake/caches/Release.cmake

Co-authored-by: Petr Hosek 
---
 clang/cmake/caches/Release.cmake | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/cmake/caches/Release.cmake b/clang/cmake/caches/Release.cmake
index 0d114c3734a82d..1ca9138b980731 100644
--- a/clang/cmake/caches/Release.cmake
+++ b/clang/cmake/caches/Release.cmake
@@ -70,7 +70,7 @@ if (LLVM_RELEASE_ENABLE_LTO OR LLVM_RELEASE_ENABLE_PGO)
 endif()
 
 if (LLVM_RELEASE_ENABLE_PGO)
-  set(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED ON CACHE BOOL "")
+  set(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED IR CACHE STRING "")
   list(APPEND STAGE2_RUNTIMES "compiler-rt")
   set(BOOTSTRAP_LLVM_ENABLE_LTO ${LLVM_RELEASE_ENABLE_LTO})
   if 

[clang] [llvm] [CMake][Release] Add option for enabling PGO to release cache file. (PR #78823)

2024-01-20 Thread Petr Hosek via cfe-commits


@@ -37,11 +63,26 @@ set(BOOTSTRAP_CLANG_BOOTSTRAP_TARGETS
 
 # Stage 2 Options
 set(STAGE2_PROJECTS "clang")
-if (LLVM_RELEASE_ENABLE_LTO)
+set(STAGE2_RUNTIMES "")
+
+if (LLVM_RELEASE_ENABLE_LTO OR LLVM_RELEASE_ENABLE_PGO)
  list(APPEND STAGE2_PROJECTS "lld")
 endif()
+
+if (LLVM_RELEASE_ENABLE_PGO)
+  set(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED ON CACHE BOOL "")

petrhosek wrote:

```suggestion
  set(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED IR CACHE STRING "")
```

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


[lldb] [clang] [libc] [flang] [lld] [clang-tools-extra] [llvm] [libcxx] [compiler-rt] [lld-macho] Find objects in library search path (PR #78628)

2024-01-20 Thread Shoaib Meenai via cfe-commits


@@ -0,0 +1,14 @@
+# REQUIRES: x86
+# RUN: mkdir -p %t
+# RUN: llvm-mc -filetype=obj -triple=x86_64-apple-darwin %p/Inputs/libhello.s 
-o %t/hello.o
+# RUN: llvm-mc -filetype=obj -triple=x86_64-apple-darwin %s -o %t/main.o
+# RUN: %lld -L %t %t/main.o %t/hello.o -o %t/a.out

smeenai wrote:

Should one of these be linked with `-l` instead of by path?

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


[clang] [clang-repl] We do not need to call new in the object allocation. (PR #78843)

2024-01-20 Thread Vitaly Buka via cfe-commits

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


[clang] 2759e47 - [clang-repl] We do not need to call new in the object allocation. (#78843)

2024-01-20 Thread via cfe-commits

Author: Vassil Vassilev
Date: 2024-01-20T17:00:38-08:00
New Revision: 2759e47067ea286f6302adcfe93b653cfaf6f2eb

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

LOG: [clang-repl] We do not need to call new in the object allocation. (#78843)

This test demonstrates template instantiation via the interpreter code.
In order to do that we can allocate the object on the stack and extend
its lifetime by boxing it into a clang::Value.

That avoids the subtle problem where we call the new operator on an
object only known to the interpreter and we cannot destroy it from
compiled code since there is not suitable facility in clang::Value yet.

That should resolve the asan issues that was reported in
llvm/llvm-project#76218.

Added: 


Modified: 
clang/unittests/Interpreter/InterpreterTest.cpp

Removed: 




diff  --git a/clang/unittests/Interpreter/InterpreterTest.cpp 
b/clang/unittests/Interpreter/InterpreterTest.cpp
index d6eb0684ba49d8..e76c0677db5ead 100644
--- a/clang/unittests/Interpreter/InterpreterTest.cpp
+++ b/clang/unittests/Interpreter/InterpreterTest.cpp
@@ -34,12 +34,6 @@ using namespace clang;
 #define CLANG_INTERPRETER_NO_SUPPORT_EXEC
 #endif
 
-#if LLVM_ADDRESS_SANITIZER_BUILD || LLVM_HWADDRESS_SANITIZER_BUILD
-#include 
-#else
-extern "C" void __lsan_ignore_object(const void *p) {}
-#endif
-
 int Global = 42;
 // JIT reports symbol not found on Windows without the visibility attribute.
 REPL_EXTERNAL_VISIBILITY int getGlobal() { return Global; }
@@ -257,7 +251,12 @@ TEST(IncrementalProcessing, FindMangledNameSymbol) {
 static Value AllocateObject(TypeDecl *TD, Interpreter ) {
   std::string Name = TD->getQualifiedNameAsString();
   Value Addr;
-  cantFail(Interp.ParseAndExecute("new " + Name + "()", ));
+  // FIXME: Consider providing an option in clang::Value to take ownership of
+  // the memory created from the interpreter.
+  // cantFail(Interp.ParseAndExecute("new " + Name + "()", ));
+
+  // The lifetime of the temporary is extended by the clang::Value.
+  cantFail(Interp.ParseAndExecute(Name + "()", ));
   return Addr;
 }
 
@@ -317,8 +316,6 @@ TEST(IncrementalProcessing, InstantiateTemplate) {
   auto fn =
   cantFail(Interp->getSymbolAddress(MangledName)).toPtr();
   EXPECT_EQ(42, fn(NewA.getPtr()));
-  // FIXME: release the memory.
-  __lsan_ignore_object(NewA.getPtr());
 }
 
 #ifdef CLANG_INTERPRETER_NO_SUPPORT_EXEC



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


[clang] [clang-repl] We do not need to call new in the object allocation. (PR #78843)

2024-01-20 Thread Vitaly Buka via cfe-commits

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

LGTM

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


[clang] [Clang][Sema] fix outline member function template with default align crash (PR #78400)

2024-01-20 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/78400

>From e4ac395028e651721677d85caf6c76e3a7f79308 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 17 Jan 2024 14:16:34 +0800
Subject: [PATCH] [Clang][Sema] fix outline member function template with
 default align crash

---
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 12 -
 clang/test/SemaTemplate/default-parm-init.cpp | 50 +++
 2 files changed, 60 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/SemaTemplate/default-parm-init.cpp

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index fc80515b45e35b..1ed63db75294aa 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -3051,6 +3051,7 @@ bool Sema::SubstDefaultArgument(
 //   default argument expression appears.
 ContextRAII SavedContext(*this, FD);
 std::unique_ptr LIS;
+auto NewTemplateArgs = TemplateArgs;
 
 if (ForCallExpr) {
   // When instantiating a default argument due to use in a call expression,
@@ -3063,11 +3064,18 @@ bool Sema::SubstDefaultArgument(
   /*ForDefinition*/ false);
   if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
 return true;
+  if (FD->isOutOfLine()) {
+auto *CurrentTemplateArgumentList = TemplateArgumentList::CreateCopy(
+getASTContext(), TemplateArgs.getInnermost());
+NewTemplateArgs = getTemplateInstantiationArgs(
+FD, FD->getDeclContext(), true, CurrentTemplateArgumentList, true,
+nullptr, false, false);
+  }
 }
 
 runWithSufficientStackSpace(Loc, [&] {
-  Result = SubstInitializer(PatternExpr, TemplateArgs,
-/*DirectInit*/false);
+  Result = SubstInitializer(PatternExpr, NewTemplateArgs,
+/*DirectInit*/ false);
 });
   }
   if (Result.isInvalid())
diff --git a/clang/test/SemaTemplate/default-parm-init.cpp 
b/clang/test/SemaTemplate/default-parm-init.cpp
new file mode 100644
index 00..4bcea7eaa10176
--- /dev/null
+++ b/clang/test/SemaTemplate/default-parm-init.cpp
@@ -0,0 +1,50 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++17 -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify %s
+// expected-no-diagnostics
+
+template
+struct Problem{
+  template
+  constexpr int FuncAlign(int param = alignof(FunctionTemplateParam));
+
+  template
+  constexpr int FuncSizeof(int param = sizeof(FunctionTemplateParam));
+
+  template
+  constexpr int FuncAlign2(int param = alignof(TemplateParam));
+
+  template
+  constexpr int FuncSizeof2(int param = sizeof(TemplateParam));
+};
+
+template <>
+template
+constexpr int Problem::FuncAlign(int param) {
+   return param;
+}
+
+template <>
+template
+constexpr int Problem::FuncSizeof(int param) {
+   return param;
+}
+
+template <>
+template
+constexpr int Problem::FuncAlign2(int param) {
+   return param;
+}
+
+template <>
+template
+constexpr int Problem::FuncSizeof2(int param) {
+   return param;
+}
+
+int main(){
+Problem p = {};
+static_assert(p.FuncAlign() == alignof(char));
+static_assert(p.FuncSizeof() == sizeof(char));
+static_assert(p.FuncAlign2() == alignof(int));
+static_assert(p.FuncSizeof2() == sizeof(int));
+}

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


[llvm] [clang] [clang-tools-extra] [clang] Implement CWG1878 "`operator auto` template" (PR #78103)

2024-01-20 Thread Shafik Yaghmour via cfe-commits


@@ -11321,9 +11321,20 @@ Decl 
*Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
   << ClassType << ConvType;
   }
 
-  if (FunctionTemplateDecl *ConversionTemplate
-= Conversion->getDescribedFunctionTemplate())
+  if (FunctionTemplateDecl *ConversionTemplate =
+  Conversion->getDescribedFunctionTemplate()) {
+if (const auto *ConvTypePtr = ConvType->getAs()) {
+  ConvType = ConvTypePtr->getPointeeType();
+}
+if (ConvType->isUndeducedAutoType()) {
+  Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)
+  << getReturnTypeLoc(Conversion).getSourceRange()
+  << llvm::to_underlying(ConvType->getAs()->getKeyword())
+  << /* in declaration of conversion function template= */ 24;

shafik wrote:

`warn_cconv_unsupported` uses `CallingConventionIgnoredReason` enum to specify 
which one.

Not sure if this is something we want to use more often or not.

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


[clang] [clang-format] Add SpacesInParensOption for attributes and filtering for repeated parens (PR #77522)

2024-01-20 Thread Gedare Bloom via cfe-commits

gedare wrote:

> > Covering all double parens in a single sub-option is not precise enough for 
> > code bases that may want to have `__attribute__(( x ))` but also allow `if 
> > ( ( x ) )`.
> 
> We should not go overboard with supporting all kinds of options/suboptions 
> imaginable. I don't think we should support spaces between consecutive parens 
> in the first place, which was likely a bug.
> 
Well, it seems to be far too late to go back and change the default behavior.

> We can't just disregard the long-standing 
> [policy](https://clang.llvm.org/docs/ClangFormatStyleOptions.html#adding-additional-style-options)
>  on adding new options. If anyone thinks that policy is outdated, they should 
> go through the RFC process and get it updated.

I have no problem with this policy. I think it is a good policy. I can advocate 
for my position. My patches relate to the style maintenance of a widely-used 
real-time operating system. The code is 
[self-hosted](https://git.rtems.org/rtems/) and [mirrored on 
GitHub](https://github.com/RTEMS/rtems) with a [documented style 
guide](https://docs.rtems.org/branches/master/eng/coding-formatting.html). In 
addition, I have been and will continue to be willing to provide bug fix and 
other maintenance support to clang-format based on the changes submitted to 
support these style needs.

At the moment, I need to satisfy a particular style rule that requires me to 
add spaces inside of conditional and compound expressions. This support 
basically exists in `clang-format` but the compound expressions fall under the 
`SpacesInParensOption.Other` category. In order to control compound expressions 
separately from other uses of parens, it seems to be the easiest thing to 
explicitly define "everything else" and control the injection of spaces within 
them. Eventually, it results in a much more controlled and configurable way to 
manage whitespace.

If this is not desired, I will need to step back to consider my options 
further, and probably have to take this up with the other maintainers of my 
code base to see what, if any, concessions we can make based on what is allowed 
with `clang-format`. I'm trying to get to a point where we are able to use 
`clang-format` on our code base with enforced CI actions. It is still a ways to 
go before I get there.



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


[clang] [Clang][AST] Fix a crash on attaching doc comments (PR #78716)

2024-01-20 Thread Dmitri Gribenko via cfe-commits

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


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


[clang] [Clang][AST] Fix a crash on attaching doc comments (PR #78716)

2024-01-20 Thread Dmitri Gribenko via cfe-commits

gribozavr wrote:

Thank you for the fix.

Here's what happens here.

This function receives the just-parsed decls, and its aim is to the comment in 
the same vicinity (I know this because I am the original author of the code).

This first loop over `Decls` identifies the file in which we will be looking 
for comments. Then the code retrieves the comments in that file (`auto 
CommentsInThisFile = Comments.getCommentsInFile(File);`). At this point we have 
really committed which file we are looking in.

Now, the next loop over `Decls` disturbs this decision this by adjusting the 
decl to the template. That decl could be in a different file.

The call `const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);` 
retrieves source locations for the adjusted decl. The adjusted decl could be in 
a different file from the comments that we retrieved in `CommentsInThisFile`.

Next, we are passing the mismatched `DeclLocs` and `CommentsInThisFile` into 
`getRawCommentForDeclNoCacheImpl`, which crashes when they come from different 
files.

I think the bug was introduced as a consequence of f31d8df1c8c69 and 
b67d3702577d4, while the recent source location change merely unmasked it.

So, this makes me wondering if there is a better way to structure this code to 
make the mismatch between `DeclLocs` and `CommentsInThisFile` impossible. I 
think a better way would be to merge the two loops over `Decls` and call 
`Comments.getCommentsInFile` for the source location from `DeclLocs`.

WDYT @chenshanzhi ? We can merge this change as is, since it is a good crash 
fix, but it would be great if you could make the code more robust by merging 
the loops.

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


[clang] [llvm] [WIP] Correct lowering of `fp128` intrinsics (PR #76558)

2024-01-20 Thread Trevor Gross via cfe-commits

https://github.com/tgross35 updated 
https://github.com/llvm/llvm-project/pull/76558

>From e869ad1bc601d95b6364dc5619e79a06e8b0fc82 Mon Sep 17 00:00:00 2001
From: Trevor Gross 
Date: Fri, 11 Aug 2023 22:16:01 -0400
Subject: [PATCH 1/5] [IR] Add an xpassing test for `f128` intrinsic lowering

`f128` intrinsic functions lower to incorrect libc calls. Add a test
showing current behavior.
---
 .../CodeGen/Generic/f128-math-lowering.ll | 610 ++
 1 file changed, 610 insertions(+)
 create mode 100644 llvm/test/CodeGen/Generic/f128-math-lowering.ll

diff --git a/llvm/test/CodeGen/Generic/f128-math-lowering.ll 
b/llvm/test/CodeGen/Generic/f128-math-lowering.ll
new file mode 100644
index 00..8a70786d97fe67
--- /dev/null
+++ b/llvm/test/CodeGen/Generic/f128-math-lowering.ll
@@ -0,0 +1,610 @@
+
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py 
UTC_ARGS: --version 2
+;
+; RUN: llc < %s -mtriple=aarch64-unknown-unknown -verify-machineinstrs | 
FileCheck %s --check-prefix=CHECK-AARCH64
+; RUN: llc < %s -mtriple=riscv32-unknown-unknown -verify-machineinstrs | 
FileCheck %s --check-prefix=CHECK-RISCV32
+; RUN: llc < %s -mtriple=s390x-unknown-unknown -verify-machineinstrs | 
FileCheck %s --check-prefix=CHECK-S390X
+; RUN: llc < %s -mtriple=i686-unknown-unknown   -verify-machineinstrs | 
FileCheck %s --check-prefix=CHECK-X86
+; RUN: llc < %s -mtriple=x86_64-unknown-unknown -verify-machineinstrs | 
FileCheck %s --check-prefix=CHECK-X64
+;
+; Verify that fp128 intrinsics only lower to `long double` calls on platforms
+; where `f128` and `long double` have the same layout.
+;
+; We test on x86 and x64 which have 80-bit ld, as well as aarch64 (ld == f128),
+; riscv32 (ld == f64), and s380x (ld == f128 with different alignment from
+; x64/aarch64 f128).
+;
+; FIXME: these emit calls to long double functions but should emit f128 calls
+
+define fp128 @test_cbrtf128(fp128 %a) {
+; CHECK-LABEL:  test_cbrtf128:
+; CHECK-AARCH64:b llvm.cbrt.f128
+; CHECK-RISCV32:call llvm.cbrt.f128@plt
+; CHECK-S390X:  brasl {{%.*}} llvm.cbrt.f128@PLT
+; CHECK-X64:jmp llvm.cbrt.f128@PLT # TAILCALL
+; CHECK-X86:calll llvm.cbrt.f128@PLT
+start:
+  %0 = tail call fp128 @llvm.cbrt.f128(fp128 %a)
+  ret fp128 %0
+}
+
+declare fp128 @llvm.cbrt.f128(fp128)
+
+
+define fp128 @test_ceilf128(fp128 %a) {
+; CHECK-LABEL:  test_ceilf128:
+; CHECK-AARCH64:b ceill
+; CHECK-RISCV32:call ceill@plt
+; CHECK-S390X:  brasl {{%.*}} ceill@PLT
+; CHECK-X64:jmp ceill@PLT
+; CHECK-X86:calll ceill
+start:
+  %0 = tail call fp128 @llvm.ceil.f128(fp128 %a)
+  ret fp128 %0
+}
+
+declare fp128 @llvm.ceil.f128(fp128)
+
+
+define fp128 @test_copysignf128(fp128 %a, fp128 %b) {
+; No math library call here, so make sure the assembly does the correct thing.
+; This test is autogenerated
+; CHECK-LABEL:test_copysignf128:
+; CHECK-AARCH64-LABEL: test_copysignf128:
+; CHECK-AARCH64:   // %bb.0: // %start
+; CHECK-AARCH64-NEXT:stp q0, q1, [sp, #-32]!
+; CHECK-AARCH64-NEXT:.cfi_def_cfa_offset 32
+; CHECK-AARCH64-NEXT:ldrb w8, [sp, #15]
+; CHECK-AARCH64-NEXT:ldrb w9, [sp, #31]
+; CHECK-AARCH64-NEXT:bfxil w9, w8, #0, #7
+; CHECK-AARCH64-NEXT:strb w9, [sp, #15]
+; CHECK-AARCH64-NEXT:ldr q0, [sp], #32
+; CHECK-AARCH64-NEXT:ret
+;
+; CHECK-RISCV32-LABEL: test_copysignf128:
+; CHECK-RISCV32:   # %bb.0: # %start
+; CHECK-RISCV32-NEXT:lw a3, 0(a1)
+; CHECK-RISCV32-NEXT:lw a4, 4(a1)
+; CHECK-RISCV32-NEXT:lw a2, 12(a2)
+; CHECK-RISCV32-NEXT:lw a5, 12(a1)
+; CHECK-RISCV32-NEXT:lw a1, 8(a1)
+; CHECK-RISCV32-NEXT:lui a6, 524288
+; CHECK-RISCV32-NEXT:and a2, a2, a6
+; CHECK-RISCV32-NEXT:slli a5, a5, 1
+; CHECK-RISCV32-NEXT:srli a5, a5, 1
+; CHECK-RISCV32-NEXT:or a2, a5, a2
+; CHECK-RISCV32-NEXT:sw a1, 8(a0)
+; CHECK-RISCV32-NEXT:sw a4, 4(a0)
+; CHECK-RISCV32-NEXT:sw a3, 0(a0)
+; CHECK-RISCV32-NEXT:sw a2, 12(a0)
+; CHECK-RISCV32-NEXT:ret
+;
+; CHECK-S390X-LABEL: test_copysignf128:
+; CHECK-S390X:   # %bb.0: # %start
+; CHECK-S390X-NEXT:ld %f0, 0(%r3)
+; CHECK-S390X-NEXT:ld %f2, 8(%r3)
+; CHECK-S390X-NEXT:ld %f1, 0(%r4)
+; CHECK-S390X-NEXT:ld %f3, 8(%r4)
+; CHECK-S390X-NEXT:cpsdr %f0, %f1, %f0
+; CHECK-S390X-NEXT:std %f0, 0(%r2)
+; CHECK-S390X-NEXT:std %f2, 8(%r2)
+; CHECK-S390X-NEXT:br %r14
+;
+; CHECK-X86-LABEL: test_copysignf128:
+; CHECK-X86:   # %bb.0: # %start
+; CHECK-X86-NEXT:pushl %ebx
+; CHECK-X86-NEXT:.cfi_def_cfa_offset 8
+; CHECK-X86-NEXT:pushl %edi
+; CHECK-X86-NEXT:.cfi_def_cfa_offset 12
+; CHECK-X86-NEXT:pushl %esi
+; CHECK-X86-NEXT:.cfi_def_cfa_offset 16
+; CHECK-X86-NEXT:.cfi_offset %esi, -16
+; CHECK-X86-NEXT:.cfi_offset %edi, -12
+; CHECK-X86-NEXT:.cfi_offset %ebx, -8
+; CHECK-X86-NEXT:movl {{[0-9]+}}(%esp), %eax
+; CHECK-X86-NEXT:movl {{[0-9]+}}(%esp), %ecx
+; 

[clang-tools-extra] [clang] [llvm] [CLANG] Fix : More Detailed "No expected directives found" (PR #78338)

2024-01-20 Thread Shourya Goel via cfe-commits

Sh0g0-1758 wrote:

gentle ping @tbaederr . 

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


[clang] [clang-format] Handle templated elaborated type specifier in function… (PR #77013)

2024-01-20 Thread Owen Pan via cfe-commits

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


[clang] a464e05 - [clang-format] Handle templated elaborated type specifier in function… (#77013)

2024-01-20 Thread via cfe-commits

Author: XDeme
Date: 2024-01-20T14:47:58-08:00
New Revision: a464e05109088f1f3a0ca4c83d6dd900e83bdb4b

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

LOG: [clang-format] Handle templated elaborated type specifier in function… 
(#77013)

… return type.

The behavior now is consistent with the non template version.
Enabled and updated old test.

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index c08ce86449b6ea..7bc6410a78a495 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3882,6 +3882,9 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   const FormatToken  = *FormatTok;
   nextToken();
 
+  auto IsNonMacroIdentifier = [](const FormatToken *Tok) {
+return Tok->is(tok::identifier) && Tok->TokenText != 
Tok->TokenText.upper();
+  };
   // The actual identifier can be a nested name specifier, and in macros
   // it is often token-pasted.
   // An [[attribute]] can be before the identifier.
@@ -3903,27 +3906,26 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) 
{
 }
 if (FormatTok->is(tok::l_square) && handleCppAttributes())
   continue;
-bool IsNonMacroIdentifier =
-FormatTok->is(tok::identifier) &&
-FormatTok->TokenText != FormatTok->TokenText.upper();
 nextToken();
 // We can have macros in between 'class' and the class name.
-if (!IsNonMacroIdentifier && FormatTok->is(tok::l_paren))
+if (!IsNonMacroIdentifier(FormatTok->Previous) &&
+FormatTok->is(tok::l_paren)) {
   parseParens();
+}
   }
 
-  // Note that parsing away template declarations here leads to incorrectly
-  // accepting function declarations as record declarations.
-  // In general, we cannot solve this problem. Consider:
-  // class A B() {}
-  // which can be a function definition or a class definition when B() is a
-  // macro. If we find enough real-world cases where this is a problem, we
-  // can parse for the 'template' keyword in the beginning of the statement,
-  // and thus rule out the record production in case there is no template
-  // (this would still leave us with an ambiguity between template function
-  // and class declarations).
   if (FormatTok->isOneOf(tok::colon, tok::less)) {
+int AngleNestingLevel = 0;
 do {
+  if (FormatTok->is(tok::less))
+++AngleNestingLevel;
+  else if (FormatTok->is(tok::greater))
+--AngleNestingLevel;
+
+  if (AngleNestingLevel == 0 && FormatTok->is(tok::l_paren) &&
+  IsNonMacroIdentifier(FormatTok->Previous)) {
+break;
+  }
   if (FormatTok->is(tok::l_brace)) {
 calculateBraceTypes(/*ExpectClassBody=*/true);
 if (!tryToParseBracedList())

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index cab495125415aa..3fb55ae2c1f413 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -14659,9 +14659,13 @@ TEST_F(FormatTest, 
UnderstandContextOfRecordTypeKeywords) {
   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
   verifyFormat("int i = SomeFunction(a b);");
 
-  // FIXME:
-  // This now gets parsed incorrectly as class definition.
-  // verifyFormat("class A f() {\n}\nint n;");
+  verifyFormat("class A f() {}\n"
+   "int n;");
+  verifyFormat("template  class A f() {}\n"
+   "int n;");
+
+  verifyFormat("template <> class Foo F() {\n"
+   "} n;");
 
   // Elaborate types where incorrectly parsing the structural element would
   // break the indent.

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 64b2abac5cce53..b1e1e70a1abbf0 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -2520,6 +2520,20 @@ TEST_F(TokenAnnotatorTest, BraceKind) {
   EXPECT_BRACE_KIND(Tokens[4], BK_Block);
   EXPECT_BRACE_KIND(Tokens[5], BK_Block);
 
+  Tokens = annotate("class Foo f() {}");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::identifier, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[8], tok::l_brace, TT_FunctionLBrace);
+  EXPECT_BRACE_KIND(Tokens[8], BK_Block);
+  EXPECT_BRACE_KIND(Tokens[9], BK_Block);
+
+  Tokens = annotate("template  class Foo f() {}");
+  ASSERT_EQ(Tokens.size(), 16u) << Tokens;
+  EXPECT_TOKEN(Tokens[10], tok::identifier, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[13], tok::l_brace, TT_FunctionLBrace);
+  

[clang] [clang-format] Handle templated elaborated type specifier in function… (PR #77013)

2024-01-20 Thread via cfe-commits

https://github.com/XDeme updated https://github.com/llvm/llvm-project/pull/77013

>From 45d01cbc7ec958518b1739daa9e9b0dc35c2d194 Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Thu, 4 Jan 2024 19:04:21 -0300
Subject: [PATCH 1/8] [clang-format] Handle templated elaborated type specifier
 in function return type. The behaviour now is consistent with the non
 templated version

---
 clang/lib/Format/UnwrappedLineParser.cpp | 8 
 clang/unittests/Format/FormatTest.cpp| 4 +---
 2 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 684609747a5513f..aaff6319dd45ef9 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3914,7 +3914,15 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   // (this would still leave us with an ambiguity between template function
   // and class declarations).
   if (FormatTok->isOneOf(tok::colon, tok::less)) {
+int AngleNestingLevel = 0;
 do {
+  if (FormatTok->is(tok::less))
+++AngleNestingLevel;
+  else if (FormatTok->is(tok::greater))
+--AngleNestingLevel;
+
+  if (AngleNestingLevel == 0 && FormatTok->is(tok::r_paren))
+break;
   if (FormatTok->is(tok::l_brace)) {
 calculateBraceTypes(/*ExpectClassBody=*/true);
 if (!tryToParseBracedList())
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 762fc8254bdfc9a..f304407d0ce2f46 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -14583,9 +14583,7 @@ TEST_F(FormatTest, 
UnderstandContextOfRecordTypeKeywords) {
   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
   verifyFormat("int i = SomeFunction(a b);");
 
-  // FIXME:
-  // This now gets parsed incorrectly as class definition.
-  // verifyFormat("class A f() {\n}\nint n;");
+  verifyFormat("class A f() {}\nint n;");
 
   // Elaborate types where incorrectly parsing the structural element would
   // break the indent.

>From 7a7d298c1e25940cc0607ba55eac5677b3b02f46 Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Thu, 4 Jan 2024 21:53:11 -0300
Subject: [PATCH 2/8] Fix edge case in template specialization

---
 clang/lib/Format/UnwrappedLineParser.cpp | 13 -
 1 file changed, 12 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index aaff6319dd45ef9..dc6ece09059b5d7 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3903,6 +3903,15 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   parseParens();
   }
 
+  auto IsTemplate = [&] {
+FormatToken *Tok = InitialToken.Previous;
+while (Tok) {
+  if (Tok->is(tok::kw_template))
+return true;
+  Tok = Tok->Previous;
+}
+return false;
+  };
   // Note that parsing away template declarations here leads to incorrectly
   // accepting function declarations as record declarations.
   // In general, we cannot solve this problem. Consider:
@@ -3921,8 +3930,10 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   else if (FormatTok->is(tok::greater))
 --AngleNestingLevel;
 
-  if (AngleNestingLevel == 0 && FormatTok->is(tok::r_paren))
+  if (AngleNestingLevel == 0 && !IsTemplate() &&
+  FormatTok->is(tok::r_paren)) {
 break;
+  }
   if (FormatTok->is(tok::l_brace)) {
 calculateBraceTypes(/*ExpectClassBody=*/true);
 if (!tryToParseBracedList())

>From 019992a0e227755015bc46e637d406fee911b9b5 Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Thu, 4 Jan 2024 22:13:15 -0300
Subject: [PATCH 3/8] Add test

---
 clang/unittests/Format/FormatTest.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index f304407d0ce2f46..6ac290b64ca450a 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -14584,6 +14584,7 @@ TEST_F(FormatTest, 
UnderstandContextOfRecordTypeKeywords) {
   verifyFormat("int i = SomeFunction(a b);");
 
   verifyFormat("class A f() {}\nint n;");
+  verifyFormat("template <> class Foo F() {\n} n;");
 
   // Elaborate types where incorrectly parsing the structural element would
   // break the indent.

>From e41076ed7799dc7867d8bb9854298da396307090 Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Sat, 6 Jan 2024 19:54:57 -0300
Subject: [PATCH 4/8] Add test

---
 clang/unittests/Format/TokenAnnotatorTest.cpp | 7 +++
 1 file changed, 7 insertions(+)

diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 2cafc0438ffb46a..396ed1c003e975a 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -2453,6 +2453,13 @@ 

[clang] [clang-format] Handle templated elaborated type specifier in function… (PR #77013)

2024-01-20 Thread Owen Pan via cfe-commits


@@ -3873,6 +3873,9 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   const FormatToken  = *FormatTok;
   nextToken();
 
+  auto IsNonMacroIdentifier = [](FormatToken *Tok) {

owenca wrote:

Nit:
```suggestion
  auto IsNonMacroIdentifier = [](const FormatToken *Tok) {
```

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


[clang] [clang-format]: Fix formatting of if statements with BlockIndent (PR #77699)

2024-01-20 Thread Owen Pan via cfe-commits


@@ -768,15 +768,25 @@ void 
ContinuationIndenter::addTokenOnCurrentLine(LineState , bool DryRun,
   // parenthesis by disallowing any further line breaks if there is no line
   // break after the opening parenthesis. Don't break if it doesn't conserve
   // columns.
+  const auto IsOpeningBracket = [&](const FormatToken ) {
+const auto IsStartOfBracedList = [&]() {
+  return Tok.is(tok::l_brace) && Tok.isNot(BK_Block) &&
+ Style.Cpp11BracedListStyle;
+};
+if (Tok.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) ||
+IsStartOfBracedList()) {
+  if (!Tok.Previous)
+return true;
+  if (Tok.Previous->isIf())
+return Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak;
+  return !Tok.Previous->isOneOf(TT_CastRParen, tok::kw_for, tok::kw_while,
+tok::kw_switch);
+}
+return false;

owenca wrote:

```suggestion
if (!Tok.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) &&
!IsStartOfBracedList()) {
  return false;
}
if (!Tok.Previous)
  return true;
if (Tok.Previous->isIf())
  return Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak;
return !Tok.Previous->isOneOf(TT_CastRParen, tok::kw_for, tok::kw_while,
  tok::kw_switch);
```

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


[clang] [clang-format]: Fix formatting of if statements with BlockIndent (PR #77699)

2024-01-20 Thread Owen Pan via cfe-commits


@@ -768,15 +768,25 @@ void 
ContinuationIndenter::addTokenOnCurrentLine(LineState , bool DryRun,
   // parenthesis by disallowing any further line breaks if there is no line
   // break after the opening parenthesis. Don't break if it doesn't conserve
   // columns.
+  const auto IsOpeningBracket = [&](const FormatToken ) {
+const auto IsStartOfBracedList = [&]() {

owenca wrote:

```suggestion
  auto IsOpeningBracket = [&](const FormatToken ) {
auto IsStartOfBracedList = [&]() {
```

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


[clang] 8511436 - [Frontend] Use SmallString::operator std::string (NFC)

2024-01-20 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2024-01-20T14:30:36-08:00
New Revision: 851143608e2394487d849f56ea1d4b3d3d8f2ead

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

LOG: [Frontend] Use SmallString::operator std::string (NFC)

Added: 


Modified: 
clang/lib/Frontend/CompilerInstance.cpp
clang/lib/Frontend/CompilerInvocation.cpp
clang/lib/Frontend/LogDiagnosticPrinter.cpp
clang/lib/Frontend/Rewrite/FrontendActions.cpp
clang/lib/Frontend/TextDiagnosticBuffer.cpp

Removed: 




diff  --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index 6df5521b25cc08..c258870072613c 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -543,7 +543,7 @@ std::string 
CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) {
   SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
   if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
 llvm::sys::path::append(SpecificModuleCache, ModuleHash);
-  return std::string(SpecificModuleCache.str());
+  return std::string(SpecificModuleCache);
 }
 
 // ASTContext

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index b5e192d54465b1..ed9cd1299eae28 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -3176,7 +3176,7 @@ static bool ParseHeaderSearchArgs(HeaderSearchOptions 
, ArgList ,
   llvm::sys::fs::make_absolute(WorkingDir, P);
   }
   llvm::sys::path::remove_dots(P);
-  Opts.ModuleCachePath = std::string(P.str());
+  Opts.ModuleCachePath = std::string(P);
 
   // Only the -fmodule-file== form.
   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
@@ -3217,7 +3217,7 @@ static bool ParseHeaderSearchArgs(HeaderSearchOptions 
, ArgList ,
   SmallString<32> Buffer;
   llvm::sys::path::append(Buffer, Opts.Sysroot,
   llvm::StringRef(A->getValue()).substr(1));
-  Path = std::string(Buffer.str());
+  Path = std::string(Buffer);
 }
 
 Opts.AddPath(Path, Group, IsFramework,

diff  --git a/clang/lib/Frontend/LogDiagnosticPrinter.cpp 
b/clang/lib/Frontend/LogDiagnosticPrinter.cpp
index 32fc6cb2acd875..469d1c22633aa3 100644
--- a/clang/lib/Frontend/LogDiagnosticPrinter.cpp
+++ b/clang/lib/Frontend/LogDiagnosticPrinter.cpp
@@ -134,7 +134,7 @@ void 
LogDiagnosticPrinter::HandleDiagnostic(DiagnosticsEngine::Level Level,
   // Format the message.
   SmallString<100> MessageStr;
   Info.FormatDiagnostic(MessageStr);
-  DE.Message = std::string(MessageStr.str());
+  DE.Message = std::string(MessageStr);
 
   // Set the location information.
   DE.Filename = "";

diff  --git a/clang/lib/Frontend/Rewrite/FrontendActions.cpp 
b/clang/lib/Frontend/Rewrite/FrontendActions.cpp
index 92921bf6f3d7bd..cf5a9437e89e6c 100644
--- a/clang/lib/Frontend/Rewrite/FrontendActions.cpp
+++ b/clang/lib/Frontend/Rewrite/FrontendActions.cpp
@@ -88,7 +88,7 @@ class FixItRewriteToTemp : public FixItOptions {
 llvm::sys::fs::createTemporaryFile(llvm::sys::path::filename(Filename),

llvm::sys::path::extension(Filename).drop_front(), fd,
Path);
-return std::string(Path.str());
+return std::string(Path);
   }
 };
 } // end anonymous namespace

diff  --git a/clang/lib/Frontend/TextDiagnosticBuffer.cpp 
b/clang/lib/Frontend/TextDiagnosticBuffer.cpp
index 90f273e65f88f7..681bc25f46b832 100644
--- a/clang/lib/Frontend/TextDiagnosticBuffer.cpp
+++ b/clang/lib/Frontend/TextDiagnosticBuffer.cpp
@@ -32,20 +32,20 @@ void 
TextDiagnosticBuffer::HandleDiagnostic(DiagnosticsEngine::Level Level,
  "Diagnostic not handled during diagnostic 
buffering!");
   case DiagnosticsEngine::Note:
 All.emplace_back(Level, Notes.size());
-Notes.emplace_back(Info.getLocation(), std::string(Buf.str()));
+Notes.emplace_back(Info.getLocation(), std::string(Buf));
 break;
   case DiagnosticsEngine::Warning:
 All.emplace_back(Level, Warnings.size());
-Warnings.emplace_back(Info.getLocation(), std::string(Buf.str()));
+Warnings.emplace_back(Info.getLocation(), std::string(Buf));
 break;
   case DiagnosticsEngine::Remark:
 All.emplace_back(Level, Remarks.size());
-Remarks.emplace_back(Info.getLocation(), std::string(Buf.str()));
+Remarks.emplace_back(Info.getLocation(), std::string(Buf));
 break;
   case DiagnosticsEngine::Error:
   case DiagnosticsEngine::Fatal:
 All.emplace_back(Level, Errors.size());
-Errors.emplace_back(Info.getLocation(), std::string(Buf.str()));
+Errors.emplace_back(Info.getLocation(), std::string(Buf));
 break;

[clang] 84cb8ea - [Sema] Use llvm::is_contained (NFC)

2024-01-20 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2024-01-20T14:30:30-08:00
New Revision: 84cb8eaeeb108234be1c8498688a014b87fd431d

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

LOG: [Sema] Use llvm::is_contained (NFC)

Added: 


Modified: 
clang/lib/Sema/SemaDeclAttr.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index a482919356e1bce..2a73567c2f0513c 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -9008,10 +9008,8 @@ static void handleArmNewAttr(Sema , Decl *D, const 
ParsedAttr ) {
   return;
 }
 
-if (std::find(NewState.begin(), NewState.end(), StateName) ==
-NewState.end()) { // Avoid adding duplicates.
+if (!llvm::is_contained(NewState, StateName)) // Avoid adding duplicates.
   NewState.push_back(StateName);
-}
   }
 
   if (auto *FPT = dyn_cast(D->getFunctionType())) {



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


[clang] [clang-format] Handle templated elaborated type specifier in function… (PR #77013)

2024-01-20 Thread via cfe-commits

https://github.com/XDeme updated https://github.com/llvm/llvm-project/pull/77013

>From 45d01cbc7ec958518b1739daa9e9b0dc35c2d194 Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Thu, 4 Jan 2024 19:04:21 -0300
Subject: [PATCH 1/7] [clang-format] Handle templated elaborated type specifier
 in function return type. The behaviour now is consistent with the non
 templated version

---
 clang/lib/Format/UnwrappedLineParser.cpp | 8 
 clang/unittests/Format/FormatTest.cpp| 4 +---
 2 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 684609747a5513..aaff6319dd45ef 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3914,7 +3914,15 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   // (this would still leave us with an ambiguity between template function
   // and class declarations).
   if (FormatTok->isOneOf(tok::colon, tok::less)) {
+int AngleNestingLevel = 0;
 do {
+  if (FormatTok->is(tok::less))
+++AngleNestingLevel;
+  else if (FormatTok->is(tok::greater))
+--AngleNestingLevel;
+
+  if (AngleNestingLevel == 0 && FormatTok->is(tok::r_paren))
+break;
   if (FormatTok->is(tok::l_brace)) {
 calculateBraceTypes(/*ExpectClassBody=*/true);
 if (!tryToParseBracedList())
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 762fc8254bdfc9..f304407d0ce2f4 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -14583,9 +14583,7 @@ TEST_F(FormatTest, 
UnderstandContextOfRecordTypeKeywords) {
   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
   verifyFormat("int i = SomeFunction(a b);");
 
-  // FIXME:
-  // This now gets parsed incorrectly as class definition.
-  // verifyFormat("class A f() {\n}\nint n;");
+  verifyFormat("class A f() {}\nint n;");
 
   // Elaborate types where incorrectly parsing the structural element would
   // break the indent.

>From 7a7d298c1e25940cc0607ba55eac5677b3b02f46 Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Thu, 4 Jan 2024 21:53:11 -0300
Subject: [PATCH 2/7] Fix edge case in template specialization

---
 clang/lib/Format/UnwrappedLineParser.cpp | 13 -
 1 file changed, 12 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index aaff6319dd45ef..dc6ece09059b5d 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3903,6 +3903,15 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   parseParens();
   }
 
+  auto IsTemplate = [&] {
+FormatToken *Tok = InitialToken.Previous;
+while (Tok) {
+  if (Tok->is(tok::kw_template))
+return true;
+  Tok = Tok->Previous;
+}
+return false;
+  };
   // Note that parsing away template declarations here leads to incorrectly
   // accepting function declarations as record declarations.
   // In general, we cannot solve this problem. Consider:
@@ -3921,8 +3930,10 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   else if (FormatTok->is(tok::greater))
 --AngleNestingLevel;
 
-  if (AngleNestingLevel == 0 && FormatTok->is(tok::r_paren))
+  if (AngleNestingLevel == 0 && !IsTemplate() &&
+  FormatTok->is(tok::r_paren)) {
 break;
+  }
   if (FormatTok->is(tok::l_brace)) {
 calculateBraceTypes(/*ExpectClassBody=*/true);
 if (!tryToParseBracedList())

>From 019992a0e227755015bc46e637d406fee911b9b5 Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Thu, 4 Jan 2024 22:13:15 -0300
Subject: [PATCH 3/7] Add test

---
 clang/unittests/Format/FormatTest.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index f304407d0ce2f4..6ac290b64ca450 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -14584,6 +14584,7 @@ TEST_F(FormatTest, 
UnderstandContextOfRecordTypeKeywords) {
   verifyFormat("int i = SomeFunction(a b);");
 
   verifyFormat("class A f() {}\nint n;");
+  verifyFormat("template <> class Foo F() {\n} n;");
 
   // Elaborate types where incorrectly parsing the structural element would
   // break the indent.

>From e41076ed7799dc7867d8bb9854298da396307090 Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Sat, 6 Jan 2024 19:54:57 -0300
Subject: [PATCH 4/7] Add test

---
 clang/unittests/Format/TokenAnnotatorTest.cpp | 7 +++
 1 file changed, 7 insertions(+)

diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 2cafc0438ffb46..396ed1c003e975 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -2453,6 +2453,13 @@ 

[clang] [clang-format] Add SpacesInParensOption for attributes and filtering for repeated parens (PR #77522)

2024-01-20 Thread Owen Pan via cfe-commits

owenca wrote:

> Covering all double parens in a single sub-option is not precise enough for 
> code bases that may want to have `__attribute__(( x ))` but also allow `if ( 
> ( x ) )`.

We should not go overboard with supporting all kinds of options/suboptions 
imaginable. I don't think we should support spaces between consecutive parens 
in the first place, which was likely a bug.

We can't just disregard the long-standing 
[policy](https://clang.llvm.org/docs/ClangFormatStyleOptions.html#adding-additional-style-options)
 on adding new options. If anyone thinks that policy is outdated, they should 
go through the RFC process and get it updated.

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


[clang-tools-extra] [clang] [llvm] [libcxx] [libc++][hardening] Classify assertions related to leaks and syscalls. (PR #77164)

2024-01-20 Thread Konstantin Varlamov via cfe-commits

https://github.com/var-const updated 
https://github.com/llvm/llvm-project/pull/77164

>From e28e7b3e1337cb960cdc8028a70a43740fa7d636 Mon Sep 17 00:00:00 2001
From: Konstantin Varlamov 
Date: Thu, 21 Dec 2023 14:36:47 -0800
Subject: [PATCH 1/4] [libc++][hardening] Classify assertions related to leaks
 and syscalls.

Introduce two new categories:
- `_LIBCPP_ASSERT_VALID_DEALLOCATION`;
- `_LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL`.
---
 libcxx/include/__config  | 16 
 libcxx/include/__coroutine/coroutine_handle.h| 16 
 .../__memory_resource/polymorphic_allocator.h|  3 ++-
 libcxx/src/filesystem/operations.cpp |  8 +---
 libcxx/src/memory_resource.cpp   |  3 ++-
 libcxx/src/mutex.cpp |  8 +---
 6 files changed, 38 insertions(+), 16 deletions(-)

diff --git a/libcxx/include/__config b/libcxx/include/__config
index 082c73e672c749..4d74b564864272 100644
--- a/libcxx/include/__config
+++ b/libcxx/include/__config
@@ -280,6 +280,14 @@
 // - `_LIBCPP_ASSERT_NON_OVERLAPPING_RANGES` -- for functions that take 
several ranges as arguments, checks that the
 //   given ranges do not overlap.
 //
+// - `_LIBCPP_ASSERT_VALID_DEALLOCATION` -- checks that an attempt to 
deallocate memory is valid (e.g. the given object
+//   was allocated by the given allocator). Violating this category typically 
results in a memory leak.
+//
+// - `_LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL` -- checks that a call to an 
external API (e.g. a syscall) doesn't fail in
+//   an unexpected manner. This includes triggering documented cases of 
undefined behavior in an external library (like
+//   attempting to unlock an unlocked mutex in pthreads). We generally don't 
expect these failures to compromize memory
+//   safety or otherwise create an immediate security issue.
+//
 // - `_LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR` -- checks any operations that 
exchange nodes between containers to make sure
 //   the containers have compatible allocators.
 //
@@ -327,6 +335,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 // Overlapping ranges will make algorithms produce incorrect results but don't 
directly lead to a security
 // vulnerability.
 #define _LIBCPP_ASSERT_NON_OVERLAPPING_RANGES(expression, message)   
_LIBCPP_ASSUME(expression)
+#define _LIBCPP_ASSERT_VALID_DEALLOCATION(expression, message)   
_LIBCPP_ASSUME(expression)
+#define _LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL(expression, message)  
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message) 
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message) 
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_INTERNAL(expression, message) 
_LIBCPP_ASSUME(expression)
@@ -341,6 +351,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_NULL(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_OVERLAPPING_RANGES(expression, message)   
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_DEALLOCATION(expression, message)   
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message) 
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_UNCATEGORIZED(expression, message)
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message) 
_LIBCPP_ASSERT(expression, message)
@@ -356,6 +368,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_NULL(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_NON_OVERLAPPING_RANGES(expression, message)
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_DEALLOCATION(expression, message)
_LIBCPP_ASSERT(expression, message)
+#define _LIBCPP_ASSERT_VALID_EXTERNAL_API_CALL(expression, message)   
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_COMPATIBLE_ALLOCATOR(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_PEDANTIC(expression, message)  
_LIBCPP_ASSERT(expression, message)
 #define _LIBCPP_ASSERT_INTERNAL(expression, message)  
_LIBCPP_ASSERT(expression, message)
@@ -370,6 +384,8 @@ _LIBCPP_HARDENING_MODE_DEBUG
 #define _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(expression, message)  
_LIBCPP_ASSUME(expression)
 #define _LIBCPP_ASSERT_NON_NULL(expression, message)  
_LIBCPP_ASSUME(expression)
 #

[clang] [clang-format] Handle templated elaborated type specifier in function… (PR #77013)

2024-01-20 Thread Owen Pan via cfe-commits


@@ -14583,9 +14583,10 @@ TEST_F(FormatTest, 
UnderstandContextOfRecordTypeKeywords) {
   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
   verifyFormat("int i = SomeFunction(a b);");
 
-  // FIXME:
-  // This now gets parsed incorrectly as class definition.
-  // verifyFormat("class A f() {\n}\nint n;");
+  verifyFormat("class A f() {}\nint n;");
+  verifyFormat("template  class A f() {}\nint n;");
+
+  verifyFormat("template <> class Foo F() {\n} n;");

owenca wrote:

Please wrap after newlines.

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


[clang-tools-extra] [clang-tidy] Ignore user-defined literals in google-runtime-int (PR #78859)

2024-01-20 Thread Piotr Zegar via cfe-commits


@@ -56,11 +56,14 @@ void IntegerTypesCheck::registerMatchers(MatchFinder 
*Finder) {
   // http://google.github.io/styleguide/cppguide.html#64-bit_Portability
   // "Where possible, avoid passing arguments of types specified by
   // bitwidth typedefs to printf-based APIs."
-  Finder->addMatcher(typeLoc(loc(isInteger()),
- unless(hasAncestor(callExpr(
- 
callee(functionDecl(hasAttr(attr::Format)))
- .bind("tl"),
- this);
+  Finder->addMatcher(
+  typeLoc(loc(isInteger()),
+  unless(anyOf(hasAncestor(callExpr(
+   callee(functionDecl(hasAttr(attr::Format),
+   hasParent(parmVarDecl(hasAncestor(functionDecl(
+   matchesName("operator\"\".*$"

PiotrZSL wrote:

may work, but better would be to write AST_MATCHER that would utilize this:
/// getLiteralIdentifier - The literal suffix identifier this function
/// represents, if any.
const 
[IdentifierInfo](https://clang.llvm.org/doxygen/classclang_1_1IdentifierInfo.html)
 
*[FunctionDecl::getLiteralIdentifier](https://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html#abff3536d50f040b6e96c52744a79736c)()
 const {
  if 
([getDeclName](https://clang.llvm.org/doxygen/classclang_1_1NamedDecl.html#a62f956edf003453d95cff6384168c071)().getNameKind()
 == 
[DeclarationName::CXXLiteralOperatorName](https://clang.llvm.org/doxygen/classclang_1_1DeclarationName.html#a9ab322d434446b43379d39e41af5cbe3a72a534aca2e192f3fcc66c34c16e7e19))
return 
[getDeclName](https://clang.llvm.org/doxygen/classclang_1_1NamedDecl.html#a62f956edf003453d95cff6384168c071)().[getCXXLiteralIdentifier](https://clang.llvm.org/doxygen/classclang_1_1DeclarationName.html#a63cdc12bea65df4ea28af50ca280c2fe)();
  return nullptr;
}

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


[clang-tools-extra] [clang-tidy] Ignore user-defined literals in google-runtime-int (PR #78859)

2024-01-20 Thread Piotr Zegar via cfe-commits


@@ -359,6 +359,9 @@ Changes in existing checks
   to ignore unused parameters when they are marked as unused and parameters of
   deleted functions and constructors.
 
+- Improved :doc:`google-runtime-int` check to ignore
+  false positives on user defined-literals.

PiotrZSL wrote:

should be:
```
- Improved :doc:`google-runtime-int` 
check to ignore
  false positives on user defined-literals.
```

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


[compiler-rt] [clang] [flang] [libc] [lldb] [libcxx] [clang-tools-extra] [llvm] [lld] [lld-macho] Find objects in library search path (PR #78628)

2024-01-20 Thread Vincent Lee via cfe-commits

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


[clang] [clang-format] Fix poor spacing in `AlignArrayOfStructures: Left` (PR #77868)

2024-01-20 Thread Owen Pan via cfe-commits

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


[clang] 2fc2ee1 - [clang-format] Fix poor spacing in `AlignArrayOfStructures: Left` (#77868)

2024-01-20 Thread via cfe-commits

Author: XDeme
Date: 2024-01-20T13:34:37-08:00
New Revision: 2fc2ee136c0183f40af4c0e7a8d27092b8ce3415

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

LOG: [clang-format] Fix poor spacing in `AlignArrayOfStructures: Left` (#77868)

Fixes llvm/llvm-project#62904

`AlignArrayOfStructures: Left` combined with `SpacesInParentheses: true`
causes the first cell of every row to have 1 additional space.
We were only setting the first cell of the first row to be against the
left brace, now every row will be against the left brace.

Added: 


Modified: 
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 8415c8d360d640..df84f97a8e8ac1 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1366,11 +1366,12 @@ void 
WhitespaceManager::alignArrayInitializersLeftJustified(
   auto  = CellDescs.Cells;
   // Now go through and fixup the spaces.
   auto *CellIter = Cells.begin();
-  // The first cell needs to be against the left brace.
-  if (Changes[CellIter->Index].NewlinesBefore == 0)
-Changes[CellIter->Index].Spaces = BracePadding;
-  else
-Changes[CellIter->Index].Spaces = CellDescs.InitialSpaces;
+  // The first cell of every row needs to be against the left brace.
+  for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement) {
+auto  = Changes[Next->Index];
+Change.Spaces =
+Change.NewlinesBefore == 0 ? BracePadding : CellDescs.InitialSpaces;
+  }
   ++CellIter;
   for (auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {
 auto MaxNetWidth = getMaximumNetWidth(

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 44896c10b0b251..cab495125415aa 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -21331,6 +21331,14 @@ TEST_F(FormatTest, 
CatchAlignArrayOfStructuresLeftAlignment) {
   "\" },\n"
   "};",
   Style);
+
+  Style.SpacesInParens = FormatStyle::SIPO_Custom;
+  Style.SpacesInParensOptions.Other = true;
+  verifyFormat("Foo foo[] = {\n"
+   "{1, 1},\n"
+   "{1, 1},\n"
+   "};",
+   Style);
 }
 
 TEST_F(FormatTest, UnderstandsPragmas) {



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


[clang] [clang-format] Fix poor spacing in `AlignArrayOfStructures: Left` (PR #77868)

2024-01-20 Thread Owen Pan via cfe-commits

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


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


[clang] [clang-format] Fix poor spacing in `AlignArrayOfStructures: Left` (PR #77868)

2024-01-20 Thread via cfe-commits

https://github.com/XDeme updated https://github.com/llvm/llvm-project/pull/77868

>From 9f705be37183ca030e7720707f75ffbf9feb670a Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Fri, 12 Jan 2024 00:18:56 -0300
Subject: [PATCH 1/3] [clang-format] Fix poor spacing in
 `AlignArrayOfStructures: Left` Fixes llvm/llvm-project#62904

We were only setting the first cell of the first row to be against the left 
brace,
now every row will be against the left brace.
---
 clang/lib/Format/WhitespaceManager.cpp | 11 ++-
 clang/unittests/Format/FormatTest.cpp  |  8 
 2 files changed, 14 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index f1d176f182ffa4..d91a212d357689 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1366,11 +1366,12 @@ void 
WhitespaceManager::alignArrayInitializersLeftJustified(
   auto  = CellDescs.Cells;
   // Now go through and fixup the spaces.
   auto *CellIter = Cells.begin();
-  // The first cell needs to be against the left brace.
-  if (Changes[CellIter->Index].NewlinesBefore == 0)
-Changes[CellIter->Index].Spaces = BracePadding;
-  else
-Changes[CellIter->Index].Spaces = CellDescs.InitialSpaces;
+  // The first cell of every row needs to be against the left brace.
+  for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement)
+if (Changes[Next->Index].NewlinesBefore == 0)
+  Changes[Next->Index].Spaces = BracePadding;
+else
+  Changes[Next->Index].Spaces = CellDescs.InitialSpaces;
   ++CellIter;
   for (auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {
 auto MaxNetWidth = getMaximumNetWidth(
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 8f115fb8cbf0fb..4d44a1f0a9ff97 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -21325,6 +21325,14 @@ TEST_F(FormatTest, 
CatchAlignArrayOfStructuresLeftAlignment) {
   "\" },\n"
   "};",
   Style);
+
+  Style.SpacesInParens = FormatStyle::SIPO_Custom;
+  Style.SpacesInParensOptions.Other = true;
+  verifyFormat("Foo foo[] = {\n"
+   "{1, 1},\n"
+   "{1, 1},\n"
+   "};",
+   Style);
 }
 
 TEST_F(FormatTest, UnderstandsPragmas) {

>From a0eec9816b91057bb15a7e3fb403e655b563d3e2 Mon Sep 17 00:00:00 2001
From: XDeme <66138117+xd...@users.noreply.github.com>
Date: Sat, 20 Jan 2024 18:23:13 -0300
Subject: [PATCH 2/3] Apply suggestions from code review

Co-authored-by: Owen Pan 
---
 clang/lib/Format/WhitespaceManager.cpp | 9 -
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index d91a212d357689..429c26ea261f2a 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1367,11 +1367,10 @@ void 
WhitespaceManager::alignArrayInitializersLeftJustified(
   // Now go through and fixup the spaces.
   auto *CellIter = Cells.begin();
   // The first cell of every row needs to be against the left brace.
-  for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement)
-if (Changes[Next->Index].NewlinesBefore == 0)
-  Changes[Next->Index].Spaces = BracePadding;
-else
-  Changes[Next->Index].Spaces = CellDescs.InitialSpaces;
+  for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement) {
+auto  = Changes[Next->Index];
+Change.Spaces = Change.NewlinesBefore == 0 ? BracePadding : 
CellDescs.InitialSpaces;
+  }
   ++CellIter;
   for (auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {
 auto MaxNetWidth = getMaximumNetWidth(

>From 03e654ebb5d53fef114cc6f6d692db6cb981 Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Sat, 20 Jan 2024 18:29:22 -0300
Subject: [PATCH 3/3] Format

---
 clang/lib/Format/WhitespaceManager.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 429c26ea261f2a..ee1d9f0c3dccba 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1369,7 +1369,8 @@ void 
WhitespaceManager::alignArrayInitializersLeftJustified(
   // The first cell of every row needs to be against the left brace.
   for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement) {
 auto  = Changes[Next->Index];
-Change.Spaces = Change.NewlinesBefore == 0 ? BracePadding : 
CellDescs.InitialSpaces;
+Change.Spaces =
+Change.NewlinesBefore == 0 ? BracePadding : CellDescs.InitialSpaces;
   }
   ++CellIter;
   for (auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {

___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[clang] [clang-format] Fix poor spacing in `AlignArrayOfStructures: Left` (PR #77868)

2024-01-20 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 093e6bdd4bec8ce9b3baf1e8e0a07aa6549dd5d4 
a0eec9816b91057bb15a7e3fb403e655b563d3e2 -- 
clang/lib/Format/WhitespaceManager.cpp clang/unittests/Format/FormatTest.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 429c26ea26..ee1d9f0c3d 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1369,7 +1369,8 @@ void 
WhitespaceManager::alignArrayInitializersLeftJustified(
   // The first cell of every row needs to be against the left brace.
   for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement) {
 auto  = Changes[Next->Index];
-Change.Spaces = Change.NewlinesBefore == 0 ? BracePadding : 
CellDescs.InitialSpaces;
+Change.Spaces =
+Change.NewlinesBefore == 0 ? BracePadding : CellDescs.InitialSpaces;
   }
   ++CellIter;
   for (auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {

``




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


[clang] [clang-format] Fix poor spacing in `AlignArrayOfStructures: Left` (PR #77868)

2024-01-20 Thread via cfe-commits

https://github.com/XDeme updated https://github.com/llvm/llvm-project/pull/77868

>From 9f705be37183ca030e7720707f75ffbf9feb670a Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Fri, 12 Jan 2024 00:18:56 -0300
Subject: [PATCH 1/2] [clang-format] Fix poor spacing in
 `AlignArrayOfStructures: Left` Fixes llvm/llvm-project#62904

We were only setting the first cell of the first row to be against the left 
brace,
now every row will be against the left brace.
---
 clang/lib/Format/WhitespaceManager.cpp | 11 ++-
 clang/unittests/Format/FormatTest.cpp  |  8 
 2 files changed, 14 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index f1d176f182ffa4..d91a212d357689 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1366,11 +1366,12 @@ void 
WhitespaceManager::alignArrayInitializersLeftJustified(
   auto  = CellDescs.Cells;
   // Now go through and fixup the spaces.
   auto *CellIter = Cells.begin();
-  // The first cell needs to be against the left brace.
-  if (Changes[CellIter->Index].NewlinesBefore == 0)
-Changes[CellIter->Index].Spaces = BracePadding;
-  else
-Changes[CellIter->Index].Spaces = CellDescs.InitialSpaces;
+  // The first cell of every row needs to be against the left brace.
+  for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement)
+if (Changes[Next->Index].NewlinesBefore == 0)
+  Changes[Next->Index].Spaces = BracePadding;
+else
+  Changes[Next->Index].Spaces = CellDescs.InitialSpaces;
   ++CellIter;
   for (auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {
 auto MaxNetWidth = getMaximumNetWidth(
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 8f115fb8cbf0fb..4d44a1f0a9ff97 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -21325,6 +21325,14 @@ TEST_F(FormatTest, 
CatchAlignArrayOfStructuresLeftAlignment) {
   "\" },\n"
   "};",
   Style);
+
+  Style.SpacesInParens = FormatStyle::SIPO_Custom;
+  Style.SpacesInParensOptions.Other = true;
+  verifyFormat("Foo foo[] = {\n"
+   "{1, 1},\n"
+   "{1, 1},\n"
+   "};",
+   Style);
 }
 
 TEST_F(FormatTest, UnderstandsPragmas) {

>From a0eec9816b91057bb15a7e3fb403e655b563d3e2 Mon Sep 17 00:00:00 2001
From: XDeme <66138117+xd...@users.noreply.github.com>
Date: Sat, 20 Jan 2024 18:23:13 -0300
Subject: [PATCH 2/2] Apply suggestions from code review

Co-authored-by: Owen Pan 
---
 clang/lib/Format/WhitespaceManager.cpp | 9 -
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index d91a212d357689..429c26ea261f2a 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1367,11 +1367,10 @@ void 
WhitespaceManager::alignArrayInitializersLeftJustified(
   // Now go through and fixup the spaces.
   auto *CellIter = Cells.begin();
   // The first cell of every row needs to be against the left brace.
-  for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement)
-if (Changes[Next->Index].NewlinesBefore == 0)
-  Changes[Next->Index].Spaces = BracePadding;
-else
-  Changes[Next->Index].Spaces = CellDescs.InitialSpaces;
+  for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement) {
+auto  = Changes[Next->Index];
+Change.Spaces = Change.NewlinesBefore == 0 ? BracePadding : 
CellDescs.InitialSpaces;
+  }
   ++CellIter;
   for (auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {
 auto MaxNetWidth = getMaximumNetWidth(

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


[clang] [clang-format] Fix poor spacing in `AlignArrayOfStructures: Left` (PR #77868)

2024-01-20 Thread Owen Pan via cfe-commits


@@ -1366,11 +1366,12 @@ void 
WhitespaceManager::alignArrayInitializersLeftJustified(
   auto  = CellDescs.Cells;
   // Now go through and fixup the spaces.
   auto *CellIter = Cells.begin();
-  // The first cell needs to be against the left brace.
-  if (Changes[CellIter->Index].NewlinesBefore == 0)
-Changes[CellIter->Index].Spaces = BracePadding;
-  else
-Changes[CellIter->Index].Spaces = CellDescs.InitialSpaces;
+  // The first cell of every row needs to be against the left brace.
+  for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement)
+if (Changes[Next->Index].NewlinesBefore == 0)
+  Changes[Next->Index].Spaces = BracePadding;
+else
+  Changes[Next->Index].Spaces = CellDescs.InitialSpaces;

owenca wrote:

```suggestion
  for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement) {
auto  = Changes[Next->Index];
Change.Spaces = Change.NewlinesBefore == 0 ? BracePadding : 
CellDescs.InitialSpaces;
  }
```

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


[clang] [clang-format] Add MainIncludeChar option. (PR #78752)

2024-01-20 Thread Owen Pan via cfe-commits


@@ -0,0 +1,27 @@
+// Test the combination of regrouped include directives, via regexes and

owenca wrote:

> Ok I will move them there, thanks :) Should I remove these lit tests or are 
> they complementary?

Please remove them from the lit tests.

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


[lld] [flang] [libcxx] [compiler-rt] [libc] [clang] [lldb] [clang-tools-extra] [llvm] [lld-macho] Find objects in library search path (PR #78628)

2024-01-20 Thread via cfe-commits

https://github.com/OldWorldOrdr updated 
https://github.com/llvm/llvm-project/pull/78628

>From e73fc2d0263e9e601f2964a90cfe347e8d2bb87c Mon Sep 17 00:00:00 2001
From: OldWorldOrdr 
Date: Thu, 18 Jan 2024 16:20:52 -0500
Subject: [PATCH 1/5] [lld-macho] Find objects in library search path

---
 lld/MachO/Driver.cpp | 13 +
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/lld/MachO/Driver.cpp b/lld/MachO/Driver.cpp
index 401459a054394e..f04165f5c02615 100644
--- a/lld/MachO/Driver.cpp
+++ b/lld/MachO/Driver.cpp
@@ -95,11 +95,16 @@ static std::optional findLibrary(StringRef name) 
{
   findPathCombination("lib" + name, config->librarySearchPaths,
   {".tbd", ".dylib", ".so"}))
 return path;
-  return findPathCombination("lib" + name, config->librarySearchPaths,
- {".a"});
+  else if (std::optional path = findPathCombination(
+   "lib" + name, config->librarySearchPaths, {".a"}))
+return path;
+  return findPathCombination(name, config->librarySearchPaths, {""});
 }
-return findPathCombination("lib" + name, config->librarySearchPaths,
-   {".tbd", ".dylib", ".so", ".a"});
+if (std::optional path =
+findPathCombination("lib" + name, config->librarySearchPaths,
+{".tbd", ".dylib", ".so", ".a"}))
+  return path;
+return findPathCombination(name, config->librarySearchPaths, {""});
   };
 
   std::optional path = doFind();

>From 5b29c5da6770982fb2f36edcd3a367893b18a19d Mon Sep 17 00:00:00 2001
From: OldWorldOrdr 
Date: Thu, 18 Jan 2024 21:16:57 -0500
Subject: [PATCH 2/5] [lld-macho] find objects in library search path version 2

---
 lld/MachO/Driver.cpp | 16 +++-
 1 file changed, 7 insertions(+), 9 deletions(-)

diff --git a/lld/MachO/Driver.cpp b/lld/MachO/Driver.cpp
index f04165f5c02615..f8b01da5255c6d 100644
--- a/lld/MachO/Driver.cpp
+++ b/lld/MachO/Driver.cpp
@@ -90,21 +90,19 @@ static std::optional findLibrary(StringRef name) 
{
 return entry->second;
 
   auto doFind = [&] {
+// Special case for Csu support files.
+if (name.ends_with(".o"))
+  return findPathCombination(name, config->librarySearchPaths, {""});
 if (config->searchDylibsFirst) {
   if (std::optional path =
   findPathCombination("lib" + name, config->librarySearchPaths,
   {".tbd", ".dylib", ".so"}))
 return path;
-  else if (std::optional path = findPathCombination(
-   "lib" + name, config->librarySearchPaths, {".a"}))
-return path;
-  return findPathCombination(name, config->librarySearchPaths, {""});
+  return findPathCombination("lib" + name, config->librarySearchPaths,
+ {".a"});
 }
-if (std::optional path =
-findPathCombination("lib" + name, config->librarySearchPaths,
-{".tbd", ".dylib", ".so", ".a"}))
-  return path;
-return findPathCombination(name, config->librarySearchPaths, {""});
+return findPathCombination("lib" + name, config->librarySearchPaths,
+   {".tbd", ".dylib", ".so", ".a"});
   };
 
   std::optional path = doFind();

>From 5aab87e5c580ca1dba654fb00cf9571c7e3c7999 Mon Sep 17 00:00:00 2001
From: OldWorldOrdr 
Date: Fri, 19 Jan 2024 01:32:20 -0500
Subject: [PATCH 3/5] add test case

---
 lld/test/MachO/link-csu-obj.s | 10 ++
 1 file changed, 10 insertions(+)
 create mode 100644 lld/test/MachO/link-csu-obj.s

diff --git a/lld/test/MachO/link-csu-obj.s b/lld/test/MachO/link-csu-obj.s
new file mode 100644
index 00..00cb26bb260743
--- /dev/null
+++ b/lld/test/MachO/link-csu-obj.s
@@ -0,0 +1,10 @@
+# REQUIRES: x86
+# RUN: mkdir -p %t
+# RUN: llvm-mc -filetype=obj -triple=x86_64-apple-darwin %p/Inputs/libhello.s 
-o %t/hello.o
+# RUN: llvm-mc -filetype=obj -triple=x86_64-apple-darwin %s -o %t/main.o
+# RUN: %lld -L %t %t/main.o %t/hello.o -o %t/a.out
+
+.globl _main
+_main:
+call _print_hello
+ret

>From 6e8b321b1ed74665f26e5ee6dd0a04ec7b4dbb89 Mon Sep 17 00:00:00 2001
From: OldWorldOrdr 
Date: Fri, 19 Jan 2024 11:38:25 -0500
Subject: [PATCH 4/5] Improve comment

---
 lld/MachO/Driver.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/lld/MachO/Driver.cpp b/lld/MachO/Driver.cpp
index f8b01da5255c6d..7ac3f51cec103f 100644
--- a/lld/MachO/Driver.cpp
+++ b/lld/MachO/Driver.cpp
@@ -90,7 +90,8 @@ static std::optional findLibrary(StringRef name) {
 return entry->second;
 
   auto doFind = [&] {
-// Special case for Csu support files.
+// Special case for Csu support files required for Mac OS X 10.7 and older
+// (crt1.o)
 if (name.ends_with(".o"))
   return findPathCombination(name, config->librarySearchPaths, {""});
 if (config->searchDylibsFirst) {

>From 

[clang-tools-extra] [clang-tidy] Ignore user-defined literals in google-runtime-int (PR #78859)

2024-01-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Félix-Antoine Constantin (felix642)


Changes

User-defined literals do not accept u?intXX(_t)? variables. So the check should 
not emit a warning.

Fixes #54546 #25214

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


3 Files Affected:

- (modified) clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp (+8-5) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+3) 
- (modified) clang-tools-extra/test/clang-tidy/checkers/google/runtime-int.cpp 
(+6-4) 


``diff
diff --git a/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp 
b/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
index bb4e1de8cc4b15..b60f2d0ed63112 100644
--- a/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
+++ b/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
@@ -56,11 +56,14 @@ void IntegerTypesCheck::registerMatchers(MatchFinder 
*Finder) {
   // http://google.github.io/styleguide/cppguide.html#64-bit_Portability
   // "Where possible, avoid passing arguments of types specified by
   // bitwidth typedefs to printf-based APIs."
-  Finder->addMatcher(typeLoc(loc(isInteger()),
- unless(hasAncestor(callExpr(
- 
callee(functionDecl(hasAttr(attr::Format)))
- .bind("tl"),
- this);
+  Finder->addMatcher(
+  typeLoc(loc(isInteger()),
+  unless(anyOf(hasAncestor(callExpr(
+   callee(functionDecl(hasAttr(attr::Format),
+   hasParent(parmVarDecl(hasAncestor(functionDecl(
+   matchesName("operator\"\".*$"
+  .bind("tl"),
+  this);
   IdentTable = std::make_unique(getLangOpts());
 }
 
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index a235a7d02592e8..5c857824c2b021 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -359,6 +359,9 @@ Changes in existing checks
   to ignore unused parameters when they are marked as unused and parameters of
   deleted functions and constructors.
 
+- Improved :doc:`google-runtime-int` check to ignore
+  false positives on user defined-literals.
+
 - Improved :doc:`llvm-namespace-comment
   ` check to provide fixes for
   ``inline`` namespaces in the same format as :program:`clang-format`.
diff --git a/clang-tools-extra/test/clang-tidy/checkers/google/runtime-int.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/google/runtime-int.cpp
index 4bb739876b7f4c..88f0b519e9cbee 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/google/runtime-int.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/google/runtime-int.cpp
@@ -59,11 +59,13 @@ void qux() {
 // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'short' with 
'int16'
 }
 
-// FIXME: This shouldn't warn, as UD-literal operators require one of a handful
-// of types as an argument.
 struct some_value {};
-constexpr some_value operator"" _some_literal(unsigned long long int i);
-// CHECK-MESSAGES: [[@LINE-1]]:47: warning: consider replacing 'unsigned long 
long'
+constexpr some_value operator"" _some_literal(unsigned long long int i)
+{
+  short j;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'short' with 
'int16'
+  return some_value();
+}
 
 struct A { A& operator=(const A&); };
 class B { A a[0]; };

``




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


[clang-tools-extra] [clang-tidy] Ignore user-defined literals in google-runtime-int (PR #78859)

2024-01-20 Thread Félix-Antoine Constantin via cfe-commits

https://github.com/felix642 created 
https://github.com/llvm/llvm-project/pull/78859

User-defined literals do not accept u?intXX(_t)? variables. So the check should 
not emit a warning.

Fixes #54546 #25214

From 8ea205ae2324d67f9adaf30d5662d2cde2096534 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Sat, 20 Jan 2024 15:29:06 -0500
Subject: [PATCH] [clang-tidy] Ignore user-defined literals in
 google-runtime-int

User-defined literals do not accept u?intXX(_t)? variables.
So the check should not emit a warning.

Fixes #54546 #25214
---
 .../clang-tidy/google/IntegerTypesCheck.cpp | 13 -
 clang-tools-extra/docs/ReleaseNotes.rst |  3 +++
 .../test/clang-tidy/checkers/google/runtime-int.cpp | 10 ++
 3 files changed, 17 insertions(+), 9 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp 
b/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
index bb4e1de8cc4b15..b60f2d0ed63112 100644
--- a/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
+++ b/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
@@ -56,11 +56,14 @@ void IntegerTypesCheck::registerMatchers(MatchFinder 
*Finder) {
   // http://google.github.io/styleguide/cppguide.html#64-bit_Portability
   // "Where possible, avoid passing arguments of types specified by
   // bitwidth typedefs to printf-based APIs."
-  Finder->addMatcher(typeLoc(loc(isInteger()),
- unless(hasAncestor(callExpr(
- 
callee(functionDecl(hasAttr(attr::Format)))
- .bind("tl"),
- this);
+  Finder->addMatcher(
+  typeLoc(loc(isInteger()),
+  unless(anyOf(hasAncestor(callExpr(
+   callee(functionDecl(hasAttr(attr::Format),
+   hasParent(parmVarDecl(hasAncestor(functionDecl(
+   matchesName("operator\"\".*$"
+  .bind("tl"),
+  this);
   IdentTable = std::make_unique(getLangOpts());
 }
 
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index a235a7d02592e8..5c857824c2b021 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -359,6 +359,9 @@ Changes in existing checks
   to ignore unused parameters when they are marked as unused and parameters of
   deleted functions and constructors.
 
+- Improved :doc:`google-runtime-int` check to ignore
+  false positives on user defined-literals.
+
 - Improved :doc:`llvm-namespace-comment
   ` check to provide fixes for
   ``inline`` namespaces in the same format as :program:`clang-format`.
diff --git a/clang-tools-extra/test/clang-tidy/checkers/google/runtime-int.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/google/runtime-int.cpp
index 4bb739876b7f4c..88f0b519e9cbee 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/google/runtime-int.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/google/runtime-int.cpp
@@ -59,11 +59,13 @@ void qux() {
 // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'short' with 
'int16'
 }
 
-// FIXME: This shouldn't warn, as UD-literal operators require one of a handful
-// of types as an argument.
 struct some_value {};
-constexpr some_value operator"" _some_literal(unsigned long long int i);
-// CHECK-MESSAGES: [[@LINE-1]]:47: warning: consider replacing 'unsigned long 
long'
+constexpr some_value operator"" _some_literal(unsigned long long int i)
+{
+  short j;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'short' with 
'int16'
+  return some_value();
+}
 
 struct A { A& operator=(const A&); };
 class B { A a[0]; };

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


[clang] [clang-format] Fix poor spacing in `AlignArrayOfStructures: Left` (PR #77868)

2024-01-20 Thread Björn Schäpers via cfe-commits

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

Sorry, seems I've missed this change.

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


[clang] [clang-format] NEVER allow && to be an unary operator. (PR #78852)

2024-01-20 Thread Björn Schäpers via cfe-commits

HazardyKnusperkeks wrote:

Never knew that, and I'm sad I do now...
But based on the documentation one could just check the previous token to be 
one of `={,-+(`.

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


[compiler-rt] [lld] [libcxx] [openmp] [llvm] [clang-tools-extra] [flang] [clang] [mlir] [libc] [lldb] [libc++][format] P2637R3: Member `visit` (`std::basic_format_arg`) (PR #76449)

2024-01-20 Thread Mark de Wever via cfe-commits

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

Still LGTM!

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


[compiler-rt] [libc] [flang] [mlir] [libcxx] [lldb] [clang-tools-extra] [openmp] [clang] [llvm] [lld] [libc++][variant] P2637R3: Member `visit` (`std::variant`) (PR #76447)

2024-01-20 Thread Mark de Wever via cfe-commits

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

LGTM!

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


[clang-tools-extra] [llvm] [clang] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-20 Thread Julian Schmidt via cfe-commits

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


[clang] [clang-format] Allow decltype in requires clause (PR #78847)

2024-01-20 Thread Björn Schäpers via cfe-commits


@@ -1071,6 +1071,16 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsRequiresClausesAndConcepts) {
 "concept C = (!Foo) && Bar;");
   ASSERT_EQ(Tokens.size(), 19u) << Tokens;
   EXPECT_TOKEN(Tokens[15], tok::ampamp, TT_BinaryOperator);
+
+  Tokens = annotate("void f() & requires(C) {}");
+  ASSERT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::amp, TT_PointerOrReference);
+  EXPECT_TOKEN(Tokens[5], tok::kw_requires, TT_RequiresClause);
+
+  Tokens = annotate("auto f() -> int& requires(C) {}");
+  ASSERT_EQ(Tokens.size(), 20u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::amp, TT_PointerOrReference);
+  EXPECT_TOKEN(Tokens[7], tok::kw_requires, TT_RequiresClause);
 }

HazardyKnusperkeks wrote:

For the mentioned test coverage (you are completely right), something like:
```c++
int foo(auto t) {
if (requires (decltype(t) x) {x.foo();}) {
return 1;
}
return 0;
}
```

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


[clang] [clang][modules] Print library module manifest path. (PR #76451)

2024-01-20 Thread Mark de Wever via cfe-commits

https://github.com/mordante updated 
https://github.com/llvm/llvm-project/pull/76451

>From f3f0db64da4d341f8e4a2054f9f25c87f8eda829 Mon Sep 17 00:00:00 2001
From: Mark de Wever 
Date: Wed, 27 Dec 2023 17:34:10 +0100
Subject: [PATCH 1/7] [clang][modules] Print library module manifest path.

This implements a way for the compiler to find the modules.json
associated with the C++23 Standard library modules.

This is based on a discussion in SG15. At the moment no Standard library
installs this manifest. #75741 adds this feature in libc++.
---
 clang/include/clang/Driver/Driver.h   | 10 +
 clang/include/clang/Driver/Options.td |  3 ++
 clang/lib/Driver/Driver.cpp   | 40 +++
 .../usr/lib/x86_64-linux-gnu/libc++.so|  0
 .../usr/lib/x86_64-linux-gnu/modules.json |  0
 ...dules-print-library-module-manifest-path.c | 15 +++
 ...arwin-print-library-module-manifest-path.c |  9 +
 7 files changed, 77 insertions(+)
 create mode 100644 
clang/test/Driver/Inputs/cxx23_modules/usr/lib/x86_64-linux-gnu/libc++.so
 create mode 100644 
clang/test/Driver/Inputs/cxx23_modules/usr/lib/x86_64-linux-gnu/modules.json
 create mode 100644 
clang/test/Driver/cxx23-modules-print-library-module-manifest-path.c
 create mode 100644 
clang/test/Driver/darwin-print-library-module-manifest-path.c

diff --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index 3ee1bcf2a69c9b..2e1e3b128744ff 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -602,6 +602,16 @@ class Driver {
   // FIXME: This should be in CompilationInfo.
   std::string GetProgramPath(StringRef Name, const ToolChain ) const;
 
+  /// GetModuleManifestPath - Lookup the name of the Standard library manifest.
+  ///
+  /// \param C - The compilation.
+  /// \param TC - The tool chain for additional information on
+  /// directories to search.
+  //
+  // FIXME: This should be in CompilationInfo.
+  std::string GetModuleManifestPath(const Compilation ,
+const ToolChain ) const;
+
   /// HandleAutocompletions - Handle --autocomplete by searching and printing
   /// possible flags, descriptions, and its arguments.
   void HandleAutocompletions(StringRef PassedFlags) const;
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 2b93ddf033499c..890257e11485b6 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5280,6 +5280,9 @@ def print_resource_dir : Flag<["-", "--"], 
"print-resource-dir">,
 def print_search_dirs : Flag<["-", "--"], "print-search-dirs">,
   HelpText<"Print the paths used for finding libraries and programs">,
   Visibility<[ClangOption, CLOption]>;
+def print_library_module_manifest_path : Flag<["-", "--"], 
"print-library-module-manifest-path">,
+  HelpText<"Print the path for the C++ Standard library module manifest">,
+  Visibility<[ClangOption, CLOption]>;
 def print_targets : Flag<["-", "--"], "print-targets">,
   HelpText<"Print the registered targets">,
   Visibility<[ClangOption, CLOption]>;
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index ff95c899c5f3d4..8d682f9238c6b8 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -2164,6 +2164,12 @@ bool Driver::HandleImmediateArgs(const Compilation ) {
 return false;
   }
 
+  if (C.getArgs().hasArg(options::OPT_print_library_module_manifest_path)) {
+llvm::outs() << "module: ="
+ << GetModuleManifestPath(C, C.getDefaultToolChain()) << '\n';
+return false;
+  }
+
   if (C.getArgs().hasArg(options::OPT_print_runtime_dir)) {
 if (std::optional RuntimePath = TC.getRuntimePath())
   llvm::outs() << *RuntimePath << '\n';
@@ -6135,6 +6141,40 @@ std::string Driver::GetProgramPath(StringRef Name, const 
ToolChain ) const {
   return std::string(Name);
 }
 
+std::string Driver::GetModuleManifestPath(const Compilation ,
+  const ToolChain ) const {
+
+  switch (TC.GetCXXStdlibType(C.getArgs())) {
+  case ToolChain::CST_Libcxx: {
+std::string lib = "libc++.so";
+std::string path = GetFilePath(lib, TC);
+
+// Note when there are multiple flavours of libc++ the module json needs to
+// look at the command-line arguments for the proper json.
+
+// For example
+/*
+const SanitizerArgs  = TC.getSanitizerArgs(C.getArgs());
+if (Sanitize.needsAsanRt())
+  return path.replace(path.size() - lib.size(), lib.size(),
+  "modules-asan.json");
+*/
+
+path = path.replace(path.size() - lib.size(), lib.size(), "modules.json");
+if (TC.getVFS().exists(path))
+  return path;
+
+return "";
+  }
+
+  case ToolChain::CST_Libstdcxx:
+// libstdc++ does not provide Standard library modules yet.
+return "";
+  }
+
+  return "";
+}
+
 std::string 

[compiler-rt] [lld] [libcxx] [openmp] [llvm] [clang-tools-extra] [flang] [clang] [mlir] [libc] [lldb] [libc++][format] P2637R3: Member `visit` (`std::basic_format_arg`) (PR #76449)

2024-01-20 Thread Hristo Hristov via cfe-commits

H-G-Hristov wrote:

@mordante Could you please have another look at the test/latest update.

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


[llvm] [clang] [clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-20 Thread Julian Schmidt via cfe-commits

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


[clang-tools-extra] [llvm] [clang] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-20 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,135 @@
+//===--- UseStdMinMaxCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStdMinMaxCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+static const llvm::StringRef AlgorithmHeader("");
+
+UseStdMinMaxCheck::UseStdMinMaxCheck(StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM),
+  areDiagsSelfContained()) {}
+
+void UseStdMinMaxCheck::storeOptions(ClangTidyOptions::OptionMap ) {
+  Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
+}
+
+void UseStdMinMaxCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  ifStmt(
+  hasCondition(binaryOperator(hasAnyOperatorName("<", ">", "<=", ">="),
+  hasLHS(expr().bind("CondLhs")),
+  hasRHS(expr().bind("CondRhs",
+  hasThen(anyOf(stmt(binaryOperator(hasOperatorName("="),
+hasLHS(expr().bind("AssignLhs")),
+hasRHS(expr().bind("AssignRhs",
+compoundStmt(has(binaryOperator(
+ hasOperatorName("="),
+ hasLHS(expr().bind("AssignLhs")),
+ hasRHS(expr().bind("AssignRhs")
+.bind("compound"
+  .bind("if"),
+  this);
+}
+
+void UseStdMinMaxCheck::registerPPCallbacks(const SourceManager ,
+Preprocessor *PP,
+Preprocessor *ModuleExpanderPP) {
+  IncludeInserter.registerPreprocessor(PP);
+}
+
+void UseStdMinMaxCheck::check(const MatchFinder::MatchResult ) {
+  const auto *CondLhs = Result.Nodes.getNodeAs("CondLhs");
+  const auto *CondRhs = Result.Nodes.getNodeAs("CondRhs");
+  const auto *AssignLhs = Result.Nodes.getNodeAs("AssignLhs");
+  const auto *AssignRhs = Result.Nodes.getNodeAs("AssignRhs");
+  const auto *If = Result.Nodes.getNodeAs("if");
+  const auto *Compound = Result.Nodes.getNodeAs("compound");
+  const auto  = *Result.Context;
+  const auto  = Context.getLangOpts();
+  const SourceManager  = Context.getSourceManager();
+
+  const auto *BinaryOp = dyn_cast(If->getCond());
+  if (!BinaryOp || If->hasElseStorage())
+return;
+
+  if (Compound) {
+if (Compound->size() > 1)
+  return;
+  }
+
+  const SourceLocation IfLocation = If->getIfLoc();
+  const SourceLocation ThenLocation = If->getEndLoc();
+
+  if (IfLocation.isMacroID() || ThenLocation.isMacroID())
+return;
+
+  const auto CreateReplacement = [&](bool UseMax) {
+const auto *FunctionName = UseMax ? "std::max" : "std::min";
+const auto CondLhsStr = Lexer::getSourceText(
+Source.getExpansionRange(CondLhs->getSourceRange()), Source, LO);
+const auto CondRhsStr = Lexer::getSourceText(
+Source.getExpansionRange(CondRhs->getSourceRange()), Source, LO);
+const auto AssignLhsStr = Lexer::getSourceText(
+Source.getExpansionRange(AssignLhs->getSourceRange()), Source, LO);
+const auto AssignLhsType =
+AssignLhs->getType().getCanonicalType().getAsString();
+return (AssignLhsStr + " = " + FunctionName + "<" + AssignLhsType + ">(" +

5chmidti wrote:

And I don't think we would want to use the canonical type. When the user 
specified a type for the variable, it should be used what the user wrote.

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


[llvm] [clang] [clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-20 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti commented:

@11happy, regarding the statement count:
The tests work when I add `statementCountIs(1),` right after `compoundStmt(` -> 
`compoundStmt(statementCountIs(1),`. I removed the bound node, `Compound` and 
the `Compoind->size() > 1` check. But the tests should still succeed even if 
you leave the rest as is.

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


[clang] [clang-tools-extra] [llvm] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-20 Thread Julian Schmidt via cfe-commits

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


[clang] [clang-tools-extra] [llvm] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-20 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,129 @@
+//===--- UseStdMinMaxCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseStdMinMaxCheck.h"
+#include "../utils/ASTUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 

5chmidti wrote:

Unused include ``

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


[openmp] [libc] [mlir] [lld] [llvm] [clang] [clang-tools-extra] [compiler-rt] [lldb] [flang] [libcxx] [libc++][format] P2637R3: Member `visit` (`std::basic_format_arg`) (PR #76449)

2024-01-20 Thread Hristo Hristov via cfe-commits


@@ -1513,6 +1519,11 @@ 
__sanitizer_verify_double_ended_contiguous_container(const void*, const void*, c
 #define _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
 #  endif
 
+// Clang-18 has support for deducing this, but it does not set the FTM.
+#if defined(__cpp_explicit_this_parameter) || (defined(_LIBCPP_CLANG_VER ) 
&&_LIBCPP_CLANG_VER >= 1800)
+#  define _LIBCPP_HAS_EXPLICIT_THIS_PARAMETER
+#endif
+

H-G-Hristov wrote:

Of course!

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


[clang] [clang-format] Allow decltype in requires clause (PR #78847)

2024-01-20 Thread Björn Schäpers via cfe-commits


@@ -1071,6 +1071,16 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsRequiresClausesAndConcepts) {
 "concept C = (!Foo) && Bar;");

HazardyKnusperkeks wrote:

I'm in favor. Just for the correctness.

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


[clang] [clang-format] Support of TableGen statements in unwrapped line parser (PR #78846)

2024-01-20 Thread Björn Schäpers via cfe-commits


@@ -2743,6 +2760,14 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
 }
   }
 
+  // TableGen's if statement has the form of `if  then { ... }`.
+  if (Style.isTableGen()) {
+while (!eof() && !(FormatTok->is(Keywords.kw_then))) {

HazardyKnusperkeks wrote:

```suggestion
while (!eof() && FormatTok->isNot(Keywords.kw_then)) {
```

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


[clang] [clang-format] Do not update cursor pos if no includes replacement (PR #77456)

2024-01-20 Thread Björn Schäpers via cfe-commits

HazardyKnusperkeks wrote:

> Oh, sorry @HazardyKnusperkeks I missed this in your previous comment.
> 
> I've updated the PR.
> 
> As a side note, I tried adding these two tests but they fail, meaning the 
> cursor is still incorrectly computed with CRLF when replacing lines.
> 
> This is due to adding lines between the include groups (with Regroup option), 
> as this new line is added with only the character `\n` (while the line break 
> between include lines is right because the include line itself contains a 
> trailing `\r`). I am not sure how to fix this correctly because I do not want 
> to break things by trimming the include line and I do not think 
> `sortCppIncludes` should manage whitespaces (`WhitespaceManager` seems to be 
> the correct class to handle this?). Maybe the cursor should be updated when 
> replacing these whitespaces?
> 
> ```c++
> TEST_F(
>SortIncludesTest,
>
> CalculatesCorrectCursorPositionWhenNewLineReplacementsWithRegroupingAndCRLF) {
>   Style.IncludeBlocks   = Style.IBS_Regroup;
>   FmtStyle.LineEnding   = FormatStyle::LE_CRLF;
>   Style.IncludeCategories = {
>   {"^\"a\"", 0, 0, false}, {"^\"b\"", 1, 1, false}, {".*", 2, 2, false}};
>   std::string Code = "#include \"a\"\r\n" // Start of line: 0
>  "#include \"b\"\r\n" // Start of line: 14
>  "#include \"c\"\r\n" // Start of line: 28
>  "\r\n"   // Start of line: 42
>  "int i;";// Start of line: 44
>   std::string Expected = "#include \"a\"\r\n" // Start of line: 0
>  "\r\n"   // Start of line: 14
>  "#include \"b\"\r\n" // Start of line: 16
>  "\r\n"   // Start of line: 30
>  "#include \"c\"\r\n" // Start of line: 32
>  "\r\n"   // Start of line: 46
>  "int i;";// Start of line: 48
>   EXPECT_EQ(Expected, sort(Code));
>   EXPECT_EQ(0u, newCursor(Code, 0));
>   EXPECT_EQ(15u, newCursor(Code, 14)); // FIXME: should expect 16, caused by 
> \r
>   EXPECT_EQ(30u, newCursor(Code, 28)); // FIXME: should expect 32, caused by 
> \r
>   EXPECT_EQ(44u, newCursor(Code, 42)); // FIXME: should expect 46, caused by 
> \r
>   EXPECT_EQ(46u, newCursor(Code, 44)); // FIXME: should expect 48, caused by 
> \r
> }
> 
> TEST_F(
>SortIncludesTest,
>
> CalculatesCorrectCursorPositionWhenNoNewLineReplacementsWithRegroupingAndCRLF)
>  {
>   Style.IncludeBlocks = Style.IBS_Regroup;
>   FmtStyle.LineEnding = FormatStyle::LE_CRLF;
>   Style.IncludeCategories = {
>   {"^\"a\"", 0, 0, false}, {"^\"b\"", 1, 1, false}, {".*", 2, 2, false}};
>   std::string Code = "#include \"a\"\r\n" // Start of line: 0
>  "\r\n"   // Start of line: 14
>  "#include \"c\"\r\n" // Start of line: 16
>  "\r\n"   // Start of line: 30
>  "#include \"b\"\r\n" // Start of line: 32
>  "\r\n"   // Start of line: 46
>  "int i;";// Start of line: 48
>   std::string Expected = "#include \"a\"\r\n" // Start of line: 0
>  "\r\n"   // Start of line: 14
>  "#include \"b\"\r\n" // Start of line: 16
>  "\r\n"   // Start of line: 30
>  "#include \"c\"\r\n" // Start of line: 32
>  "\r\n"   // Start of line: 46
>  "int i;";// Start of line: 48
>   EXPECT_EQ(Expected, sort(Code));
>   EXPECT_EQ(0u, newCursor(Code, 0));
>   EXPECT_EQ(14u, newCursor(Code, 14));
>   EXPECT_EQ(30u, newCursor(Code, 16)); // FIXME: should expect 32, caused by 
> \r
>   EXPECT_EQ(30u, newCursor(Code, 30));
>   EXPECT_EQ(15u, newCursor(Code, 32)); // FIXME: should expect 15, caused by 
> \r
>   EXPECT_EQ(44u, newCursor(Code, 46)); // FIXME: should expect 46, caused by 
> \r
>   EXPECT_EQ(46u, newCursor(Code, 48)); // FIXME: should expect 48, caused by 
> \r
> }
> ```

That's outside my comfortable zone and I'll refer to @owenca or @mydeveloperday.

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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-20 Thread Björn Schäpers via cfe-commits

HazardyKnusperkeks wrote:

> > I think splitting the two features would be better.
> 
> I'm going to close this MR and create two new ones.
> 
> > Also please add a note to the changelog.
> 
> Where can I find the changelog?

`clang/docs/ReleaseNotes.rst`

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


[clang] [clang-format] Add MainIncludeChar option. (PR #78752)

2024-01-20 Thread Björn Schäpers via cfe-commits


@@ -0,0 +1,27 @@
+// Test the combination of regrouped include directives, via regexes and

HazardyKnusperkeks wrote:

I've never run anything but the unit tests. I'd remove these, but I have no 
strong opinion on that matter.

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


  1   2   3   >