[clang] 96336ac - [clang][bytecode] Tighten double-destroy check (#129528)

2025-03-03 Thread via cfe-commits

Author: Timm Baeder
Date: 2025-03-03T16:26:56+01:00
New Revision: 96336acb48562edcae59eb1d5d4acb0200efeded

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

LOG: [clang][bytecode] Tighten double-destroy check (#129528)

The instance pointer of the current function being the same as the one
we're destroying is only relevant if said function is also a destructor.

Added: 


Modified: 
clang/lib/AST/ByteCode/Interp.cpp
clang/test/AST/ByteCode/new-delete.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Interp.cpp 
b/clang/lib/AST/ByteCode/Interp.cpp
index 5e0d2e91fb1b2..67b7ac1f8f0f9 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -992,7 +992,8 @@ static bool runRecordDestructor(InterpState &S, CodePtr 
OpPC,
   const Record *R = Desc->ElemRecord;
   assert(R);
 
-  if (Pointer::pointToSameBlock(BasePtr, S.Current->getThis())) {
+  if (Pointer::pointToSameBlock(BasePtr, S.Current->getThis()) &&
+  S.Current->getFunction()->isDestructor()) {
 const SourceInfo &Loc = S.Current->getSource(OpPC);
 S.FFDiag(Loc, diag::note_constexpr_double_destroy);
 return false;

diff  --git a/clang/test/AST/ByteCode/new-delete.cpp 
b/clang/test/AST/ByteCode/new-delete.cpp
index a85ddaf29caf4..bd7351cbc3d4c 100644
--- a/clang/test/AST/ByteCode/new-delete.cpp
+++ b/clang/test/AST/ByteCode/new-delete.cpp
@@ -558,6 +558,11 @@ namespace DeleteThis {
   }
   static_assert(super_secret_double_delete()); // both-error {{not an integral 
constant expression}} \
// both-note {{in call to 
'super_secret_double_delete()'}}
+
+  struct B {
+constexpr void reset() { delete this; }
+  };
+  static_assert(((new B)->reset(), true));
 }
 
 namespace CastedDelete {



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


[clang-tools-extra] dd3c4fb - [clang-tidy][doc] Contributing.rst update snippet and docs (#129209)

2025-03-03 Thread via cfe-commits

Author: Marco C.
Date: 2025-02-28T20:18:13+01:00
New Revision: dd3c4fbec9ce72cd741280aedbba7a643ff78654

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

LOG: [clang-tidy][doc] Contributing.rst update snippet and docs (#129209)

This reflects the add_new_check.py changes: isLanguageVersionSupported
is now overridden by default by the script

The changes were instroduced in
https://github.com/llvm/llvm-project/pull/100129

Thanks

Added: 


Modified: 
clang-tools-extra/docs/clang-tidy/Contributing.rst

Removed: 




diff  --git a/clang-tools-extra/docs/clang-tidy/Contributing.rst 
b/clang-tools-extra/docs/clang-tidy/Contributing.rst
index 4f1df8d11..9611c655886f2 100644
--- a/clang-tools-extra/docs/clang-tidy/Contributing.rst
+++ b/clang-tools-extra/docs/clang-tidy/Contributing.rst
@@ -149,6 +149,9 @@ After choosing the module and the name for the check, run 
the
 ``clang-tidy/add_new_check.py`` script to create the skeleton of the check and
 plug it to :program:`clang-tidy`. It's the recommended way of adding new 
checks.
 
+By default, the new check will apply only to C++ code. If it should apply under
+
diff erent language options, use the ``--language`` script's parameter.
+
 If we want to create a `readability-awesome-function-names`, we would run:
 
 .. code-block:: console
@@ -171,9 +174,7 @@ Let's see in more detail at the check class definition:
 
   #include "../ClangTidyCheck.h"
 
-  namespace clang {
-  namespace tidy {
-  namespace readability {
+  namespace clang::tidy::readability {
 
   ...
   class AwesomeFunctionNamesCheck : public ClangTidyCheck {
@@ -182,11 +183,12 @@ Let's see in more detail at the check class definition:
 : ClangTidyCheck(Name, Context) {}
 void registerMatchers(ast_matchers::MatchFinder *Finder) override;
 void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+bool isLanguageVersionSupported(const LangOptions &LangOpts) const 
override {
+  return LangOpts.CPlusPlus;
+}
   };
 
-  } // namespace readability
-  } // namespace tidy
-  } // namespace clang
+  } // namespace clang::tidy::readability
 
   ...
 
@@ -231,9 +233,6 @@ override the method ``registerPPCallbacks``.  The 
``add_new_check.py`` script
 does not generate an override for this method in the starting point for your
 new check.
 
-If your check applies only under a specific set of language options, be sure
-to override the method ``isLanguageVersionSupported`` to reflect that.
-
 Check development tips
 --
 



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


[clang] a3584fb - [NFC] Fix Windows after #121115 (#129534)

2025-03-03 Thread via cfe-commits

Author: Chris B
Date: 2025-03-03T10:27:02-06:00
New Revision: a3584fb13eebeb736aba20ed1d0dfa77fc73c552

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

LOG: [NFC] Fix Windows after #121115 (#129534)

Added: 


Modified: 
clang/test/Driver/sanitizer-ld.c

Removed: 




diff  --git a/clang/test/Driver/sanitizer-ld.c 
b/clang/test/Driver/sanitizer-ld.c
index b084edcb66ab1..f9c3506e43208 100644
--- a/clang/test/Driver/sanitizer-ld.c
+++ b/clang/test/Driver/sanitizer-ld.c
@@ -514,7 +514,7 @@
 // RUN: -resource-dir=%S/Inputs/resource_dir \
 // RUN: --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | %{filecheck} --check-prefix=CHECK-UBSAN-LINUX-LINK-CXX
-// CHECK-UBSAN-LINUX-LINK-CXX: "{{.*}}ld"
+// CHECK-UBSAN-LINUX-LINK-CXX: "{{.*}}ld{{(.exe)?}}"
 // CHECK-UBSAN-LINUX-LINK-CXX-NOT: "-lstdc++"
 // CHECK-UBSAN-LINUX-LINK-CXX: "--whole-archive" 
"{{.*}}libclang_rt.ubsan_standalone.a" "--no-whole-archive"
 
@@ -544,7 +544,7 @@
 // RUN: -resource-dir=%S/Inputs/resource_dir \
 // RUN: --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | %{filecheck}--check-prefix=CHECK-VPTR-LINUX-CXX
-// CHECK-VPTR-LINUX-CXX: "{{.*}}ld"
+// CHECK-VPTR-LINUX-CXX: "{{.*}}ld{{(.exe)?}}"
 // CHECK-VPTR-LINUX-CXX-SAME: "--whole-archive" 
"{{.*}}libclang_rt.ubsan_standalone.a" "--no-whole-archive"
 // CHECK-VPTR-LINUX-CXX-SAME: "--whole-archive" 
"{{.*}}libclang_rt.ubsan_standalone_cxx.a" "--no-whole-archive"
 // CHECK-VPTR-LINUX-CXX-SAME: "-lstdc++"
@@ -618,7 +618,7 @@
 // RUN: -resource-dir=%S/Inputs/resource_dir \
 // RUN: --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | %{filecheck} --check-prefix=CHECK-ASAN-VPTR-LINUX-CXX
-// CHECK-ASAN-VPTR-LINUX-CXX: "{{.*}}ld"
+// CHECK-ASAN-VPTR-LINUX-CXX: "{{.*}}ld{{(.exe)?}}"
 // CHECK-ASAN-VPTR-LINUX-CXX-SAME: "--whole-archive" 
"{{.*}}libclang_rt.asan_static.a" "--no-whole-archive"
 // CHECK-ASAN-VPTR-LINUX-CXX-SAME: "--whole-archive" 
"{{.*}}libclang_rt.asan.a" "--no-whole-archive"
 // CHECK-ASAN-VPTR-LINUX-CXX-SAME: 
"--dynamic-list={{.*}}libclang_rt.asan.a.syms"
@@ -658,7 +658,7 @@
 // RUN: -resource-dir=%S/Inputs/resource_dir \
 // RUN: --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | %{filecheck} --check-prefix=CHECK-MSAN-VPTR-LINUX-CXX
-// CHECK-MSAN-VPTR-LINUX-CXX: "{{.*}}ld"
+// CHECK-MSAN-VPTR-LINUX-CXX: "{{.*}}ld{{(.exe)?}}"
 // CHECK-MSAN-VPTR-LINUX-CXX-SAME: "--whole-archive" 
"{{.*}}libclang_rt.msan.a" "--no-whole-archive"
 // CHECK-MSAN-VPTR-LINUX-CXX-SAME: 
"--dynamic-list={{.*}}libclang_rt.msan.a.syms"
 // CHECK-MSAN-VPTR-LINUX-CXX-SAME: "--whole-archive" 
"{{.*}}libclang_rt.msan_cxx.a" "--no-whole-archive"
@@ -681,7 +681,7 @@
 // RUN: -resource-dir=%S/Inputs/resource_dir \
 // RUN: --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | %{filecheck} --check-prefix=CHECK-TSAN-VPTR-LINUX-CXX
-// CHECK-TSAN-VPTR-LINUX-CXX: "{{.*}}ld"
+// CHECK-TSAN-VPTR-LINUX-CXX: "{{.*}}ld{{(.exe)?}}"
 // CHECK-TSAN-VPTR-LINUX-CXX-SAME: "--whole-archive" 
"{{.*}}libclang_rt.tsan.a" "--no-whole-archive"
 // CHECK-TSAN-VPTR-LINUX-CXX-SAME: 
"--dynamic-list={{.*}}libclang_rt.tsan.a.syms"
 // CHECK-TSAN-VPTR-LINUX-CXX-SAME: "--whole-archive" 
"{{.*}}libclang_rt.tsan_cxx.a" "--no-whole-archive"



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


[clang] d37a392 - [CUDA][HIP] fix virtual dtor host/device attr (#128926)

2025-03-03 Thread via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2025-03-03T10:23:35-05:00
New Revision: d37a39207bc15507e602e41b7655f615c10c9a1d

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

LOG: [CUDA][HIP] fix virtual dtor host/device attr (#128926)

Currently if CUDA/HIP users use template class with virtual dtor
and std::string data member with C++20 and MSVC. When the template
class is explicitly instantiated, there is error about host
function called by host device function (used to be undefined
symbols in linking stage before member destructors were checked
by deferred diagnostics).

It was caused by clang inferring host/device attributes for
default dtors. Since all dtors of member and parent classes
have implicit host device attrs, clang infers the virtual dtor have
implicit host and device attrs. Since virtual dtor of
explicitly instantiated template class must be emitted,
this causes constexpr dtor of std::string emitted, which
calls a host function which was not emitted on device side.

This is a serious issue since it prevents users from
using std::string with C++20 on Windows.

When inferring host device attr of virtual dtor of explicit
template class instantiation, clang should be conservative
since it is sure to be emitted. Since an implicit host device
function may call a host function, clang cannot assume it is
always available on device. This guarantees dtors that
may call host functions not to have implicit device attr,
therefore will not be emitted on device side.

Fixes: https://github.com/llvm/llvm-project/issues/108548

Fixes: SWDEV-517435

Added: 


Modified: 
clang/docs/HIPSupport.rst
clang/lib/Sema/SemaCUDA.cpp
clang/test/SemaCUDA/dtor.cu

Removed: 




diff  --git a/clang/docs/HIPSupport.rst b/clang/docs/HIPSupport.rst
index 481ed39230813..8f473c21e1918 100644
--- a/clang/docs/HIPSupport.rst
+++ b/clang/docs/HIPSupport.rst
@@ -286,6 +286,26 @@ Example Usage
   basePtr->virtualFunction(); // Allowed since obj is constructed in 
device code
}
 
+Host and Device Attributes of Default Destructors
+===
+
+If a default destructor does not have explicit host or device attributes,
+clang infers these attributes based on the destructors of its data members
+and base classes. If any conflicts are detected among these destructors,
+clang diagnoses the issue. Otherwise, clang adds an implicit host or device
+attribute according to whether the data members's and base classes's
+destructors can execute on the host or device side.
+
+For explicit template classes with virtual destructors, which must be emitted,
+the inference adopts a conservative approach. In this case, implicit host or
+device attributes from member and base class destructors are ignored. This
+precaution is necessary because, although a constexpr destructor carries
+implicit host or device attributes, a constexpr function may call a
+non-constexpr function, which is by default a host function.
+
+Users can override the inferred host and device attributes of default
+destructors by adding explicit host and device attributes to them.
+
 C++ Standard Parallelism Offload Support: Compiler And Runtime
 ==
 

diff  --git a/clang/lib/Sema/SemaCUDA.cpp b/clang/lib/Sema/SemaCUDA.cpp
index 473956c37bb51..0e5fc5e1a40b4 100644
--- a/clang/lib/Sema/SemaCUDA.cpp
+++ b/clang/lib/Sema/SemaCUDA.cpp
@@ -437,7 +437,9 @@ bool 
SemaCUDA::inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
 if (!SMOR.getMethod())
   continue;
 
-CUDAFunctionTarget BaseMethodTarget = IdentifyTarget(SMOR.getMethod());
+CUDAFunctionTarget BaseMethodTarget =
+IdentifyTarget(SMOR.getMethod(), IsExpVDtor);
+
 if (!InferredTarget) {
   InferredTarget = BaseMethodTarget;
 } else {
@@ -481,7 +483,9 @@ bool 
SemaCUDA::inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
 if (!SMOR.getMethod())
   continue;
 
-CUDAFunctionTarget FieldMethodTarget = IdentifyTarget(SMOR.getMethod());
+CUDAFunctionTarget FieldMethodTarget =
+IdentifyTarget(SMOR.getMethod(), IsExpVDtor);
+
 if (!InferredTarget) {
   InferredTarget = FieldMethodTarget;
 } else {

diff  --git a/clang/test/SemaCUDA/dtor.cu b/clang/test/SemaCUDA/dtor.cu
index c266e51f5c29e..cc37837e70791 100644
--- a/clang/test/SemaCUDA/dtor.cu
+++ b/clang/test/SemaCUDA/dtor.cu
@@ -32,22 +32,24 @@ public:
 template class B;
 }
 
-// The implicit host/device attrs of virtual dtor B::~B() is inferred to
-// have implicit device attr since dtors of its members and parent classes can
-// be executed on device. This causes a diagnostic since B::~B() must
-// be emitted, and it eventually causes host_fun() called on device sid

[clang] 3dafa48 - [clang][bytecode] Don't narrow() when dereferencing to array type (#129524)

2025-03-03 Thread via cfe-commits

Author: Timm Baeder
Date: 2025-03-03T17:14:54+01:00
New Revision: 3dafa486a6a41bacd31b3b1661fa44fa5e71520a

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

LOG: [clang][bytecode] Don't narrow() when dereferencing to array type (#129524)

It doesn't make sense to do this if the result is supposed to be an
array.

Added: 
clang/test/AST/ByteCode/libcxx/deref-to-array.cpp

Modified: 
clang/lib/AST/ByteCode/Compiler.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 4cf6a48edd5e0..96f67ffca43b3 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -6039,14 +6039,12 @@ bool Compiler::VisitUnaryOperator(const 
UnaryOperator *E) {
 // We should already have a pointer when we get here.
 return this->delegate(SubExpr);
   case UO_Deref: // *x
-if (DiscardResult) {
-  // assert(false);
+if (DiscardResult)
   return this->discard(SubExpr);
-}
 
 if (!this->visit(SubExpr))
   return false;
-if (classifyPrim(SubExpr) == PT_Ptr)
+if (classifyPrim(SubExpr) == PT_Ptr && !E->getType()->isArrayType())
   return this->emitNarrowPtr(E);
 return true;
 

diff  --git a/clang/test/AST/ByteCode/libcxx/deref-to-array.cpp 
b/clang/test/AST/ByteCode/libcxx/deref-to-array.cpp
new file mode 100644
index 0..2a527ab336a0d
--- /dev/null
+++ b/clang/test/AST/ByteCode/libcxx/deref-to-array.cpp
@@ -0,0 +1,391 @@
+// RUN: %clang_cc1 -std=c++2c -fexperimental-new-constant-interpreter 
-verify=expected,both %s
+// RUN: %clang_cc1 -std=c++2c  -verify=ref,both %s
+
+// both-no-diagnostics
+
+namespace std {
+inline namespace {
+template  struct integral_constant {
+  static const _Tp value = __v;
+};
+template  using _BoolConstant = integral_constant;
+template  using __remove_cv_t = __remove_cv(_Tp);
+template  using remove_cv_t = __remove_cv_t<_Tp>;
+template 
+constexpr bool is_convertible_v = __is_convertible(_From, _To);
+template  _Tp __declval(long);
+template  decltype(__declval<_Tp>(0)) declval();
+template 
+concept convertible_to = is_convertible_v<_From, _To> &&
+ requires { static_cast<_To>(declval<_From>()); };
+template  constexpr bool is_reference_v = __is_reference(_Tp);
+template 
+constexpr bool is_lvalue_reference_v = __is_lvalue_reference(_Tp);
+template 
+constexpr bool is_nothrow_destructible_v =
+integral_constant::value;
+template 
+concept destructible = is_nothrow_destructible_v<_Tp>;
+template 
+using _IsSame = _BoolConstant<__is_same(_Tp, _Up)>;
+template 
+constexpr bool is_constructible_v = __is_constructible(_Args...);
+template 
+concept constructible_from = destructible<_Tp> && is_constructible_v<_Tp>;
+template 
+concept move_constructible =
+constructible_from<_Tp, _Tp> && convertible_to<_Tp, _Tp>;
+template 
+concept __same_as_impl = _IsSame<_Tp, _Up>::value;
+template 
+concept same_as = __same_as_impl<_Tp, _Up> && __same_as_impl<_Up, _Tp>;
+template  struct _IfImpl;
+template <> struct _IfImpl {
+  template  using _Select = _ElseRes;
+};
+template 
+using _If = _IfImpl<_Cond>::template _Select<_IfRes, _ElseRes>;
+template  struct conditional {
+  using type = _If;
+};
+template 
+using conditional_t = conditional<_IfRes>::type;
+template 
+using __libcpp_remove_reference_t = __remove_reference_t(_Tp);
+template 
+using remove_reference_t = __libcpp_remove_reference_t<_Tp>;
+template  using __decay_t = __decay(_Tp);
+template  using __remove_cvref_t = __remove_cvref(_Tp);
+template  using remove_cvref_t = __remove_cvref_t<_Tp>;
+struct __copy_cv {
+  template  using __apply = _To;
+};
+template  using __copy_cv_t = __copy_cv::__apply<_To>;
+template 
+using __cond_res =
+decltype(false ? std::declval<_Xp (&)()>()() : std::declval<_Yp 
(&)()>()());
+template ,
+  class = remove_reference_t<_Bp>>
+struct __common_ref;
+template 
+struct __common_ref : __common_ref<_Bp, _Ap> {};
+template 
+using __common_ref_t = __common_ref<_Xp, _Yp>::__type;
+template 
+using __cv_cond_res =
+__cond_res<__copy_cv_t<_Xp, _Yp> &, __copy_cv_t<_Yp, _Xp> &>;
+template 
+  requires requires { typename __cv_cond_res<_Xp, _Yp>; } &&
+   is_reference_v<__cv_cond_res<_Xp, _Yp>>
+struct __common_ref<_Ap, _Bp &, _Xp, _Yp> {
+  using __type = __cv_cond_res<_Xp, _Yp>;
+};
+template 
+using __common_ref_D = __common_ref_t;
+template 
+  requires requires { typename __common_ref_D<_Xp, _Yp>; } &&
+   is_convertible_v<_Ap, __common_ref_D<_Xp, _Yp>>
+struct __common_ref<_Ap &&, _Bp &, _Xp, _Yp> {
+  using __type = __common_ref_D<_Xp, _Yp>;
+};
+template  struct common_reference;
+template 
+using common_reference_t = common_reference<_Types...>::type;
+template  struct __common_referenc

[clang] 9db72e5 - [clang][cmake] Fix support for dynamic libraries in CLANG_BOLT

2025-03-03 Thread via cfe-commits

Author: serge-sans-paille
Date: 2025-03-03T09:21:05+01:00
New Revision: 9db72e55edf8c10b2a1b72f1a2d4594d312dd91c

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

LOG: [clang][cmake] Fix support for dynamic libraries in CLANG_BOLT

Patch typo introduced in #127020

Added: 


Modified: 
clang/utils/perf-training/perf-helper.py

Removed: 




diff  --git a/clang/utils/perf-training/perf-helper.py 
b/clang/utils/perf-training/perf-helper.py
index cdb6c39f6c50e..7a049e71d9826 100644
--- a/clang/utils/perf-training/perf-helper.py
+++ b/clang/utils/perf-training/perf-helper.py
@@ -560,12 +560,12 @@ def genOrderFile(args):
 return 0
 
 
-def filter_bolt_optimized(inputs, instrumented_outputs):
+def filter_bolt_optimized(inputs, instrumented_outputs, readelf):
 new_inputs = []
 new_instrumented_ouputs = []
 for input, instrumented_output in zip(inputs, instrumented_outputs):
 output = subprocess.check_output(
-[opts.readelf, "-WS", input], universal_newlines=True
+[readelf, "-WS", input], universal_newlines=True
 )
 
 # This binary has already been bolt-optimized, so skip further 
processing.
@@ -597,7 +597,9 @@ def bolt_optimize(args):
 instrumented_outputs
 ), "inconsistent --input / --instrumented-output arguments"
 
-inputs, instrumented_outputs = filter_bolt_optimized(inputs, 
instrumented_outputs)
+inputs, instrumented_outputs = filter_bolt_optimized(inputs,
+ instrumented_outputs,
+ opts.readelf)
 if not inputs:
 return 0
 



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


[clang] 1119b72 - [RISCV][clang] Add address space argument to getNaturalAlignIndirect (#129493)

2025-03-03 Thread via cfe-commits

Author: Brandon Wu
Date: 2025-03-03T17:37:55+08:00
New Revision: 1119b7297780e870e8ae05651389913e09ae2036

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

LOG: [RISCV][clang] Add address space argument to getNaturalAlignIndirect 
(#129493)

This is introduced in 39ec9de7c23063b87f5c56f4e80c8d0f8b511a4b

Added: 


Modified: 
clang/lib/CodeGen/Targets/RISCV.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/Targets/RISCV.cpp 
b/clang/lib/CodeGen/Targets/RISCV.cpp
index 109fa1f9ee521..e350a3589dcaf 100644
--- a/clang/lib/CodeGen/Targets/RISCV.cpp
+++ b/clang/lib/CodeGen/Targets/RISCV.cpp
@@ -578,7 +578,9 @@ ABIArgInfo RISCVABIInfo::coerceVLSVector(QualType Ty, 
unsigned ABIVLen) const {
   } else {
 // Check registers needed <= 8.
 if ((EltType->getScalarSizeInBits() * NumElts / ABIVLen) > 8)
-  return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
+  return getNaturalAlignIndirect(
+  Ty, /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
+  /*ByVal=*/false);
 
 // Generic vector
 // The number of elements needs to be at least 1.



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


[clang] da7403e - [clang][analyzer] Add checker 'alpha.core.FixedAddressDereference' (#127191)

2025-03-03 Thread via cfe-commits

Author: Balázs Kéri
Date: 2025-03-03T10:44:05+01:00
New Revision: da7403ed1d5727cd758560ffc7957bba5c395745

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

LOG: [clang][analyzer] Add checker 'alpha.core.FixedAddressDereference' 
(#127191)

Added: 
clang/test/Analysis/suppress-dereferences-from-any-address-space.c

Modified: 
clang/docs/analyzer/checkers.rst
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp
clang/test/Analysis/analyzer-config.c
clang/test/Analysis/cast-value-notes.cpp
clang/test/Analysis/concrete-address.c
clang/test/Analysis/misc-ps.m

Removed: 




diff  --git a/clang/docs/analyzer/checkers.rst 
b/clang/docs/analyzer/checkers.rst
index c1eedb33e74d2..b817a99a1c56f 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -118,19 +118,6 @@ core.NullDereference (C, C++, ObjC)
 """
 Check for dereferences of null pointers.
 
-This checker specifically does
-not report null pointer dereferences for x86 and x86-64 targets when the
-address space is 256 (x86 GS Segment), 257 (x86 FS Segment), or 258 (x86 SS
-segment). See `X86/X86-64 Language Extensions
-`__
-for reference.
-
-The ``SuppressAddressSpaces`` option suppresses
-warnings for null dereferences of all pointers with address spaces. You can
-disable this behavior with the option
-``-analyzer-config core.NullDereference:SuppressAddressSpaces=false``.
-*Defaults to true*.
-
 .. code-block:: objc
 
  // C
@@ -170,6 +157,19 @@ disable this behavior with the option
obj->x = 1; // warn
  }
 
+Null pointer dereferences of pointers with address spaces are not always 
defined
+as error. Specifically on x86/x86-64 target if the pointer address space is
+256 (x86 GS Segment), 257 (x86 FS Segment), or 258 (x86 SS Segment), a null
+dereference is not defined as error. See `X86/X86-64 Language Extensions
+`__
+for reference.
+   
+If the analyzer option ``suppress-dereferences-from-any-address-space`` is set
+to true (the default value), then this checker never reports dereference of
+pointers with a specified address space. If the option is set to false, then
+reports from the specific x86 address spaces 256, 257 and 258 are still
+suppressed, but null dereferences from other address spaces are reported.
+
 .. _core-StackAddressEscape:
 
 core.StackAddressEscape (C)
@@ -2919,6 +2919,41 @@ Check for assignment of a fixed address to a pointer.
p = (int *) 0x1; // warn
  }
 
+.. _alpha-core-FixedAddressDereference:
+
+alpha.core.FixedAddressDereference (C, C++, ObjC)
+"
+Check for dereferences of fixed addresses.
+
+A pointer contains a fixed address if it was set to a hard-coded value or it
+becomes otherwise obvious that at that point it can have only a single specific
+value.
+
+.. code-block:: c
+
+ void test1() {
+   int *p = (int *)0x020;
+   int x = p[0]; // warn
+ }
+
+ void test2(int *p) {
+   if (p == (int *)-1)
+ *p = 0; // warn
+ }
+
+ void test3() {
+   int (*p_function)(char, char);
+   p_function = (int (*)(char, char))0x04080;
+   int x = (*p_function)('x', 'y'); // NO warning yet at functon pointer calls
+ }
+
+If the analyzer option ``suppress-dereferences-from-any-address-space`` is set
+to true (the default value), then this checker never reports dereference of
+pointers with a specified address space. If the option is set to false, then
+reports from the specific x86 address spaces 256, 257 and 258 are still
+suppressed, but fixed address dereferences from other address spaces are
+reported.
+
 .. _alpha-core-PointerArithm:
 
 alpha.core.PointerArithm (C)

diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 410f841630660..c8895db914d13 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -213,13 +213,6 @@ def DereferenceModeling : Checker<"DereferenceModeling">,
 
 def NullDereferenceChecker : Checker<"NullDereference">,
   HelpText<"Check for dereferences of null pointers">,
-  CheckerOptions<[
-CmdLineOption
-  ]>,
   Documentation,
   Dependencies<[DereferenceModeling]>;
 
@@ -285,6 +278,12 @@ def FixedAddressChecker : Checker<"FixedAddr">,
   HelpText<"Check for assignment of a fixed address to a pointer">,
   Documentation;
 
+def FixedAddressDereferenceChecker
+: Check

[clang] 370d34f - [flang][Driver] Add support of -fd-lines-as-comments and -fd-lines-as-code flags (#127605)

2025-03-03 Thread via cfe-commits

Author: Jean-Didier PAILLEUX
Date: 2025-03-03T11:55:36Z
New Revision: 370d34fe40162946905b900097ed746dd4aeb6ad

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

LOG: [flang][Driver] Add support of -fd-lines-as-comments and -fd-lines-as-code 
flags (#127605)

`-fd-lines-as-code` and `-fd-lines-as-comments` enables treatment for
lines beginning with `d` or `D` in fixed form sources.
Using these options in free form has no effect.
If the `-fd-lines-as-code` option is given they are treated as if the
first column contained a blank.
If the `-fd-lines-as-comments` option is given, they are treated as
comment lines.

Added: 
flang/test/Driver/fd-lines-as.f90
flang/test/Preprocessing/fd-lines-as.f90

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Flang.cpp
flang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 75b1c51445942..c4bd030e32b5b 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6777,8 +6777,16 @@ defm backtrace : BooleanFFlag<"backtrace">, 
Group;
 defm bounds_check : BooleanFFlag<"bounds-check">, Group;
 defm check_array_temporaries : BooleanFFlag<"check-array-temporaries">, 
Group;
 defm cray_pointer : BooleanFFlag<"cray-pointer">, Group;
-defm d_lines_as_code : BooleanFFlag<"d-lines-as-code">, Group;
-defm d_lines_as_comments : BooleanFFlag<"d-lines-as-comments">, 
Group;
+defm d_lines_as_code : BooleanFFlag<"d-lines-as-code">,
+   HelpText<"Treat fixed form lines with 'd' or 'D' in the 
"
+"first column as blank.">,
+   Group,
+   Visibility<[FlangOption, FC1Option]>;
+defm d_lines_as_comments : BooleanFFlag<"d-lines-as-comments">,
+   HelpText<"Treat fixed form lines with 'd' or 'D' in 
"
+"the first column as comments.">,
+   Group,
+   Visibility<[FlangOption, FC1Option]>;
 defm dollar_ok : BooleanFFlag<"dollar-ok">, Group;
 defm dump_fortran_optimized : BooleanFFlag<"dump-fortran-optimized">, 
Group;
 defm dump_fortran_original : BooleanFFlag<"dump-fortran-original">, 
Group;

diff  --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 45c26cf8c3159..d4fea633d0edf 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -60,6 +60,8 @@ void Flang::addFortranDialectOptions(const ArgList &Args,
 options::OPT_frealloc_lhs,
 options::OPT_fno_realloc_lhs,
 options::OPT_fsave_main_program,
+options::OPT_fd_lines_as_code,
+options::OPT_fd_lines_as_comments,
 options::OPT_fno_save_main_program});
 }
 

diff  --git a/flang/lib/Frontend/CompilerInvocation.cpp 
b/flang/lib/Frontend/CompilerInvocation.cpp
index 724316f1b30c7..8b07a50824899 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -961,6 +961,32 @@ static bool parseDialectArgs(CompilerInvocation &res, 
llvm::opt::ArgList &args,
  clang::DiagnosticsEngine &diags) {
   unsigned numErrorsBefore = diags.getNumErrors();
 
+  // -fd-lines-as-code
+  if (args.hasArg(clang::driver::options::OPT_fd_lines_as_code)) {
+if (res.getFrontendOpts().fortranForm == FortranForm::FreeForm) {
+  const unsigned fdLinesAsWarning = diags.getCustomDiagID(
+  clang::DiagnosticsEngine::Warning,
+  "‘-fd-lines-as-code’ has no effect in free form.");
+  diags.Report(fdLinesAsWarning);
+} else {
+  res.getFrontendOpts().features.Enable(
+  Fortran::common::LanguageFeature::OldDebugLines, true);
+}
+  }
+
+  // -fd-lines-as-comments
+  if (args.hasArg(clang::driver::options::OPT_fd_lines_as_comments)) {
+if (res.getFrontendOpts().fortranForm == FortranForm::FreeForm) {
+  const unsigned fdLinesAsWarning = diags.getCustomDiagID(
+  clang::DiagnosticsEngine::Warning,
+  "‘-fd-lines-as-comments’ has no effect in free form.");
+  diags.Report(fdLinesAsWarning);
+} else {
+  res.getFrontendOpts().features.Enable(
+  Fortran::common::LanguageFeature::OldDebugLines, false);
+}
+  }
+
   // -fdefault* family
   if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
 res.getDefaultKinds().set_defaultRealKind(8);

diff  --git a/flang/test/Driver/fd-lines-as.f90 
b/flang/test/Driver/fd-lines-as.f90
new file mode 100644
index 0..ea06a3

[clang] 742fa8a - [ARM] Introduce -mtp=auto and make it the default (#128901)

2025-03-03 Thread via cfe-commits

Author: Austin
Date: 2025-03-03T20:20:43+08:00
New Revision: 742fa8ac67796198dde99e18cdadeaf9b96c2f88

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

LOG: [ARM] Introduce -mtp=auto and make it the default (#128901)

This adds a new value auto to the possible values of the existing -mtp=
clang option which controls how the thread pointer is found. auto means
the same as soft if the target architecture doesn't support a hardware
thread pointer at all; otherwise it means the same as cp15.

This behavior is the default in gcc version 4.1.0 and later. The new
auto option is therefore also the default in clang, so this change
aligns clang with gcc.

Fixes #123864.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Arch/ARM.cpp
clang/test/Driver/arm-thread-pointer.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d2fc1ce07dd79..b572a166146ac 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -126,6 +126,10 @@ Deprecated Compiler Flags
 Modified Compiler Flags
 ---
 
+- The ARM AArch32 ``-mtp`` option accepts and defaults to ``auto``, a value of 
``auto`` uses the best available method of providing the frame pointer 
supported by the hardware. This matches
+  the behavior of ``-mtp`` in gcc. This changes the default behavior for ARM 
targets that provide the ``TPIDRURO`` register as this will be used instead of 
a call to the ``__aeabi_read_tp``.
+  Programs that use ``__aeabi_read_tp`` but do not use the ``TPIDRURO`` 
register must use ``-mtp=soft``. Fixes #123864
+
 Removed Compiler Flags
 -
 

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c4bd030e32b5b..d0414aba35209 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4729,7 +4729,7 @@ def mexecute_only : Flag<["-"], "mexecute-only">, 
Group,
 def mno_execute_only : Flag<["-"], "mno-execute-only">, 
Group,
   HelpText<"Allow generation of data access to code sections (ARM only)">;
 let Flags = [TargetSpecific] in {
-def mtp_mode_EQ : Joined<["-"], "mtp=">, Group, 
Values<"soft,cp15,tpidrurw,tpidruro,tpidrprw,el0,el1,el2,el3,tpidr_el0,tpidr_el1,tpidr_el2,tpidr_el3,tpidrro_el0">,
+def mtp_mode_EQ : Joined<["-"], "mtp=">, Group, 
Values<"soft,cp15,tpidrurw,tpidruro,tpidrprw,el0,el1,el2,el3,tpidr_el0,tpidr_el1,tpidr_el2,tpidr_el3,tpidrro_el0,auto">,
   HelpText<"Thread pointer access method. "
"For AArch32: 'soft' uses a function call, or 'tpidrurw', 
'tpidruro' or 'tpidrprw' use the three CP15 registers. 'cp15' is an alias for 
'tpidruro'. "
"For AArch64: 'tpidr_el0', 'tpidr_el1', 'tpidr_el2', 'tpidr_el3' or 
'tpidrro_el0' use the five system registers. 'elN' is an alias for 
'tpidr_elN'.">;

diff  --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp 
b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
index 3aee540d501be..51454de1b9dcc 100644
--- a/clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -215,7 +215,8 @@ bool arm::isHardTPSupported(const llvm::Triple &Triple) {
 // Select mode for reading thread pointer (-mtp=soft/cp15).
 arm::ReadTPMode arm::getReadTPMode(const Driver &D, const ArgList &Args,
const llvm::Triple &Triple, bool ForAS) {
-  if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
+  Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ);
+  if (A && A->getValue() != StringRef("auto")) {
 arm::ReadTPMode ThreadPointer =
 llvm::StringSwitch(A->getValue())
 .Case("cp15", ReadTPMode::TPIDRURO)
@@ -239,7 +240,7 @@ arm::ReadTPMode arm::getReadTPMode(const Driver &D, const 
ArgList &Args,
   D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);
 return ReadTPMode::Invalid;
   }
-  return ReadTPMode::Soft;
+  return (isHardTPSupported(Triple) ? ReadTPMode::TPIDRURO : ReadTPMode::Soft);
 }
 
 void arm::setArchNameInTriple(const Driver &D, const ArgList &Args,
@@ -574,12 +575,14 @@ llvm::ARM::FPUKind arm::getARMTargetFeatures(const Driver 
&D,
   A->ignoreTargetSpecific();
   }
 
-  if (getReadTPMode(D, Args, Triple, ForAS) == ReadTPMode::TPIDRURW)
+  arm::ReadTPMode TPMode = getReadTPMode(D, Args, Triple, ForAS);
+
+  if (TPMode == ReadTPMode::TPIDRURW)
 Features.push_back("+read-tp-tpidrurw");
-  if (getReadTPMode(D, Args, Triple, ForAS) == ReadTPMode::TPIDRURO)
-Features.push_back("+read-tp-tpidruro");
-  if (getReadTPMode(D, Args, Triple, ForAS) == ReadTPMode::TPIDRPRW)
+  else if (TPMode == ReadTPMode::TPIDRPRW)
 Features.push_back("+read-tp-tpidrprw");
+  else if (TPMode == ReadTPMode::TPID

[clang] [clang][HIP] Make some math not not work with AMDGCN SPIR-V (PR #128360)

2025-03-03 Thread Alex Voicu via cfe-commits

AlexVlx wrote:

> > This seems to break tests: http://45.33.8.238/linux/161683/step_6.txt
> > Please take a look and revert for now if it takes a while to fix.
> 
> Should be fixed within the next 30 mins or so, if not I'll revert, apologies 
> for the inconvenience.

I've reverted this for now, even though I cannot repro locally.

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


[clang] [clang-tools-extra] [libcxx] [llvm] [libc++][ranges] P2542R8: Implement `views::concat` (PR #120920)

2025-03-03 Thread Nhat Nguyen via cfe-commits

https://github.com/changkhothuychung updated 
https://github.com/llvm/llvm-project/pull/120920

error: too big or took too long to generate
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Contributing.rst update snippet and docs (PR #129209)

2025-03-03 Thread via cfe-commits

github-actions[bot] wrote:



@Marcondiro Congratulations on having your first Pull Request (PR) merged into 
the LLVM Project!

Your changes will be combined with recent changes from other authors, then 
tested by our [build bots](https://lab.llvm.org/buildbot/). If there is a 
problem with a build, you may receive a report in an email or a comment on this 
PR.

Please check whether problems have been caused by your change specifically, as 
the builds can include changes from many authors. It is not uncommon for your 
change to be included in a build that fails due to someone else's changes, or 
infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail 
[here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr).

If your change does cause a problem, it may be reverted, or you can revert it 
yourself. This is a normal part of [LLVM 
development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy).
 You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are 
working as expected, well done!


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


[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)

2025-03-03 Thread via cfe-commits

llvmbot wrote:




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

Author: David Rivera (RiverDave)


Changes

This aims to address a portion of #122480 by adding matchers on binary 
operators. **This allows explicit arithmetic operations within initializers.**

### Note
I'm aware of the other false-negatives presented in the issue above, 
specifically not matching explicit castings & constexpr values. These will 
be addressed separately on a different PR which is in the process and shouldn't 
take long (let me know if that's the right approach).

Feedback is much appreciated. 


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


3 Files Affected:

- (modified) 
clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp (+12-1) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
 (+26) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
index 6c06b0af342f6..a9d9e8b66ea7c 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -159,6 +159,12 @@ static bool sameValue(const Expr *E1, const Expr *E2) {
   case Stmt::UnaryOperatorClass:
 return sameValue(cast(E1)->getSubExpr(),
  cast(E2)->getSubExpr());
+  case Stmt::BinaryOperatorClass: {
+const auto *BinOp1 = cast(E1);
+const auto *BinOp2 = cast(E2);
+return sameValue(BinOp1->getLHS(), BinOp2->getLHS()) &&
+sameValue(BinOp1->getRHS(), BinOp2->getRHS());
+  }
   case Stmt::CharacterLiteralClass:
 return cast(E1)->getValue() ==
cast(E2)->getValue();
@@ -202,7 +208,12 @@ void 
UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
 unaryOperator(hasAnyOperatorName("+", "-"),
   hasUnaryOperand(floatLiteral())),
 cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(),
-declRefExpr(to(enumConstantDecl(;
+declRefExpr(to(enumConstantDecl())),
+binaryOperator(
+hasLHS(anyOf(integerLiteral(), floatLiteral(),
+ declRefExpr(to(enumConstantDecl())), 
binaryOperator())),
+hasRHS(anyOf(integerLiteral(), floatLiteral(),
+ declRefExpr(to(enumConstantDecl())), 
binaryOperator();
 
   auto Init =
   anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)),
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 07a79d6bbe807..6d909f9d7c6bd 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -137,6 +137,10 @@ Changes in existing checks
   ` check by fixing false 
negatives
   on ternary operators calling ``std::move``.
 
+- Improved :doc:`modernize-use-default-member-init
+  ` check by matching 
arithmetic
+  operations within member list initialization.
+
 Removed checks
 ^^
 
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
index 81c980e0217e6..ff8c80b682bdb 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
@@ -518,3 +518,29 @@ class ArrayBraceInitMultipleValues {
 };
 
 } // namespace PR63285
+
+namespace PR122480 {
+
+#define ARITHMETIC_MACRO (44 - 2)
+
+class DefaultMemberInitWithArithmetic {
+  DefaultMemberInitWithArithmetic() : a{1 + 1},  b{1 + 11 + 123 + 1234},  c{2 
+ (4 / 2) + 3 + (7 / 11)},  d{ARITHMETIC_MACRO * 2}, e{1.2 + 3.4} {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:39: warning: member initializer for 'a' is 
redundant [modernize-use-default-member-init]
+  // CHECK-FIXES: DefaultMemberInitWithArithmetic()  {}
+
+  int a{1 + 1};
+  int b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer 
for 'b' [modernize-use-default-member-init]
+  // CHECK-FIXES:  int b{1 + 11 + 123 + 1234};
+  int c;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer 
for 'c' [modernize-use-default-member-init]
+  // CHECK-FIXES: int c{2 + (4 / 2) + 3 + (7 / 11)}
+  int d;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer 
for 'd' [modernize-use-default-member-init]
+  // CHECK-FIXES: int d{ARITHMETIC_MACRO * 2};
+  double e;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: use default member initializer 
for 'e' [modernize-use-default-member-init]
+  // CHECK-FIXES: double e{1.2 + 3.4};
+
+};
+} // namespace PR122480

``




https://github.com/llvm/llvm-project/pull/129370
___

[clang] [llvm] [RISCV] Remove Last Traces of User Interrupts (PR #129300)

2025-03-03 Thread Sam Elliott via cfe-commits

https://github.com/lenary created 
https://github.com/llvm/llvm-project/pull/129300

These were left over from when Craig removed 
`__attribute__((interrupt("user")))` support in 
05d0caef6081e1a6cb23a5a5afe43dc82e8ca558.

The tests change "interrupt"="user" into "interrupt"="machine" as they are 
still intending to be interrupt tests. ISelLowering will now reject 
"interrupt"="user". The docs no longer mention "user" as a possible interrupt 
attribute argument.

>From 0dc80a2687b0d1655cf52996befa9c3c12845a35 Mon Sep 17 00:00:00 2001
From: Sam Elliott 
Date: Fri, 28 Feb 2025 12:17:44 -0800
Subject: [PATCH] [RISCV] Remove Last Traces of User Interrupts

These were left over from when Craig removed
`__attribute__((interrupt("user")))` support in
05d0caef6081e1a6cb23a5a5afe43dc82e8ca558.

The tests change "interrupt"="user" into "interrupt"="machine" as they
are still intending to be interrupt tests. ISelLowering will now reject
"interrupt"="user". The docs no longer mention "user" as a possible
interrupt attribute argument.
---
 clang/include/clang/Basic/AttrDocs.td   | 4 ++--
 llvm/lib/Target/RISCV/RISCVISelLowering.cpp | 2 +-
 llvm/test/CodeGen/RISCV/lpad.ll | 2 +-
 llvm/test/CodeGen/RISCV/push-pop-popret.ll  | 4 ++--
 4 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index d6d43df44fb21..6e0932f82be20 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -2828,8 +2828,8 @@ targets. This attribute may be attached to a function 
definition and instructs
 the backend to generate appropriate function entry/exit code so that it can be
 used directly as an interrupt service routine.
 
-Permissible values for this parameter are ``user``, ``supervisor``,
-and ``machine``. If there is no parameter, then it defaults to machine.
+Permissible values for this parameter are ``supervisor`` and ``machine``. If
+there is no parameter, then it defaults to ``machine``.
 
 Repeated interrupt attribute on the same declaration will cause a warning
 to be emitted. In case of repeated declarations, the last one prevails.
diff --git a/llvm/lib/Target/RISCV/RISCVISelLowering.cpp 
b/llvm/lib/Target/RISCV/RISCVISelLowering.cpp
index 4e6b3a224b79b..99977f713d2a0 100644
--- a/llvm/lib/Target/RISCV/RISCVISelLowering.cpp
+++ b/llvm/lib/Target/RISCV/RISCVISelLowering.cpp
@@ -20777,7 +20777,7 @@ SDValue RISCVTargetLowering::LowerFormalArguments(
 StringRef Kind =
   MF.getFunction().getFnAttribute("interrupt").getValueAsString();
 
-if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
+if (!(Kind == "supervisor" || Kind == "machine"))
   report_fatal_error(
 "Function interrupt attribute argument not supported!");
   }
diff --git a/llvm/test/CodeGen/RISCV/lpad.ll b/llvm/test/CodeGen/RISCV/lpad.ll
index f5d06f0924c54..93eda6f10eedb 100644
--- a/llvm/test/CodeGen/RISCV/lpad.ll
+++ b/llvm/test/CodeGen/RISCV/lpad.ll
@@ -279,7 +279,7 @@ define internal void @internal2() {
 }
 
 ; Check interrupt function does not need landing pad.
-define void @interrupt() "interrupt"="user" {
+define void @interrupt() "interrupt"="machine" {
 ; CHECK-LABEL: interrupt:
 ; CHECK:   # %bb.0:
 ; CHECK-NEXT:mret
diff --git a/llvm/test/CodeGen/RISCV/push-pop-popret.ll 
b/llvm/test/CodeGen/RISCV/push-pop-popret.ll
index 1fbdaa76dfb68..65f58d0ecbf24 100644
--- a/llvm/test/CodeGen/RISCV/push-pop-popret.ll
+++ b/llvm/test/CodeGen/RISCV/push-pop-popret.ll
@@ -1769,7 +1769,7 @@ define void @alloca(i32 %n) {
 declare i32 @foo_test_irq(...)
 @var_test_irq = global [32 x i32] zeroinitializer
 
-define void @foo_with_irq() "interrupt"="user" {
+define void @foo_with_irq() "interrupt"="machine" {
 ; RV32IZCMP-LABEL: foo_with_irq:
 ; RV32IZCMP:   # %bb.0:
 ; RV32IZCMP-NEXT:cm.push {ra}, -64
@@ -2273,7 +2273,7 @@ define void @foo_no_irq() {
   ret void
 }
 
-define void @callee_with_irq() "interrupt"="user" {
+define void @callee_with_irq() "interrupt"="machine" {
 ; RV32IZCMP-LABEL: callee_with_irq:
 ; RV32IZCMP:   # %bb.0:
 ; RV32IZCMP-NEXT:cm.push {ra, s0-s11}, -112

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


[clang] [NFC] Ensure the SPIRV target is enabled for test that uses AMDGCNSPIRV (PR #129298)

2025-03-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alex Voicu (AlexVlx)


Changes

Fixes breakage found when trying to merge #128360.

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


1 Files Affected:

- (modified) clang/test/Headers/__clang_hip_math.hip (+1) 


``diff
diff --git a/clang/test/Headers/__clang_hip_math.hip 
b/clang/test/Headers/__clang_hip_math.hip
index a375ea47b530d..d448ab134ca4d 100644
--- a/clang/test/Headers/__clang_hip_math.hip
+++ b/clang/test/Headers/__clang_hip_math.hip
@@ -1,5 +1,6 @@
 // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
 // REQUIRES: amdgpu-registered-target
+// REQUIRES: spirv-registered-target
 
 // Test without OCML_BASIC_ROUNDED_OPERATIONS
 // RUN: %clang_cc1 -include __clang_hip_runtime_wrapper.h \

``




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


[clang] 299be61 - [clang] Fix CodeComplete crash involving CWG1432 (#129436)

2025-03-03 Thread via cfe-commits

Author: Matheus Izvekov
Date: 2025-03-03T11:41:50-03:00
New Revision: 299be6123b8106dae31a8c7065d1e395b400cbe2

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

LOG: [clang] Fix CodeComplete crash involving CWG1432 (#129436)

This skips the provisional resolution of CWG1432 just when ordering the
candidates for function call code completion, as otherwise this breaks
some assumptions the implementation makes about how closely related the
candidates are.

As a drive-by, deduplicate the implementation with the one used for
class template partial ordering, and strenghten an assertion which was
previosuly dependent on the order of candidates.

Also add a test for the fix for CWG1432 when partial ordering function
templates, which was otherwise untested.

Fixes #125500

Added: 
clang/test/CodeCompletion/GH125500.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Sema/Overload.h
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaCodeComplete.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/test/CXX/drs/cwg14xx.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b572a166146ac..08fafa00d5452 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -165,7 +165,7 @@ related warnings within the method body.
   print_status("%s (%#08x)\n");
   // order of %s and %x is swapped but there is no diagnostic
 }
-  
+
   Before the introducion of ``format_matches``, this code cannot be verified
   at compile-time. ``format_matches`` plugs that hole:
 
@@ -233,6 +233,8 @@ Bug Fixes in This Version
   signed char values (#GH102798).
 - Fixed rejects-valid problem when #embed appears in std::initializer_list or
   when it can affect template argument deduction (#GH122306).
+- Fix crash on code completion of function calls involving partial order of 
function templates
+  (#GH125500).
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index c03ec00d03dc5..6e08762dcc6d7 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -1265,11 +1265,11 @@ class Sema;
 
   };
 
-  bool isBetterOverloadCandidate(Sema &S,
- const OverloadCandidate &Cand1,
+  bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
  const OverloadCandidate &Cand2,
  SourceLocation Loc,
- OverloadCandidateSet::CandidateSetKind Kind);
+ OverloadCandidateSet::CandidateSetKind Kind,
+ bool PartialOverloading = false);
 
   struct ConstructorInfo {
 DeclAccessPair FoundDecl;

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 3b2be86a88e82..5b5cee5810488 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -12617,7 +12617,8 @@ class Sema final : public SemaBase {
   FunctionTemplateDecl *getMoreSpecializedTemplate(
   FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
   TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
-  QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false);
+  QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
+  bool PartialOverloading = false);
 
   /// Retrieve the most specialized of the given function template
   /// specializations.

diff  --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index 80ae87e7c5725..db467d76b5d32 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -6229,8 +6229,8 @@ static void mergeCandidatesWithResults(
   // Sort the overload candidate set by placing the best overloads first.
   llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X,
   const OverloadCandidate &Y) {
-return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
- CandidateSet.getKind());
+return isBetterOverloadCandidate(SemaRef, X, Y, Loc, 
CandidateSet.getKind(),
+ /*PartialOverloading=*/true);
   });
 
   // Add the remaining viable overload candidates as code-completion results.

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index c344b6fff40c6..d3c0534b4dd0b 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10429,7 +10429,8 @@ getMorePartialOrderingConstrained(Sema &S, FunctionDecl 
*Fn1, Function

[clang] af464c6 - [Clang][diagnostics] Fix structured binding shadows template param loc (#129116)

2025-03-03 Thread via cfe-commits

Author: Amr Hesham
Date: 2025-03-03T19:22:28+01:00
New Revision: af464c6d53c1873101e312048d35d1daed27e407

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

LOG: [Clang][diagnostics] Fix structured binding shadows template param loc 
(#129116)

Fix structured binding shadows template parameter location

Fixes: #129060

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/CXX/temp/temp.res/temp.local/p6.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 08fafa00d5452..688d50a394c62 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -220,6 +220,8 @@ Improvements to Clang's diagnostics
   :doc:`ThreadSafetyAnalysis` still does not perform alias analysis. The
   feature will be default-enabled with ``-Wthread-safety`` in a future release.
 
+- Improve the diagnostics for shadows template parameter to report correct 
location (#GH129060).
+
 Improvements to Clang's time-trace
 --
 

diff  --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 664d48ccbc382..a3a028b9485d6 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -883,8 +883,7 @@ Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
 // It's not permitted to shadow a template parameter name.
 if (Previous.isSingleResult() &&
 Previous.getFoundDecl()->isTemplateParameter()) {
-  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
-  Previous.getFoundDecl());
+  DiagnoseTemplateParameterShadow(B.NameLoc, Previous.getFoundDecl());
   Previous.clear();
 }
 

diff  --git a/clang/test/CXX/temp/temp.res/temp.local/p6.cpp 
b/clang/test/CXX/temp/temp.res/temp.local/p6.cpp
index 00bb35813c39a..205df5fa25870 100644
--- a/clang/test/CXX/temp/temp.res/temp.local/p6.cpp
+++ b/clang/test/CXX/temp/temp.res/temp.local/p6.cpp
@@ -162,3 +162,14 @@ struct A {
 };
 A<0>::B a;
 }
+
+template  int shadow() {  // expected-note{{template parameter is 
declared here}}
+  using arr = int[1];
+  // expected-warning@+1 {{decomposition declarations are a C++17 extension}}
+  auto [
+T // expected-error {{declaration of 'T' shadows template parameter}}
+] = arr{};
+  return 0;
+}
+
+auto Use = shadow();



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


[clang] ab30df4 - [CIR] Upstream floating point literal expressions (#129304)

2025-03-03 Thread via cfe-commits

Author: Amr Hesham
Date: 2025-03-03T19:22:44+01:00
New Revision: ab30df470af91427abf03f99f7f3517129464ca9

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

LOG: [CIR] Upstream floating point literal expressions (#129304)

This change adds support for floating point literal expressions

Added: 


Modified: 
clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
clang/test/CIR/func-simple.cpp

Removed: 




diff  --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
index 90a2fd2a5d806..32fab85cd3db4 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp
@@ -74,6 +74,15 @@ class ScalarExprEmitter : public 
StmtVisitor {
 builder.getAttr(type, e->getValue()));
   }
 
+  mlir::Value VisitFloatingLiteral(const FloatingLiteral *e) {
+mlir::Type type = cgf.convertType(e->getType());
+assert(mlir::isa(type) &&
+   "expect floating-point type");
+return builder.create(
+cgf.getLoc(e->getExprLoc()), type,
+builder.getAttr(type, e->getValue()));
+  }
+
   mlir::Value VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *e) {
 mlir::Type type = cgf.convertType(e->getType());
 return builder.create(

diff  --git a/clang/test/CIR/func-simple.cpp b/clang/test/CIR/func-simple.cpp
index 3947055e300a0..d37ccc7229f22 100644
--- a/clang/test/CIR/func-simple.cpp
+++ b/clang/test/CIR/func-simple.cpp
@@ -57,3 +57,15 @@ bool boolfunc() { return true; }
 // CHECK:   %0 = cir.const #true
 // CHECK:   cir.return %0 : !cir.bool
 // CHECK: }
+
+float floatfunc() { return 42.42f; }
+// CHECK: cir.func @floatfunc() -> !cir.float {
+// CHECK:   %0 = cir.const #cir.fp<4.242
+// CHECK:   cir.return %0 : !cir.float
+// CHECK: }
+
+double doublefunc() { return 42.42; }
+// CHECK: cir.func @doublefunc() -> !cir.double {
+// CHECK:   %0 = cir.const #cir.fp<4.242
+// CHECK:   cir.return %0 : !cir.double
+// CHECK: }



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


[clang] 4ca8ea8 - [Clang] Fix GPU intrinsic helpers incorrectly sign extending (#129560)

2025-03-03 Thread via cfe-commits

Author: Joseph Huber
Date: 2025-03-03T14:26:43-06:00
New Revision: 4ca8ea8c972ae05a891687eda6704ec607184fae

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

LOG: [Clang] Fix GPU intrinsic helpers incorrectly sign extending (#129560)

Summary:
These return values are actually signed, meaning that casting will
extend it and then all the bits will be one.

Added: 


Modified: 
clang/lib/Headers/amdgpuintrin.h
clang/lib/Headers/nvptxintrin.h

Removed: 




diff  --git a/clang/lib/Headers/amdgpuintrin.h 
b/clang/lib/Headers/amdgpuintrin.h
index 355e75d0b2d42..6ad8e54f4aadd 100644
--- a/clang/lib/Headers/amdgpuintrin.h
+++ b/clang/lib/Headers/amdgpuintrin.h
@@ -121,7 +121,7 @@ __gpu_read_first_lane_u64(uint64_t __lane_mask, uint64_t 
__x) {
   uint32_t __hi = (uint32_t)(__x >> 32ull);
   uint32_t __lo = (uint32_t)(__x & 0x);
   return ((uint64_t)__builtin_amdgcn_readfirstlane(__hi) << 32ull) |
- ((uint64_t)__builtin_amdgcn_readfirstlane(__lo));
+ ((uint64_t)__builtin_amdgcn_readfirstlane(__lo) & 0x);
 }
 
 // Returns a bitmask of threads in the current lane for which \p x is true.

diff  --git a/clang/lib/Headers/nvptxintrin.h b/clang/lib/Headers/nvptxintrin.h
index 29d0adcabc82f..03594dd9bd6cb 100644
--- a/clang/lib/Headers/nvptxintrin.h
+++ b/clang/lib/Headers/nvptxintrin.h
@@ -131,7 +131,8 @@ __gpu_read_first_lane_u64(uint64_t __lane_mask, uint64_t 
__x) {
  __gpu_num_lanes() - 1)
   << 32ull) |
  ((uint64_t)__nvvm_shfl_sync_idx_i32(__mask, __lo, __id,
- __gpu_num_lanes() - 1));
+ __gpu_num_lanes() - 1) &
+  0x);
 }
 
 // Returns a bitmask of threads in the current lane for which \p x is true.



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


[clang] 2b509ec - [AST] Reorder fields in FunctionTypeBitfields to avoid splitting a field across 32 bit boundary

2025-03-03 Thread Craig Topper via cfe-commits

Author: Craig Topper
Date: 2025-03-03T13:01:08-08:00
New Revision: 2b509ecf2dadcd5ea81b15c85f116c20b9b1f649

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

LOG: [AST] Reorder fields in FunctionTypeBitfields to avoid splitting a field 
across 32 bit boundary

Fixes #129521.

Added: 


Modified: 
clang/include/clang/AST/Type.h

Removed: 




diff  --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 3cd2be2d2170a..79cf237431450 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -1943,11 +1943,6 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
 LLVM_PREFERRED_TYPE(TypeBitfields)
 unsigned : NumTypeBits;
 
-/// Extra information which affects how the function is called, like
-/// regparm and the calling convention.
-LLVM_PREFERRED_TYPE(CallingConv)
-unsigned ExtInfo : 14;
-
 /// The ref-qualifier associated with a \c FunctionProtoType.
 ///
 /// This is a value of type \c RefQualifierKind.
@@ -1966,12 +1961,6 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
 LLVM_PREFERRED_TYPE(bool)
 unsigned HasExtQuals : 1;
 
-/// The number of parameters this function has, not counting '...'.
-/// According to [implimits] 8 bits should be enough here but this is
-/// somewhat easy to exceed with metaprogramming and so we would like to
-/// keep NumParams as wide as reasonably possible.
-unsigned NumParams : FunctionTypeNumParamsWidth;
-
 /// The type of exception specification this function has.
 LLVM_PREFERRED_TYPE(ExceptionSpecificationType)
 unsigned ExceptionSpecType : 4;
@@ -1991,6 +1980,17 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
 /// Whether this function has a trailing return type.
 LLVM_PREFERRED_TYPE(bool)
 unsigned HasTrailingReturn : 1;
+
+/// Extra information which affects how the function is called, like
+/// regparm and the calling convention.
+LLVM_PREFERRED_TYPE(CallingConv)
+unsigned ExtInfo : 14;
+
+/// The number of parameters this function has, not counting '...'.
+/// According to [implimits] 8 bits should be enough here but this is
+/// somewhat easy to exceed with metaprogramming and so we would like to
+/// keep NumParams as wide as reasonably possible.
+unsigned NumParams : FunctionTypeNumParamsWidth;
   };
 
   class ObjCObjectTypeBitfields {



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


[clang] f3d4d11 - [clang][cmake] Fix support for dynamic libraries in CLANG_BOLT

2025-03-03 Thread via cfe-commits

Author: serge-sans-paille
Date: 2025-03-03T18:05:18+01:00
New Revision: f3d4d1154799b32512b0fed52c9938f76b9264b5

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

LOG: [clang][cmake] Fix support for dynamic libraries in CLANG_BOLT

Simpler detection of dynamic library operands as the readelf one seems
to be unreliable (works on my setup, not on buildbots).

This is a follow-up to #127020

Added: 


Modified: 
clang/utils/perf-training/perf-helper.py

Removed: 




diff  --git a/clang/utils/perf-training/perf-helper.py 
b/clang/utils/perf-training/perf-helper.py
index 7a049e71d9826..80c6356d0497c 100644
--- a/clang/utils/perf-training/perf-helper.py
+++ b/clang/utils/perf-training/perf-helper.py
@@ -628,15 +628,14 @@ def bolt_optimize(args):
 sys.stdout.write(line)
 process.check_returncode()
 
-output = subprocess.check_output(
-[opts.readelf, "--file-header", input], universal_newlines=True
-)
-if re.search(r"Type:\s*((Shared)|(DYN))", output):
-# force using the instrumented version
+# Shared library must be preloaded to be covered.
+if ".so" in input:
 preloads.append(instrumented_output)
 
 if preloads:
-print("Patching execution environment for dynamic library")
+print(
+f"Patching execution environment for dynamic libraries: {' 
'.join(preloads)}"
+)
 environ["LD_PRELOAD"] = os.pathsep.join(preloads)
 
 args = [



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


[clang] 4bd3427 - IRBuilder: Add FMFSource parameter to CreateMaxNum/CreateMinNum (#129173)

2025-03-03 Thread via cfe-commits

Author: YunQiang Su
Date: 2025-03-04T08:49:35+08:00
New Revision: 4bd34273210329047a7829f1ea4f54c171000c68

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

LOG: IRBuilder: Add FMFSource parameter to CreateMaxNum/CreateMinNum (#129173)

In https://github.com/llvm/llvm-project/pull/112852, we claimed that
llvm.minnum and llvm.maxnum should treat +0.0>-0.0, while libc doesn't
require fmin(3)/fmax(3) for it.

Let's add FMFSource parameter to CreateMaxNum and CreateMinNum, so that
they can be used by CodeGenFunction::EmitBuiltinExpr of Clang.

Added: 


Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
llvm/include/llvm/IR/IRBuilder.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 03b8d16b76e0d..ab8f19b25fa66 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -4378,7 +4378,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
  : llvm::Intrinsic::umax,
  Op0, Op1, nullptr, "elt.max");
 } else
-  Result = Builder.CreateMaxNum(Op0, Op1, "elt.max");
+  Result = Builder.CreateMaxNum(Op0, Op1, /*FMFSource=*/nullptr, 
"elt.max");
 return RValue::get(Result);
   }
   case Builtin::BI__builtin_elementwise_min: {
@@ -4394,7 +4394,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
  : llvm::Intrinsic::umin,
  Op0, Op1, nullptr, "elt.min");
 } else
-  Result = Builder.CreateMinNum(Op0, Op1, "elt.min");
+  Result = Builder.CreateMinNum(Op0, Op1, /*FMFSource=*/nullptr, 
"elt.min");
 return RValue::get(Result);
   }
 

diff  --git a/llvm/include/llvm/IR/IRBuilder.h 
b/llvm/include/llvm/IR/IRBuilder.h
index 933dbb306d1fc..67e357c600d3b 100644
--- a/llvm/include/llvm/IR/IRBuilder.h
+++ b/llvm/include/llvm/IR/IRBuilder.h
@@ -1005,23 +1005,27 @@ class IRBuilderBase {
 const Twine &Name = "");
 
   /// Create call to the minnum intrinsic.
-  Value *CreateMinNum(Value *LHS, Value *RHS, const Twine &Name = "") {
+  Value *CreateMinNum(Value *LHS, Value *RHS, FMFSource FMFSource = {},
+  const Twine &Name = "") {
 if (IsFPConstrained) {
   return CreateConstrainedFPUnroundedBinOp(
-  Intrinsic::experimental_constrained_minnum, LHS, RHS, nullptr, Name);
+  Intrinsic::experimental_constrained_minnum, LHS, RHS, FMFSource,
+  Name);
 }
 
-return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, nullptr, Name);
+return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, FMFSource, Name);
   }
 
   /// Create call to the maxnum intrinsic.
-  Value *CreateMaxNum(Value *LHS, Value *RHS, const Twine &Name = "") {
+  Value *CreateMaxNum(Value *LHS, Value *RHS, FMFSource FMFSource = {},
+  const Twine &Name = "") {
 if (IsFPConstrained) {
   return CreateConstrainedFPUnroundedBinOp(
-  Intrinsic::experimental_constrained_maxnum, LHS, RHS, nullptr, Name);
+  Intrinsic::experimental_constrained_maxnum, LHS, RHS, FMFSource,
+  Name);
 }
 
-return CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS, nullptr, Name);
+return CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS, FMFSource, Name);
   }
 
   /// Create call to the minimum intrinsic.



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


[clang] e1fd681 - Bump DIAG_SIZE_LEX since we've hit the limit downstream as of 1c4e0f6.

2025-03-03 Thread Douglas Gliner via cfe-commits

Author: Douglas Gliner
Date: 2025-03-03T15:40:50-08:00
New Revision: e1fd681837b85563e186f3739623cfa6653a722c

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

LOG: Bump DIAG_SIZE_LEX since we've hit the limit downstream as of 1c4e0f6.

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticIDs.h

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticIDs.h 
b/clang/include/clang/Basic/DiagnosticIDs.h
index b49185c3335d8..017ef7065610f 100644
--- a/clang/include/clang/Basic/DiagnosticIDs.h
+++ b/clang/include/clang/Basic/DiagnosticIDs.h
@@ -37,7 +37,7 @@ namespace clang {
   DIAG_SIZE_DRIVER=  400,
   DIAG_SIZE_FRONTEND  =  200,
   DIAG_SIZE_SERIALIZATION =  120,
-  DIAG_SIZE_LEX   =  400,
+  DIAG_SIZE_LEX   =  500,
   DIAG_SIZE_PARSE =  700,
   DIAG_SIZE_AST   =  300,
   DIAG_SIZE_COMMENT   =  100,



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


[clang] 0ed2945 - [clang-format] Don't sort includes for C# (#129369)

2025-03-03 Thread via cfe-commits

Author: Owen Pan
Date: 2025-03-03T17:40:02-08:00
New Revision: 0ed2945a596991b75e4ca090fe04240abba6012b

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

LOG: [clang-format] Don't sort includes for C# (#129369)

Fixes #106194

Added: 


Modified: 
clang/lib/Format/Format.cpp
clang/unittests/Format/SortIncludesTest.cpp

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 92678a031178a..c699a96d3f45e 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3547,7 +3547,8 @@ tooling::Replacements sortIncludes(const FormatStyle 
&Style, StringRef Code,
 return sortJavaScriptImports(Style, Code, Ranges, FileName);
   if (Style.Language == FormatStyle::LanguageKind::LK_Java)
 return sortJavaImports(Style, Code, Ranges, FileName, Replaces);
-  sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
+  if (Style.isCpp())
+sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
   return Replaces;
 }
 

diff  --git a/clang/unittests/Format/SortIncludesTest.cpp 
b/clang/unittests/Format/SortIncludesTest.cpp
index cb3f8c73a0487..f20862f5f7461 100644
--- a/clang/unittests/Format/SortIncludesTest.cpp
+++ b/clang/unittests/Format/SortIncludesTest.cpp
@@ -1085,6 +1085,15 @@ TEST_F(SortIncludesTest, DoNotSortLikelyXml) {
 "input.h", 0));
 }
 
+TEST_F(SortIncludesTest, DoNotSortCSharp) {
+  constexpr StringRef Code{"const string expectedDataStruct = @\"\n"
+   "#include \n"
+   "#include \n"
+   "\";"};
+  FmtStyle.Language = FormatStyle::LK_CSharp;
+  EXPECT_TRUE(sortIncludes(FmtStyle, Code, GetCodeRange(Code), 
"a.cs").empty());
+}
+
 TEST_F(SortIncludesTest, DoNotOutputReplacementsForSortedBlocksWithRegrouping) 
{
   Style.IncludeBlocks = Style.IBS_Regroup;
   StringRef Code = "#include \"b.h\"\n"



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


[clang] 2ca0855 - [clang-format] Fix a bug in wrapping function return type (#129374)

2025-03-03 Thread via cfe-commits

Author: Owen Pan
Date: 2025-03-03T18:15:32-08:00
New Revision: 2ca085505996ca16cc79090dbc66d06ac46ed262

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

LOG: [clang-format] Fix a bug in wrapping function return type (#129374)

Fixes #113766

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 972dceb697a8b..4cb24dbca5ad0 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -628,6 +628,10 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   // name.
   !Style.isJavaScript() && Previous.isNot(tok::kw_template) &&
   CurrentState.BreakBeforeParameter) {
+for (const auto *Tok = &Previous; Tok; Tok = Tok->Previous)
+  if (Tok->FirstAfterPPDirectiveLine || Tok->is(TT_LineComment))
+return false;
+
 return true;
   }
 

diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 02429970599c0..2cace7c3f060e 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -594,6 +594,9 @@ struct FormatToken {
   /// Has "\n\f\n" or "\n\f\r\n" before TokenText.
   bool HasFormFeedBefore = false;
 
+  /// Is the first token after a PPDirective line.
+  bool FirstAfterPPDirectiveLine = false;
+
   /// Number of optional braces to be inserted after this token:
   ///   -1: a single left brace
   ///0: no braces

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 16f19e955bf55..2da0432816df7 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -5091,8 +5091,10 @@ UnwrappedLineParser::parseMacroCall() {
 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
   Line->Tokens.push_back(UnwrappedLineNode(Tok));
   if (MustBreakBeforeNextToken) {
-Line->Tokens.back().Tok->MustBreakBefore = true;
-Line->Tokens.back().Tok->MustBreakBeforeFinalized = true;
+auto &Tok = *Line->Tokens.back().Tok;
+Tok.MustBreakBefore = true;
+Tok.MustBreakBeforeFinalized = true;
+Tok.FirstAfterPPDirectiveLine = true;
 MustBreakBeforeNextToken = false;
   }
 }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 537be3632f439..f3948142da0c9 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -6832,6 +6832,11 @@ TEST_F(FormatTest, 
LayoutStatementsAroundPreprocessorDirectives) {
"  param3) {\n"
"  f();\n"
"}");
+
+  verifyFormat("#ifdef __cplusplus\n"
+   "extern \"C\"\n"
+   "#endif\n"
+   "void f();");
 }
 
 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
@@ -8539,6 +8544,7 @@ TEST_F(FormatTest, BreaksFunctionDeclarations) {
   verifyGoogleFormat(
   "SomeLoogType operator<<(\n"
   "const SomeLogType &a, const SomeLogType &b);");
+
   verifyFormat("void (\n"
"int aaa = 1);");
   verifyFormat("aa\n"
@@ -8552,6 +8558,9 @@ TEST_F(FormatTest, BreaksFunctionDeclarations) {
  "aaa::a(\n"
  "aaa aaa);");
 
+  verifyFormat("extern \"C\" //\n"
+   "void f();");
+
   FormatStyle Style = getLLVMStyle();
   Style.PointerAlignment = FormatStyle::PAS_Left;
   verifyFormat("void aa(\n"



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


[clang] a21ae2f - [CodeGen][ObjCGNU] Replace PointerType::getUnqual(Type) with opaque pointer version (NFC) (#128715)

2025-03-03 Thread via cfe-commits

Author: Mats Jun Larsen
Date: 2025-03-03T22:51:00+01:00
New Revision: a21ae2f04f529b6b62d83786e867e9d7dc169369

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

LOG: [CodeGen][ObjCGNU] Replace PointerType::getUnqual(Type) with opaque 
pointer version (NFC) (#128715)

Follow-up to #123569

Added: 


Modified: 
clang/lib/CodeGen/CGObjCGNU.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp
index d1876f47c0eea..495060ea0e6a2 100644
--- a/clang/lib/CodeGen/CGObjCGNU.cpp
+++ b/clang/lib/CodeGen/CGObjCGNU.cpp
@@ -819,7 +819,7 @@ class CGObjCGNUstep : public CGObjCGNU {
   const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
 
   SlotStructTy = llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
-  SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
+  SlotTy = PtrTy;
   // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
   SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
 SelectorTy, IdTy);
@@ -2284,10 +2284,12 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned 
runtimeABIVersion,
   BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
 
   Int8Ty = llvm::Type::getInt8Ty(VMContext);
+
+  PtrTy = llvm::PointerType::getUnqual(cgm.getLLVMContext());
+  PtrToIntTy = PtrTy;
   // C string type.  Used in lots of places.
-  PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
-  ProtocolPtrTy = llvm::PointerType::getUnqual(
-  Types.ConvertType(CGM.getContext().getObjCProtoType()));
+  PtrToInt8Ty = PtrTy;
+  ProtocolPtrTy = PtrTy;
 
   Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
   Zeros[1] = Zeros[0];
@@ -2302,9 +2304,6 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned 
runtimeABIVersion,
 SelectorElemTy = CGM.getTypes().ConvertTypeForMem(selTy->getPointeeType());
   }
 
-  PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
-  PtrTy = PtrToInt8Ty;
-
   Int32Ty = llvm::Type::getInt32Ty(VMContext);
   Int64Ty = llvm::Type::getInt64Ty(VMContext);
 
@@ -2323,7 +2322,7 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned 
runtimeABIVersion,
 IdTy = PtrToInt8Ty;
 IdElemTy = Int8Ty;
   }
-  PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
+  PtrToIdTy = PtrTy;
   ProtocolTy = llvm::StructType::get(IdTy,
   PtrToInt8Ty, // name
   PtrToInt8Ty, // protocols
@@ -2351,7 +2350,7 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned 
runtimeABIVersion,
   PtrToInt8Ty, PtrToInt8Ty });
 
   ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
-  PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
+  PtrToObjCSuperTy = PtrTy;
 
   llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
 
@@ -2383,9 +2382,7 @@ CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned 
runtimeABIVersion,
PtrDiffTy, BoolTy, BoolTy);
 
   // IMP type
-  llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
-  IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
-  true));
+  IMPTy = PtrTy;
 
   const LangOptions &Opts = CGM.getLangOpts();
   if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
@@ -2679,8 +2676,6 @@ CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
 Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
 if (IsClassMessage)  {
   // Load the isa pointer of the superclass is this is a class method.
-  ReceiverClass = Builder.CreateBitCast(ReceiverClass,
-
llvm::PointerType::getUnqual(IdTy));
   ReceiverClass =
 Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
 }
@@ -2721,8 +2716,6 @@ CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
 }
 // Cast the pointer to a simplified version of the class structure
 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
-ReceiverClass = Builder.CreateBitCast(ReceiverClass,
-  
llvm::PointerType::getUnqual(CastTy));
 // Get the superclass pointer
 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
 // Load the superclass pointer
@@ -3269,10 +3262,7 @@ CGObjCGNU::GenerateProtocolList(ArrayRef 
Protocols) {
 
 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
 const ObjCProtocolDecl *PD) {
-  auto protocol = GenerateProtocolRef(PD);
-  llvm::Type *T =
-  CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
-  return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
+  return GenerateProtocolRef(PD);
 }
 
 llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {



___

[clang] 94fad11 - [CodeGen] Replace PointerType::getUnqual(Type) with opaque pointer version (NFC) (#128711)

2025-03-03 Thread via cfe-commits

Author: Mats Jun Larsen
Date: 2025-03-03T23:00:32+01:00
New Revision: 94fad113070878c37f00699ca9d74b6216910af5

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

LOG: [CodeGen] Replace PointerType::getUnqual(Type) with opaque  pointer 
version (NFC) (#128711)

pointer version (NFC)

Follow-up to #123569

Added: 


Modified: 
clang/lib/CodeGen/ABIInfoImpl.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntime.h
clang/lib/CodeGen/ItaniumCXXABI.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/ABIInfoImpl.cpp 
b/clang/lib/CodeGen/ABIInfoImpl.cpp
index 68887cd7916c7..0a612d3461dc2 100644
--- a/clang/lib/CodeGen/ABIInfoImpl.cpp
+++ b/clang/lib/CodeGen/ABIInfoImpl.cpp
@@ -430,7 +430,7 @@ Address CodeGen::EmitVAArgInstr(CodeGenFunction &CGF, 
Address VAListAddr,
 CharUnits TyAlignForABI = TyInfo.Align;
 
 llvm::Type *ElementTy = CGF.ConvertTypeForMem(Ty);
-llvm::Type *BaseTy = llvm::PointerType::getUnqual(ElementTy);
+llvm::Type *BaseTy = llvm::PointerType::getUnqual(CGF.getLLVMContext());
 llvm::Value *Addr =
 CGF.Builder.CreateVAArg(VAListAddr.emitRawPointer(CGF), BaseTy);
 return Address(Addr, ElementTy, TyAlignForABI);

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index c2289985e9519..cfb7439e43e29 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1475,16 +1475,6 @@ llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
   return OMPBuilder.IdentPtr;
 }
 
-llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
-  if (!Kmpc_MicroTy) {
-// Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 
*bound_tid,...)
-llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
- llvm::PointerType::getUnqual(CGM.Int32Ty)};
-Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
-  }
-  return llvm::PointerType::getUnqual(Kmpc_MicroTy);
-}
-
 static llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseKind
 convertDeviceClause(const VarDecl *VD) {
   std::optional DevTy =
@@ -1861,7 +1851,7 @@ void CGOpenMPRuntime::emitParallelCall(CodeGenFunction 
&CGF, SourceLocation Loc,
 llvm::Value *Args[] = {
 RTLoc,
 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
-CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
+OutlinedFn};
 llvm::SmallVector RealArgs;
 RealArgs.append(std::begin(Args), std::end(Args));
 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
@@ -9937,7 +9927,7 @@ void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
   llvm::Value *Args[] = {
   RTLoc,
   CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
-  CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
+  OutlinedFn};
   llvm::SmallVector RealArgs;
   RealArgs.append(std::begin(Args), std::end(Args));
   RealArgs.append(CapturedVars.begin(), CapturedVars.end());

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.h 
b/clang/lib/CodeGen/CGOpenMPRuntime.h
index 3791bb7159235..4321712e1521d 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.h
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.h
@@ -386,10 +386,6 @@ class CGOpenMPRuntime {
   /// Map for SourceLocation and OpenMP runtime library debug locations.
   typedef llvm::DenseMap OpenMPDebugLocMapTy;
   OpenMPDebugLocMapTy OpenMPDebugLocMap;
-  /// The type for a microtask which gets passed to __kmpc_fork_call().
-  /// Original representation is:
-  /// typedef void (kmpc_micro)(kmp_int32 global_tid, kmp_int32 bound_tid,...);
-  llvm::FunctionType *Kmpc_MicroTy = nullptr;
   /// Stores debug location and ThreadID for the function.
   struct DebugLocThreadIdTy {
 llvm::Value *DebugLoc;
@@ -530,9 +526,6 @@ class CGOpenMPRuntime {
   /// Build type kmp_routine_entry_t (if not built yet).
   void emitKmpRoutineEntryT(QualType KmpInt32Ty);
 
-  /// Returns pointer to kmpc_micro type.
-  llvm::Type *getKmpc_MicroPointerTy();
-
   /// If the specified mangled name is not in the module, create and
   /// return threadprivate cache object. This object is a pointer's worth of
   /// storage that's reserved for use by the OpenMP runtime.

diff  --git a/clang/lib/CodeGen/ItaniumCXXABI.cpp 
b/clang/lib/CodeGen/ItaniumCXXABI.cpp
index bb9b6fd210667..7e26a0da3d7d2 100644
--- a/clang/lib/CodeGen/ItaniumCXXABI.cpp
+++ b/clang/lib/CodeGen/ItaniumCXXABI.cpp
@@ -953,7 +953,7 @@ ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction 
&CGF,
   Builder.CreateCondBr(IsVirtualOffset, MergeBB, ResignBB);
 
   CGF.EmitBlock(ResignBB);
-  llvm::Type *PtrTy = llvm::PointerType::getUnqual(CGM.Int8Ty);
+  llvm::Type *

[clang] d5cec38 - [OpenACC] Implement 'cache' construct AST/Sema

2025-03-03 Thread via cfe-commits

Author: erichkeane
Date: 2025-03-03T13:57:23-08:00
New Revision: d5cec386c14ac46ee252da29f5bd766db0adb6d0

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

LOG: [OpenACC] Implement 'cache' construct AST/Sema

This statement level construct takes no clauses and has no associated
statement, and simply labels a number of array elements as valid for
caching. The implementation here is pretty simple, but it is a touch of
a special case for parsing, so the parsing code reflects that.

Added: 
clang/test/AST/ast-print-openacc-cache-construct.cpp
clang/test/SemaOpenACC/cache-construct-ast.cpp
clang/test/SemaOpenACC/cache-construct.cpp

Modified: 
clang/include/clang-c/Index.h
clang/include/clang/AST/RecursiveASTVisitor.h
clang/include/clang/AST/StmtOpenACC.h
clang/include/clang/AST/TextNodeDumper.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Basic/StmtNodes.td
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/SemaOpenACC.h
clang/include/clang/Serialization/ASTBitCodes.h
clang/lib/AST/StmtOpenACC.cpp
clang/lib/AST/StmtPrinter.cpp
clang/lib/AST/StmtProfile.cpp
clang/lib/AST/TextNodeDumper.cpp
clang/lib/CodeGen/CGStmt.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/Parse/ParseOpenACC.cpp
clang/lib/Sema/SemaExceptionSpec.cpp
clang/lib/Sema/SemaOpenACC.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReaderStmt.cpp
clang/lib/Serialization/ASTWriterStmt.cpp
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/test/ParserOpenACC/parse-cache-construct.c
clang/test/ParserOpenACC/parse-cache-construct.cpp
clang/tools/libclang/CIndex.cpp
clang/tools/libclang/CXCursor.cpp

Removed: 




diff  --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index c50410dc365b6..38e2417dcd181 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/include/clang-c/Index.h
@@ -2214,7 +2214,11 @@ enum CXCursorKind {
*/
   CXCursor_OpenACCAtomicConstruct = 332,
 
-  CXCursor_LastStmt = CXCursor_OpenACCAtomicConstruct,
+  /** OpenACC cache Construct.
+   */
+  CXCursor_OpenACCCacheConstruct = 333,
+
+  CXCursor_LastStmt = CXCursor_OpenACCCacheConstruct,
 
   /**
* Cursor that represents the translation unit itself.

diff  --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index b1b4363b65721..89757ddb0781f 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -4113,6 +4113,10 @@ DEF_TRAVERSE_STMT(OpenACCUpdateConstruct,
   { TRY_TO(VisitOpenACCClauseList(S->clauses())); })
 DEF_TRAVERSE_STMT(OpenACCAtomicConstruct,
   { TRY_TO(TraverseOpenACCAssociatedStmtConstruct(S)); })
+DEF_TRAVERSE_STMT(OpenACCCacheConstruct, {
+  for (auto *E : S->getVarList())
+TRY_TO(TraverseStmt(E));
+})
 
 // Traverse HLSL: Out argument expression
 DEF_TRAVERSE_STMT(HLSLOutArgExpr, {})

diff  --git a/clang/include/clang/AST/StmtOpenACC.h 
b/clang/include/clang/AST/StmtOpenACC.h
index bd6c95d342ce2..c2c74f5cf1958 100644
--- a/clang/include/clang/AST/StmtOpenACC.h
+++ b/clang/include/clang/AST/StmtOpenACC.h
@@ -593,6 +593,81 @@ class OpenACCWaitConstruct final
   }
 };
 
+class OpenACCCacheConstruct final
+: public OpenACCConstructStmt,
+  private llvm::TrailingObjects {
+  friend TrailingObjects;
+  friend class ASTStmtWriter;
+  friend class ASTStmtReader;
+  // Locations of the left and right parens of the 'var-list'
+  // expression-list.
+  SourceRange ParensLoc;
+  SourceLocation ReadOnlyLoc;
+
+  unsigned NumVars = 0;
+
+  OpenACCCacheConstruct(unsigned NumVars)
+  : OpenACCConstructStmt(OpenACCCacheConstructClass,
+ OpenACCDirectiveKind::Cache, SourceLocation{},
+ SourceLocation{}, SourceLocation{}),
+NumVars(NumVars) {
+std::uninitialized_value_construct(getVarListPtr(),
+   getVarListPtr() + NumVars);
+  }
+  OpenACCCacheConstruct(SourceLocation Start, SourceLocation DirectiveLoc,
+SourceLocation LParenLoc, SourceLocation ReadOnlyLoc,
+ArrayRef VarList, SourceLocation RParenLoc,
+SourceLocation End)
+  : OpenACCConstructStmt(OpenACCCacheConstructClass,
+ OpenACCDirectiveKind::Cache, Start, DirectiveLoc,
+ End),
+ParensLoc(LParenLoc, RParenLoc), ReadOnlyLoc(ReadOnlyLoc),
+NumVars(VarList.size()) {
+
+std::uninitialized_copy(VarList.begin(), VarList.end(), getVarListPtr());
+  }
+
+  Expr **getVarListPtr() const {
+return const_cast(getTrailingO

[clang] f98718c - Remove leftover unused variable from #128711

2025-03-03 Thread Mats Jun Larsen via cfe-commits

Author: Mats Jun Larsen
Date: 2025-03-03T23:32:03+01:00
New Revision: f98718c9a169d90e676f877c5b6761b22f424b73

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

LOG: Remove leftover unused variable from #128711

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index cfb7439e43e29..06a652c146fb9 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1847,7 +1847,6 @@ void CGOpenMPRuntime::emitParallelCall(CodeGenFunction 
&CGF, SourceLocation Loc,
   auto &&ThenGen = [&M, OutlinedFn, CapturedVars, RTLoc,
 this](CodeGenFunction &CGF, PrePostActionTy &) {
 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
-CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
 llvm::Value *Args[] = {
 RTLoc,
 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars



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


[clang] 25713ed - [HLSL] Add additional overloads for min and max to allow for mixed scalar and vector arguments (#129334)

2025-03-03 Thread via cfe-commits

Author: Sarah Spall
Date: 2025-03-03T11:29:58-08:00
New Revision: 25713ed85fd327f4733b2ac6083c23464aa9c646

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

LOG: [HLSL] Add additional overloads for min and max to allow for mixed scalar 
and vector arguments (#129334)

Add additional overloads for min and max to support
min(vector, T) and min(T, vector)
max(vector, T) and max(T, vector)
Add tests
Closes #128231

Added: 


Modified: 
clang/lib/Headers/hlsl/hlsl_intrinsics.h
clang/test/CodeGenHLSL/builtins/max.hlsl
clang/test/CodeGenHLSL/builtins/min.hlsl

Removed: 




diff  --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h 
b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
index ed008eeb04ba8..734fc8d29b28f 100644
--- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h
+++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
@@ -37,6 +37,26 @@ namespace hlsl {
 #define _HLSL_16BIT_AVAILABILITY_STAGE(environment, version, stage)
 #endif
 
+#define GEN_VEC_SCALAR_OVERLOADS(FUNC_NAME, BASE_TYPE, AVAIL)  
\
+  GEN_BOTH_OVERLOADS(FUNC_NAME, BASE_TYPE, BASE_TYPE##2, AVAIL)
\
+  GEN_BOTH_OVERLOADS(FUNC_NAME, BASE_TYPE, BASE_TYPE##3, AVAIL)
\
+  GEN_BOTH_OVERLOADS(FUNC_NAME, BASE_TYPE, BASE_TYPE##4, AVAIL)
+
+#define GEN_BOTH_OVERLOADS(FUNC_NAME, BASE_TYPE, VECTOR_TYPE, AVAIL)   
\
+  IF_TRUE_##AVAIL( 
\
+  _HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)) constexpr VECTOR_TYPE
\
+  FUNC_NAME(VECTOR_TYPE p0, BASE_TYPE p1) {
\
+return __builtin_elementwise_##FUNC_NAME(p0, (VECTOR_TYPE)p1); 
\
+  }
\
+  IF_TRUE_##AVAIL( 
\
+  _HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)) constexpr VECTOR_TYPE
\
+  FUNC_NAME(BASE_TYPE p0, VECTOR_TYPE p1) {
\
+return __builtin_elementwise_##FUNC_NAME((VECTOR_TYPE)p0, p1); 
\
+  }
+
+#define IF_TRUE_0(EXPR)
+#define IF_TRUE_1(EXPR) EXPR
+
 
//===--===//
 // abs builtins
 
//===--===//
@@ -1700,6 +1720,7 @@ half3 max(half3, half3);
 _HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 half4 max(half4, half4);
+GEN_VEC_SCALAR_OVERLOADS(max, half, 1)
 
 #ifdef __HLSL_ENABLE_16_BIT
 _HLSL_AVAILABILITY(shadermodel, 6.2)
@@ -1714,6 +1735,7 @@ int16_t3 max(int16_t3, int16_t3);
 _HLSL_AVAILABILITY(shadermodel, 6.2)
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 int16_t4 max(int16_t4, int16_t4);
+GEN_VEC_SCALAR_OVERLOADS(max, int16_t, 1)
 
 _HLSL_AVAILABILITY(shadermodel, 6.2)
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
@@ -1727,6 +1749,7 @@ uint16_t3 max(uint16_t3, uint16_t3);
 _HLSL_AVAILABILITY(shadermodel, 6.2)
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 uint16_t4 max(uint16_t4, uint16_t4);
+GEN_VEC_SCALAR_OVERLOADS(max, uint16_t, 1)
 #endif
 
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
@@ -1737,6 +1760,7 @@ _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 int3 max(int3, int3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 int4 max(int4, int4);
+GEN_VEC_SCALAR_OVERLOADS(max, int, 0)
 
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 uint max(uint, uint);
@@ -1746,6 +1770,7 @@ _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 uint3 max(uint3, uint3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 uint4 max(uint4, uint4);
+GEN_VEC_SCALAR_OVERLOADS(max, uint, 0)
 
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 int64_t max(int64_t, int64_t);
@@ -1755,6 +1780,7 @@ _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 int64_t3 max(int64_t3, int64_t3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 int64_t4 max(int64_t4, int64_t4);
+GEN_VEC_SCALAR_OVERLOADS(max, int64_t, 0)
 
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 uint64_t max(uint64_t, uint64_t);
@@ -1764,6 +1790,7 @@ _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 uint64_t3 max(uint64_t3, uint64_t3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 uint64_t4 max(uint64_t4, uint64_t4);
+GEN_VEC_SCALAR_OVERLOADS(max, uint64_t, 0)
 
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 float max(float, float);
@@ -1773,6 +1800,7 @@ _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 float3 max(float3, float3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 float4 max(float4, float4);
+GEN_VEC_SCALAR_OVERLOADS(max, float, 0)
 
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 double max(double, double);
@@ -1782,6 +1810,7 @@ _HLSL_BUILTIN_ALIAS(__builtin_elementwise_max)
 double3 max(dou

[clang] 50ff49e - Clang: ExprConstant use maxnum/minnum for fmax/fmin (#129630)

2025-03-03 Thread via cfe-commits

Author: YunQiang Su
Date: 2025-03-04T12:26:44+08:00
New Revision: 50ff49ebbcdc88301070e94b04cb158d040db276

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

LOG: Clang: ExprConstant use maxnum/minnum for fmax/fmin (#129630)

In APFloat, we have defined maxnum and minnum, so let's use them
directly here.

In `maxnum`/`minnum` of APFloat, we process sNaN, signed-zero as
strictly as possible.

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index ef1d763009453..7244120d1be51 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -15604,16 +15604,11 @@ bool FloatExprEvaluator::VisitCallExpr(const CallExpr 
*E) {
   case Builtin::BI__builtin_fmaxl:
   case Builtin::BI__builtin_fmaxf16:
   case Builtin::BI__builtin_fmaxf128: {
-// TODO: Handle sNaN.
 APFloat RHS(0.);
 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
 !EvaluateFloat(E->getArg(1), RHS, Info))
   return false;
-// When comparing zeroes, return +0.0 if one of the zeroes is positive.
-if (Result.isZero() && RHS.isZero() && Result.isNegative())
-  Result = RHS;
-else if (Result.isNaN() || RHS > Result)
-  Result = RHS;
+Result = maxnum(Result, RHS);
 return true;
   }
 
@@ -15622,16 +15617,11 @@ bool FloatExprEvaluator::VisitCallExpr(const CallExpr 
*E) {
   case Builtin::BI__builtin_fminl:
   case Builtin::BI__builtin_fminf16:
   case Builtin::BI__builtin_fminf128: {
-// TODO: Handle sNaN.
 APFloat RHS(0.);
 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
 !EvaluateFloat(E->getArg(1), RHS, Info))
   return false;
-// When comparing zeroes, return -0.0 if one of the zeroes is negative.
-if (Result.isZero() && RHS.isZero() && RHS.isNegative())
-  Result = RHS;
-else if (Result.isNaN() || RHS < Result)
-  Result = RHS;
+Result = minnum(Result, RHS);
 return true;
   }
 



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


[clang] ce1a18e - clang-tools: Fix sprintf is deprecated warnings (#120517)

2025-03-03 Thread via cfe-commits

Author: Matt Arsenault
Date: 2025-03-04T09:53:31+07:00
New Revision: ce1a18e2c714f39fe72cd46aa04faed29ad23cb6

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

LOG: clang-tools: Fix sprintf is deprecated warnings (#120517)

Added: 


Modified: 
clang/tools/c-index-test/c-index-test.c

Removed: 




diff  --git a/clang/tools/c-index-test/c-index-test.c 
b/clang/tools/c-index-test/c-index-test.c
index 0e7de8b98ea07..942500f2975e4 100644
--- a/clang/tools/c-index-test/c-index-test.c
+++ b/clang/tools/c-index-test/c-index-test.c
@@ -376,7 +376,7 @@ static int parse_remapped_files_with_try(int try_idx,
   if (ret)
 return ret;
 
-  sprintf(opt_name, "-remap-file-%d=", try_idx);
+  snprintf(opt_name, sizeof(opt_name), "-remap-file-%d=", try_idx);
   ret = parse_remapped_files_with_opt(opt_name, argc, argv, start_arg,
   &unsaved_files_try_idx, &num_unsaved_files_try_idx);
   if (ret)
@@ -1184,8 +1184,9 @@ static void PrintCursor(CXCursor Cursor, const char 
*CommentSchemaFile) {
   CXString Spelling = clang_getCursorSpelling(Cursor);
   const char *CName = clang_getCString(Name);
   const char *CSpelling = clang_getCString(Spelling);
-  char *DefaultSetter = malloc(strlen(CSpelling) + 5);
-  sprintf(DefaultSetter, "set%s:", CSpelling);
+  size_t Len = strlen(CSpelling) + 5;
+  char *DefaultSetter = malloc(Len);
+  snprintf(DefaultSetter, Len, "set%s:", CSpelling);
   DefaultSetter[3] &= ~(1 << 5); /* Make uppercase */
   if (CName && strcmp(CName, DefaultSetter)) {
 printf(" (setter=%s)", CName);
@@ -3545,19 +3546,20 @@ static CXIdxClientContainer 
makeClientContainer(CXClientData *client_data,
   char *newStr;
   CXIdxClientFile file;
   unsigned line, column;
-  
+  size_t len;
+
   name = info->name;
   if (!name)
 name = "";
 
   clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
 
-  node =
-  (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) 
+
-digitCount(line) + digitCount(column) + 2);
+  len = sizeof(IndexDataStringList) + strlen(name) + digitCount(line) +
+digitCount(column) + 2;
+  node = (IndexDataStringList *)malloc(len);
   assert(node);
   newStr = node->data;
-  sprintf(newStr, "%s:%d:%d", name, line, column);
+  snprintf(newStr, len, "%s:%d:%d", name, line, column);
 
   /* Remember string so it can be freed later. */
   index_data = (IndexData *)client_data;



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


[clang] c1aebd4 - [Clang][OpenCL] Wrap image functions with the macro (#129177)

2025-03-03 Thread via cfe-commits

Author: Victor Mustya
Date: 2025-03-03T16:50:52-08:00
New Revision: c1aebd495be0e468044f716a3a0ff98fb2be

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

LOG: [Clang][OpenCL] Wrap image functions with the macro (#129177)

According to the OpenCL C spec, the image functions are optional.
For OpenCL C 1.2, the image functions are guarded by the
`__IMAGE_SUPPORT__` macro. For the OpenCL C 3.0 and later, the
`__opencl_c_images` macro is used.

Added: 


Modified: 
clang/lib/Headers/opencl-c.h

Removed: 




diff  --git a/clang/lib/Headers/opencl-c.h b/clang/lib/Headers/opencl-c.h
index 20719b74b6b8d..8d8ef497cec49 100644
--- a/clang/lib/Headers/opencl-c.h
+++ b/clang/lib/Headers/opencl-c.h
@@ -15082,6 +15082,7 @@ half16 __ovld __cnfn shuffle2(half16, half16, ushort16);
 #pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable
 #endif //cl_khr_gl_msaa_sharing
 
+#if (defined(__opencl_c_images) || defined(__IMAGE_SUPPORT__))
 /**
  * Use the coordinate (coord.xy) to do an element lookup in
  * the 2D image object specified by image.
@@ -16143,6 +16144,8 @@ int __ovld __cnfn get_image_num_samples(read_write 
image2d_array_msaa_depth_t);
 #endif //defined(__opencl_c_read_write_images)
 #endif
 
+#endif // (defined(__opencl_c_images) || defined(__IMAGE_SUPPORT__))
+
 // OpenCL v2.0 s6.13.15 - Work-group Functions
 
 #if defined(__opencl_c_work_group_collective_functions)



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


[clang] 136f257 - [clang-format] Lex C++ only keywords as identifiers in C (#129426)

2025-03-03 Thread via cfe-commits

Author: Owen Pan
Date: 2025-03-03T17:40:28-08:00
New Revision: 136f2574ddfe81e73376ada0ea299b67170caf2c

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

LOG: [clang-format] Lex C++ only keywords as identifiers in C (#129426)

Fix #128847

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index c699a96d3f45e..b5f1241321891 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3942,34 +3942,42 @@ tooling::Replacements sortUsingDeclarations(const 
FormatStyle &Style,
 LangOptions getFormattingLangOpts(const FormatStyle &Style) {
   LangOptions LangOpts;
 
-  FormatStyle::LanguageStandard LexingStd = Style.Standard;
-  if (LexingStd == FormatStyle::LS_Auto)
-LexingStd = FormatStyle::LS_Latest;
-  if (LexingStd == FormatStyle::LS_Latest)
+  auto LexingStd = Style.Standard;
+  if (LexingStd == FormatStyle::LS_Auto || LexingStd == FormatStyle::LS_Latest)
 LexingStd = FormatStyle::LS_Cpp20;
-  LangOpts.CPlusPlus = 1;
-  LangOpts.CPlusPlus11 = LexingStd >= FormatStyle::LS_Cpp11;
-  LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
-  LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
-  LangOpts.CPlusPlus20 = LexingStd >= FormatStyle::LS_Cpp20;
-  LangOpts.Char8 = LexingStd >= FormatStyle::LS_Cpp20;
+
+  const bool SinceCpp11 = LexingStd >= FormatStyle::LS_Cpp11;
+  const bool SinceCpp20 = LexingStd >= FormatStyle::LS_Cpp20;
+
+  switch (Style.Language) {
+  case FormatStyle::LK_C:
+LangOpts.C17 = 1;
+break;
+  case FormatStyle::LK_Cpp:
+  case FormatStyle::LK_ObjC:
+LangOpts.CXXOperatorNames = 1;
+LangOpts.CPlusPlus11 = SinceCpp11;
+LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp14;
+LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp17;
+LangOpts.CPlusPlus20 = SinceCpp20;
+[[fallthrough]];
+  default:
+LangOpts.CPlusPlus = 1;
+  }
+
+  LangOpts.Char8 = SinceCpp20;
   // Turning on digraphs in standards before C++0x is error-prone, because e.g.
   // the sequence "<::" will be unconditionally treated as "[:".
   // Cf. Lexer::LexTokenInternal.
-  LangOpts.Digraphs = LexingStd >= FormatStyle::LS_Cpp11;
+  LangOpts.Digraphs = SinceCpp11;
 
   LangOpts.LineComment = 1;
-
-  const auto Language = Style.Language;
-  LangOpts.C17 = Language == FormatStyle::LK_C;
-  LangOpts.CXXOperatorNames =
-  Language == FormatStyle::LK_Cpp || Language == FormatStyle::LK_ObjC;
-
   LangOpts.Bool = 1;
   LangOpts.ObjC = 1;
   LangOpts.MicrosoftExt = 1;// To get kw___try, kw___finally.
   LangOpts.DeclSpecKeyword = 1; // To get __declspec.
   LangOpts.C99 = 1; // To get kw_restrict for non-underscore-prefixed restrict.
+
   return LangOpts;
 }
 

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 1e1774ba5b3b5..b44a369f77d92 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -3705,6 +3705,15 @@ TEST_F(TokenAnnotatorTest, CppAltOperatorKeywords) {
   EXPECT_TOKEN(Tokens[1], tok::identifier, TT_StartOfName);
 }
 
+TEST_F(TokenAnnotatorTest, CppOnlyKeywordInC) {
+  auto Tokens = annotate("int maximized = new & STATE_MAXIMIZED;",
+ getLLVMStyle(FormatStyle::LK_C));
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::identifier, TT_Unknown); // Not tok::kw_new
+  EXPECT_TOKEN(Tokens[4], tok::amp, TT_BinaryOperator);
+  EXPECT_TOKEN(Tokens[3], tok::identifier, TT_Unknown); // Not TT_StartOfName
+}
+
 TEST_F(TokenAnnotatorTest, FunctionTryBlock) {
   auto Tokens =
   annotate("Foo::Foo(int x, int y) try\n"



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


[clang] 82d111e - [clang][bytecode][NFC] Minor cleanups (#129553)

2025-03-03 Thread via cfe-commits

Author: Timm Baeder
Date: 2025-03-04T06:17:07+01:00
New Revision: 82d111e8202328d3a04d923cdae19ad29bc79dbc

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

LOG: [clang][bytecode][NFC] Minor cleanups (#129553)

Pull local variables in to the closest scope, remove some unnecessary
calls to getLocation() and remove an outdated comment.

Added: 


Modified: 
clang/lib/AST/ByteCode/Interp.cpp
clang/lib/AST/ByteCode/Pointer.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Interp.cpp 
b/clang/lib/AST/ByteCode/Interp.cpp
index 67b7ac1f8f0f9..bf9fdb6a690db 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -551,8 +551,8 @@ bool CheckInitialized(InterpState &S, CodePtr OpPC, const 
Pointer &Ptr,
 
   if (const auto *VD = Ptr.getDeclDesc()->asVarDecl();
   VD && (VD->isConstexpr() || VD->hasGlobalStorage())) {
-const SourceInfo &Loc = S.Current->getSource(OpPC);
 if (VD->getAnyInitializer()) {
+  const SourceInfo &Loc = S.Current->getSource(OpPC);
   S.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << VD;
   S.Note(VD->getLocation(), diag::note_declared_at);
 } else {
@@ -722,7 +722,6 @@ bool CheckCallable(InterpState &S, CodePtr OpPC, const 
Function *F) {
   if (F->isLambdaStaticInvoker())
 return true;
 
-  const SourceLocation &Loc = S.Current->getLocation(OpPC);
   if (S.getLangOpts().CPlusPlus11) {
 const FunctionDecl *DiagDecl = F->getDecl();
 
@@ -748,7 +747,8 @@ bool CheckCallable(InterpState &S, CodePtr OpPC, const 
Function *F) {
 // or an inheriting constructor, we should be much more explicit about why
 // it's not constexpr.
 if (CD && CD->isInheritingConstructor()) {
-  S.FFDiag(Loc, diag::note_constexpr_invalid_inhctor, 1)
+  S.FFDiag(S.Current->getLocation(OpPC),
+   diag::note_constexpr_invalid_inhctor, 1)
   << CD->getInheritedConstructor().getConstructor()->getParent();
   S.Note(DiagDecl->getLocation(), diag::note_declared_at);
 } else {
@@ -766,7 +766,8 @@ bool CheckCallable(InterpState &S, CodePtr OpPC, const 
Function *F) {
   DiagDecl->hasBody())
 return false;
 
-  S.FFDiag(Loc, diag::note_constexpr_invalid_function, 1)
+  S.FFDiag(S.Current->getLocation(OpPC),
+   diag::note_constexpr_invalid_function, 1)
   << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
 
   if (DiagDecl->getDefinition())
@@ -776,7 +777,8 @@ bool CheckCallable(InterpState &S, CodePtr OpPC, const 
Function *F) {
 S.Note(DiagDecl->getLocation(), diag::note_declared_at);
 }
   } else {
-S.FFDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
+S.FFDiag(S.Current->getLocation(OpPC),
+ diag::note_invalid_subexpr_in_const_expr);
   }
 
   return false;
@@ -980,11 +982,6 @@ bool CheckNonNullArgs(InterpState &S, CodePtr OpPC, const 
Function *F,
   return true;
 }
 
-// FIXME: This is similar to code we already have in Compiler.cpp.
-// I think it makes sense to instead add the field and base destruction stuff
-// to the destructor Function itself. Then destroying a record would really
-// _just_ be calling its destructor. That would also help with the diagnostic
-// 
diff erence when the destructor or a field/base fails.
 static bool runRecordDestructor(InterpState &S, CodePtr OpPC,
 const Pointer &BasePtr,
 const Descriptor *Desc) {
@@ -1095,8 +1092,8 @@ bool Free(InterpState &S, CodePtr OpPC, bool 
DeleteIsArrayForm,
 
 // For a class type with a virtual destructor, the selected operator delete
 // is the one looked up when building the destructor.
-QualType AllocType = Ptr.getType();
 if (!DeleteIsArrayForm && !IsGlobalDelete) {
+  QualType AllocType = Ptr.getType();
   auto getVirtualOperatorDelete = [](QualType T) -> const FunctionDecl * {
 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
   if (const CXXDestructorDecl *DD = RD->getDestructor())

diff  --git a/clang/lib/AST/ByteCode/Pointer.cpp 
b/clang/lib/AST/ByteCode/Pointer.cpp
index 92cfa192fd385..e5876409edcf7 100644
--- a/clang/lib/AST/ByteCode/Pointer.cpp
+++ b/clang/lib/AST/ByteCode/Pointer.cpp
@@ -384,7 +384,6 @@ void Pointer::initialize() const {
 return;
 
   assert(PointeeStorage.BS.Pointee && "Cannot initialize null pointer");
-  const Descriptor *Desc = getFieldDesc();
 
   if (isRoot() && PointeeStorage.BS.Base == sizeof(GlobalInlineDescriptor)) {
 GlobalInlineDescriptor &GD = *reinterpret_cast(
@@ -393,6 +392,7 @@ void Pointer::initialize() const {
 return;
   }
 
+  const Descriptor *Desc = getFieldDesc();
   assert(Desc);
   if (Desc->isPrimitiveArray()) {
 // Primitive global

[clang] e9fe95a - [clang][bytecode][NFC] Use maxnum/minnum for fmax/fmin (#129643)

2025-03-03 Thread via cfe-commits

Author: Timm Baeder
Date: 2025-03-04T07:22:54+01:00
New Revision: e9fe95acf3b9ead924a6f059c8ca8a8aabc55575

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

LOG: [clang][bytecode][NFC] Use maxnum/minnum for fmax/fmin (#129643)

Equivalent of https://github.com/llvm/llvm-project/pull/129630 for the
bytecode interpreter.

Added: 


Modified: 
clang/lib/AST/ByteCode/InterpBuiltin.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index b964906fb6594..df9c2bc24b15f 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -397,21 +397,10 @@ static bool interp__builtin_fmin(InterpState &S, CodePtr 
OpPC,
   const Floating &LHS = getParam(Frame, 0);
   const Floating &RHS = getParam(Frame, 1);
 
-  Floating Result;
-
-  if (IsNumBuiltin) {
-Result = llvm::minimumnum(LHS.getAPFloat(), RHS.getAPFloat());
-  } else {
-// When comparing zeroes, return -0.0 if one of the zeroes is negative.
-if (LHS.isZero() && RHS.isZero() && RHS.isNegative())
-  Result = RHS;
-else if (LHS.isNan() || RHS < LHS)
-  Result = RHS;
-else
-  Result = LHS;
-  }
-
-  S.Stk.push(Result);
+  if (IsNumBuiltin)
+S.Stk.push(llvm::minimumnum(LHS.getAPFloat(), RHS.getAPFloat()));
+  else
+S.Stk.push(minnum(LHS.getAPFloat(), RHS.getAPFloat()));
   return true;
 }
 
@@ -421,21 +410,10 @@ static bool interp__builtin_fmax(InterpState &S, CodePtr 
OpPC,
   const Floating &LHS = getParam(Frame, 0);
   const Floating &RHS = getParam(Frame, 1);
 
-  Floating Result;
-
-  if (IsNumBuiltin) {
-Result = llvm::maximumnum(LHS.getAPFloat(), RHS.getAPFloat());
-  } else {
-// When comparing zeroes, return +0.0 if one of the zeroes is positive.
-if (LHS.isZero() && RHS.isZero() && LHS.isNegative())
-  Result = RHS;
-else if (LHS.isNan() || RHS > LHS)
-  Result = RHS;
-else
-  Result = LHS;
-  }
-
-  S.Stk.push(Result);
+  if (IsNumBuiltin)
+S.Stk.push(llvm::maximumnum(LHS.getAPFloat(), RHS.getAPFloat()));
+  else
+S.Stk.push(maxnum(LHS.getAPFloat(), RHS.getAPFloat()));
   return true;
 }
 



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


[clang] 4dd29eb - [clang][bytecode][NFC] Move incorrect LLVM_PREFERRED_TYPE attribute (#128740)

2025-03-03 Thread via cfe-commits

Author: Timm Baeder
Date: 2025-03-03T19:37:22+01:00
New Revision: 4dd29ebb8dc563be37244612f44537e8eff33c32

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

LOG: [clang][bytecode][NFC] Move incorrect LLVM_PREFERRED_TYPE attribute 
(#128740)

Looks like this was accidentally added after the bitfield and thus
didn't work.

Added: 


Modified: 
clang/lib/AST/ByteCode/Descriptor.h

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Descriptor.h 
b/clang/lib/AST/ByteCode/Descriptor.h
index b2e9f1b6bded4..8ce99731ee0ae 100644
--- a/clang/lib/AST/ByteCode/Descriptor.h
+++ b/clang/lib/AST/ByteCode/Descriptor.h
@@ -95,9 +95,9 @@ struct InlineDescriptor {
   /// Flag indicating if the field is the active member of a union.
   LLVM_PREFERRED_TYPE(bool)
   unsigned IsActive : 1;
-  /// Flat indicating if this field is in a union (even if nested).
-  unsigned InUnion : 1;
+  /// Flag indicating if this field is in a union (even if nested).
   LLVM_PREFERRED_TYPE(bool)
+  unsigned InUnion : 1;
   /// Flag indicating if the field is mutable (if in a record).
   LLVM_PREFERRED_TYPE(bool)
   unsigned IsFieldMutable : 1;



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


[clang] d2c4d1e - [memprof] Export __memprof_default_options_str on Darwin (#128920)

2025-03-03 Thread via cfe-commits

Author: Ellis Hoag
Date: 2025-03-03T09:57:35-08:00
New Revision: d2c4d1ec48b7c723307121164099fb2fa7d959a9

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

LOG: [memprof] Export __memprof_default_options_str on Darwin (#128920)

The `-memprof-runtime-default-options` LLVM flag introduced in
https://github.com/llvm/llvm-project/pull/118874 creates the
`__memprof_default_options_str` symbol with `WeakAnyLinkage` on Darwin.


https://github.com/ellishg/llvm-project/blob/fa0202169af23419c4bcbf66eabd1beb6b6e8e34/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp#L573-L576

This ensures Darwin passes `-exported_symbol
___memprof_default_options_str` to the linker so that the runtime
library has visibility into this symbol.

This will replace the earlier PR
https://github.com/llvm/llvm-project/pull/128615

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/Driver/fmemprof.cpp
llvm/include/llvm/ProfileData/MemProf.h
llvm/lib/Transforms/Instrumentation/MemProfiler.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 75f126965e0ac..e67997314da36 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -21,6 +21,7 @@
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Option/ArgList.h"
 #include "llvm/ProfileData/InstrProf.h"
+#include "llvm/ProfileData/MemProf.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include "llvm/Support/Threading.h"
@@ -1617,6 +1618,12 @@ void DarwinClang::AddLinkRuntimeLibArgs(const ArgList 
&Args,
 }
   }
 
+  if (Sanitize.needsMemProfRt())
+if (hasExportSymbolDirective(Args))
+  addExportedSymbol(
+  CmdArgs,
+  llvm::memprof::getMemprofOptionsSymbolDarwinLinkageName().data());
+
   const XRayArgs &XRay = getXRayArgs();
   if (XRay.needsXRayRt()) {
 AddLinkRuntimeLib(Args, CmdArgs, "xray");

diff  --git a/clang/test/Driver/fmemprof.cpp b/clang/test/Driver/fmemprof.cpp
index 5165c4452fd57..ddf2f851298f2 100644
--- a/clang/test/Driver/fmemprof.cpp
+++ b/clang/test/Driver/fmemprof.cpp
@@ -17,3 +17,10 @@
 
 // RUN: not %clangxx --target=x86_64-linux-gnu -fprofile-generate 
-fmemory-profile-use=foo %s -### 2>&1 | FileCheck %s 
--check-prefix=CONFLICTWITHPGOINSTR
 // CONFLICTWITHPGOINSTR: error: invalid argument '-fmemory-profile-use=foo' 
not allowed with '-fprofile-generate'
+
+// Test that we export the __memprof_default_options_str on Darwin because it 
has WeakAnyLinkage
+// RUN: %clangxx --target=arm64-apple-ios -fmemory-profile %s -### 2>&1 | 
FileCheck %s --check-prefix=EXPORT-BASE --implicit-check-not=exported_symbol
+// RUN: %clangxx --target=arm64-apple-ios -fmemory-profile 
-exported_symbols_list /dev/null %s -### 2>&1 | FileCheck %s 
--check-prefixes=EXPORT-BASE,EXPORT
+// FIXME: Darwin needs to link in the runtime, then we can use the regular 
CHECK prefix
+// EXPORT-BASE: "-cc1" {{.*}} "-fmemory-profile"
+// EXPORT: "-exported_symbol" "___memprof_default_options_str"

diff  --git a/llvm/include/llvm/ProfileData/MemProf.h 
b/llvm/include/llvm/ProfileData/MemProf.h
index da0cb47508e32..71e3faa506741 100644
--- a/llvm/include/llvm/ProfileData/MemProf.h
+++ b/llvm/include/llvm/ProfileData/MemProf.h
@@ -6,6 +6,7 @@
 #include "llvm/ADT/STLForwardCompat.h"
 #include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/IR/GlobalValue.h"
 #include "llvm/ProfileData/MemProfData.inc"
 #include "llvm/Support/BLAKE3.h"
@@ -42,6 +43,16 @@ constexpr uint64_t MaximumSupportedVersion = Version3;
 // Verify that the minimum and maximum satisfy the obvious constraint.
 static_assert(MinimumSupportedVersion <= MaximumSupportedVersion);
 
+inline llvm::StringRef getMemprofOptionsSymbolDarwinLinkageName() {
+  return "___memprof_default_options_str";
+}
+
+inline llvm::StringRef getMemprofOptionsSymbolName() {
+  // Darwin linkage names are prefixed with an extra "_". See
+  // DataLayout::getGlobalPrefix().
+  return getMemprofOptionsSymbolDarwinLinkageName().drop_front();
+}
+
 enum class Meta : uint64_t {
   Start = 0,
 #define MIBEntryDef(NameTag, Name, Type) NameTag,

diff  --git a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp 
b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
index 721f9ff953598..a0a5834731c2e 100644
--- a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
+++ b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
@@ -568,10 +568,9 @@ void createMemprofHistogramFlagVar(Module &M) {
 void createMemprofDefaultOptionsVar(Module &M) {
   Constant *OptionsConst = ConstantDataArray::getString(
   M.getContext(), MemprofRuntimeDefaultOptions, /*AddNull=*/true);
-  GlobalVariable

[clang-tools-extra] 818bca8 - [clang-tidy] [dataflow] Cache reference accessors for `bugprone-unchecked-optional-access` (#128437)

2025-03-03 Thread via cfe-commits

Author: Valentyn Yukhymenko
Date: 2025-02-28T13:27:20-05:00
New Revision: 818bca820ffd3e30fbd3852da0436c24ff15f8a3

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

LOG: [clang-tidy] [dataflow]  Cache reference accessors for 
`bugprone-unchecked-optional-access` (#128437)

Fixes https://github.com/llvm/llvm-project/issues/126283

Extending https://github.com/llvm/llvm-project/pull/112605 to cache
const getters which return references.

Fixes false positives from const reference accessors to object
containing optional member

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index a8d17d19fda1d..07a79d6bbe807 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -112,7 +112,8 @@ Changes in existing checks
   ` fixing false
   positives from smart pointer accessors repeated in checking ``has_value``
   and accessing ``value``. The option `IgnoreSmartPointerDereference` should
-  no longer be needed and will be removed.
+  no longer be needed and will be removed. Also fixing false positive from 
+  const reference accessors to objects containing optional member.
 
 - Improved :doc:`bugprone-unsafe-functions
   ` check to allow specifying

diff  --git 
a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp 
b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
index e1394e28cd49a..9381c5c42e566 100644
--- a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -580,6 +580,22 @@ void handleConstMemberCall(const CallExpr *CE,
 return;
   }
 
+  // Cache if the const method returns a reference
+  if (RecordLoc != nullptr && CE->isGLValue()) {
+const FunctionDecl *DirectCallee = CE->getDirectCallee();
+if (DirectCallee == nullptr)
+  return;
+
+StorageLocation &Loc =
+State.Lattice.getOrCreateConstMethodReturnStorageLocation(
+*RecordLoc, DirectCallee, State.Env, [&](StorageLocation &Loc) {
+  // no-op
+});
+
+State.Env.setStorageLocation(*CE, Loc);
+return;
+  }
+
   // Cache if the const method returns a boolean or pointer type.
   // We may decide to cache other return types in the future.
   if (RecordLoc != nullptr &&

diff  --git 
a/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
index 19c3ff49eab27..5031e17188e17 100644
--- 
a/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ 
b/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -3863,6 +3863,200 @@ TEST_P(UncheckedOptionalAccessTest, 
ConstBoolAccessorWithModInBetween) {
   )cc");
 }
 
+TEST_P(UncheckedOptionalAccessTest,
+   ConstRefAccessorToOptionalViaConstRefAccessorToHoldingObject) {
+  ExpectDiagnosticsFor(R"cc(
+#include "unchecked_optional_access_test.h"
+
+struct A {
+  const $ns::$optional& get() const { return x; }
+  
+  $ns::$optional x;
+};
+
+struct B {
+  const A& getA() const { return a; }
+
+  A a;
+};
+
+void target(B& b) {
+  if (b.getA().get().has_value()) {
+b.getA().get().value();
+  }
+}
+  )cc");
+}
+
+TEST_P(
+UncheckedOptionalAccessTest,
+
ConstRefAccessorToOptionalViaConstRefAccessorToHoldingObjectWithoutValueCheck) {
+  ExpectDiagnosticsFor(R"cc(
+#include "unchecked_optional_access_test.h"
+
+struct A {
+  const $ns::$optional& get() const { return x; }
+  
+  $ns::$optional x;
+};
+
+struct B {
+  const A& getA() const { return a; }
+
+  A a;
+};
+
+void target(B& b) {
+  b.getA().get().value(); // [[unsafe]]
+}
+  )cc");
+}
+
+TEST_P(UncheckedOptionalAccessTest,
+   ConstRefToOptionalSavedAsTemporaryVariable) {
+  ExpectDiagnosticsFor(R"cc(
+#include "unchecked_optional_access_test.h"
+
+struct A {
+  const $ns::$optional& get() const { return x; }
+  
+  $ns::$optional x;
+};
+
+struct B {
+  const A& getA() const { return a; }
+
+  A a;
+};
+
+void target(B& b) {
+  const auto& opt = b.getA().get();
+  if (opt.has_value()) {
+opt.value();
+  }
+}
+  )cc");
+}
+
+TEST_P(UncheckedOptionalAccessTest,
+   ConstRefAccessorToOptionalViaAccessorToHoldingObjectByValue) {
+  ExpectDiagnosticsFor(R"

[clang] 1c4e0f6 - [clang] Add #pragma clang __debug module_lookup (#129158)

2025-03-03 Thread via cfe-commits

Author: Michael Spencer
Date: 2025-03-03T13:28:10-08:00
New Revision: 1c4e0f6a54538972741ab1c7a5fcc5e5efd3d90c

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

LOG: [clang] Add #pragma clang __debug module_lookup (#129158)

This can be used to trigger implicit module map lookup without also
importing the module. This can be useful for debugging as it avoids
loading the module map from the AST file, which has slightly different
semantics.

Added: 
clang/test/Modules/clang-pragmas.c

Modified: 
clang/include/clang/Basic/DiagnosticLexKinds.td
clang/lib/Lex/Pragma.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticLexKinds.td 
b/clang/include/clang/Basic/DiagnosticLexKinds.td
index 8daf3602450f0..0e5592d65669b 100644
--- a/clang/include/clang/Basic/DiagnosticLexKinds.td
+++ b/clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -718,6 +718,8 @@ def warn_pragma_debug_unexpected_command : Warning<
   "unexpected debug command '%0'">, InGroup;
 def warn_pragma_debug_unknown_module : Warning<
   "unknown module '%0'">, InGroup;
+def warn_pragma_debug_unable_to_find_module : Warning<
+  "unable to find module '%0'">, InGroup;
 // #pragma module
 def err_pp_expected_module_name : Error<
   "expected %select{identifier after '.' in |}0module name">;

diff  --git a/clang/lib/Lex/Pragma.cpp b/clang/lib/Lex/Pragma.cpp
index e339ca8422278..91c1619e35623 100644
--- a/clang/lib/Lex/Pragma.cpp
+++ b/clang/lib/Lex/Pragma.cpp
@@ -1119,11 +1119,27 @@ struct PragmaDebugHandler : public PragmaHandler {
 M = MM.lookupModuleQualified(IIAndLoc.first->getName(), M);
 if (!M) {
   PP.Diag(IIAndLoc.second, diag::warn_pragma_debug_unknown_module)
-  << IIAndLoc.first;
+  << IIAndLoc.first->getName();
   return;
 }
   }
   M->dump();
+} else if (II->isStr("module_lookup")) {
+  Token MName;
+  PP.LexUnexpandedToken(MName);
+  auto *MNameII = MName.getIdentifierInfo();
+  if (!MNameII) {
+PP.Diag(MName, diag::warn_pragma_debug_missing_argument)
+<< II->getName();
+return;
+  }
+  Module *M = PP.getHeaderSearchInfo().lookupModule(MNameII->getName());
+  if (!M) {
+PP.Diag(MName, diag::warn_pragma_debug_unable_to_find_module)
+<< MNameII->getName();
+return;
+  }
+  M->dump();
 } else if (II->isStr("overflow_stack")) {
   if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
 DebugOverflowStack();

diff  --git a/clang/test/Modules/clang-pragmas.c 
b/clang/test/Modules/clang-pragmas.c
new file mode 100644
index 0..22ead7279f84f
--- /dev/null
+++ b/clang/test/Modules/clang-pragmas.c
@@ -0,0 +1,22 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -I%t %t/tu.c -fsyntax-only 
\
+// RUN:   -verify 2>&1 | FileCheck %s
+
+//--- module.modulemap
+
+module A {
+  header "A.h"
+}
+
+//--- A.h
+
+//--- tu.c
+
+#pragma clang __debug module_map A // expected-warning{{unknown module 'A'}}
+#pragma clang __debug module_lookup B // expected-warning{{unable to find 
module 'B'}}
+#pragma clang __debug module_lookup A // does header search for A
+#pragma clang __debug module_map A // now finds module A
+
+// CHECK: module A
+// CHECK: module A



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