[clang] fa20184 - [C++20] [Modules] [Serialization] Don't reuse type ID and identifier ID from imported modules

2024-06-25 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2024-06-25T15:04:32+08:00
New Revision: fa20184a8f336e4154f2ffeeeb8a538dc9462d9a

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

LOG: [C++20] [Modules] [Serialization] Don't reuse type ID and identifier ID 
from imported modules

To support no-transitive-change model for named modules, we can't reuse
type ID and identifier ID from imported modules arbitrarily. Since the
theory for no-transitive-change model is,
for a user of a named module, the user can only access the
indirectly imported decls via the directly imported module. So that it is
possible to control what matters to the users when writing the module.

And it will be unsafe to do so if the users can reuse the type IDs and
identifier IDs from the indirectly imported modules not via the directly
imported modules.

So in this patch, we don't reuse the type ID and identifier ID in the
AST writer to avoid the problematic case.

Added: 
clang/test/Modules/no-external-identifier-id.cppm
clang/test/Modules/no-external-type-id.cppm

Modified: 
clang/lib/Serialization/ASTWriter.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 5b39055cf9f27..9c55960b14cba 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -5355,6 +5355,20 @@ ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, 
StringRef isysroot,
 
   writeUnhashedControlBlock(PP, Context);
 
+  // Don't reuse type ID and Identifier ID from readers for C++ standard named
+  // modules since we want to support no-transitive-change model for named
+  // modules. The theory for no-transitive-change model is,
+  // for a user of a named module, the user can only access the indirectly
+  // imported decls via the directly imported module. So that it is possible to
+  // control what matters to the users when writing the module. It would be
+  // problematic if the users can reuse the type IDs and identifier IDs from
+  // indirectly imported modules arbitrarily. So we choose to clear these ID
+  // here.
+  if (isWritingStdCXXNamedModules()) {
+TypeIdxs.clear();
+IdentifierIDs.clear();
+  }
+
   // Look for any identifiers that were named while processing the
   // headers, but are otherwise not needed. We add these to the hash
   // table to enable checking of the predefines buffer in the case
@@ -6686,6 +6700,11 @@ void ASTWriter::ReaderInitialized(ASTReader *Reader) {
 }
 
 void ASTWriter::IdentifierRead(IdentifierID ID, IdentifierInfo *II) {
+  // Don't reuse Type ID from external modules for named modules. See the
+  // comments in WriteASTCore for details.
+  if (isWritingStdCXXNamedModules())
+return;
+
   IdentifierID &StoredID = IdentifierIDs[II];
   unsigned OriginalModuleFileIndex = StoredID >> 32;
 
@@ -6708,6 +6727,11 @@ void ASTWriter::MacroRead(serialization::MacroID ID, 
MacroInfo *MI) {
 }
 
 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
+  // Don't reuse Type ID from external modules for named modules. See the
+  // comments in WriteASTCore for details.
+  if (isWritingStdCXXNamedModules())
+return;
+
   // Always take the type index that comes in later module files.
   // This copes with an interesting
   // case for chained AST writing where we schedule writing the type and then,

diff  --git a/clang/test/Modules/no-external-identifier-id.cppm 
b/clang/test/Modules/no-external-identifier-id.cppm
new file mode 100644
index 0..25825ef67ad91
--- /dev/null
+++ b/clang/test/Modules/no-external-identifier-id.cppm
@@ -0,0 +1,37 @@
+// Testing that we won't record the identifier ID from external modules.
+//
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: cd %t
+//
+// RUN: %clang_cc1 -std=c++20 %t/a.cppm -emit-module-interface -o %t/a.pcm
+// RUN: %clang_cc1 -std=c++20 %t/b.cppm -emit-module-interface -o %t/b.pcm \
+// RUN: -fmodule-file=a=%t/a.pcm
+// RUN: llvm-bcanalyzer --dump --disable-histogram %t/b.pcm | FileCheck 
%t/b.cppm
+//
+// RUN: %clang_cc1 -std=c++20 %t/a.v1.cppm -emit-module-interface -o 
%t/a.v1.pcm
+// RUN: %clang_cc1 -std=c++20 %t/b.cppm -emit-module-interface -o %t/b.v1.pcm \
+// RUN: -fmodule-file=a=%t/a.v1.pcm
+// RUN: 
diff  %t/b.pcm %t/b.v1.pcm &> /dev/null
+
+//--- a.cppm
+export module a;
+export inline int a() {
+int foo = 43;
+return foo;
+}
+
+//--- b.cppm
+export module b;
+import a;
+export inline int b() {
+int foo = 43;
+return foo;
+}
+
+// CHECK:  /dev/null
+
+//--- a.cppm
+export module a;
+export int a();
+
+//--- b.cppm
+export module b;
+import a;
+export int b();
+
+// CHECK: https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8153773 - [clang][Interp] Fix returning primitive non-blockpointers

2024-06-25 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-06-25T09:09:49+02:00
New Revision: 8153773b23032177546944ec2524dce131b8a46e

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

LOG: [clang][Interp] Fix returning primitive non-blockpointers

We can't deref() them, so return false here.

Added: 


Modified: 
clang/lib/AST/Interp/Pointer.cpp
clang/test/AST/Interp/literals.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Pointer.cpp 
b/clang/lib/AST/Interp/Pointer.cpp
index d77cd8943c496..4070d0c54225d 100644
--- a/clang/lib/AST/Interp/Pointer.cpp
+++ b/clang/lib/AST/Interp/Pointer.cpp
@@ -347,7 +347,7 @@ std::optional Pointer::toRValue(const Context 
&Ctx) const {
   Ty = AT->getValueType();
 
 // Invalid pointers.
-if (Ptr.isDummy() || !Ptr.isLive() ||
+if (Ptr.isDummy() || !Ptr.isLive() || !Ptr.isBlockPointer() ||
 (!Ptr.isUnknownSizeArray() && Ptr.isOnePastEnd()))
   return false;
 

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index 5a29013a053a2..ef98b4947e64f 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -45,6 +45,8 @@ constexpr int Failed2 = Failed1 + 1; // both-error {{must be 
initialized by a co
 static_assert(Failed2 == 0, ""); // both-error {{not an integral constant 
expression}} \
  // both-note {{initializer of 'Failed2' is 
not a constant expression}}
 
+const int x = *(volatile int*)0x1234;
+
 namespace ScalarTypes {
   constexpr int ScalarInitInt = int();
   static_assert(ScalarInitInt == 0, "");



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


[clang] [clang] Allow class with anonymous union member to be const-default-constructible even if a union member has a default member initializer (#95854) (PR #96301)

2024-06-25 Thread Rajveer Singh Bharadwaj via cfe-commits


@@ -1392,7 +1392,8 @@ class CXXRecordDecl : public RecordDecl {
   bool allowConstDefaultInit() const {
 return !data().HasUninitializedFields ||
!(data().HasDefaultedDefaultConstructor ||
- needsImplicitDefaultConstructor());
+ needsImplicitDefaultConstructor()) ||
+   hasInClassInitializer();

Rajveer100 wrote:

@zygoloid 
Is there an existing method for checking nested structures for cases like you 
mentioned above?

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


[clang] [compiler-rt] [llvm] [CMake] Use Clang to infer the target triple (PR #89425)

2024-06-25 Thread Petr Hosek via cfe-commits

https://github.com/petrhosek updated 
https://github.com/llvm/llvm-project/pull/89425

>From eb2459876526b78c97b04801dd07bd53540b2892 Mon Sep 17 00:00:00 2001
From: Petr Hosek 
Date: Tue, 15 Feb 2022 22:59:58 -0800
Subject: [PATCH 1/2] [CMake] Use Clang to infer the target triple

When using Clang as a compiler, use Clang to normalize the triple that's
used to construct path for runtime library build and install paths. This
ensures that paths are consistent and avoids the issue where the build
uses a different triple spelling.

Differential Revision: https://reviews.llvm.org/D140925
---
 clang/cmake/caches/Fuchsia-stage2.cmake |  2 +-
 compiler-rt/lib/builtins/CMakeLists.txt | 13 +
 runtimes/CMakeLists.txt | 14 ++
 3 files changed, 28 insertions(+), 1 deletion(-)

diff --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index d5546e20873b3..029c069997396 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -142,7 +142,7 @@ if(WIN32 OR LLVM_WINSYSROOT)
   set(RUNTIMES_${target}_CMAKE_MODULE_LINKER_FLAGS ${WINDOWS_LINK_FLAGS} CACHE 
STRING "")
 endif()
 
-foreach(target 
aarch64-unknown-linux-gnu;armv7-unknown-linux-gnueabihf;i386-unknown-linux-gnu;riscv64-unknown-linux-gnu;x86_64-unknown-linux-gnu)
+foreach(target 
aarch64-linux-gnu;armv7-linux-gnueabihf;i386-linux-gnu;riscv64-linux-gnu;x86_64-linux-gnu)
   if(LINUX_${target}_SYSROOT)
 # Set the per-target builtins options.
 list(APPEND BUILTIN_TARGETS "${target}")
diff --git a/compiler-rt/lib/builtins/CMakeLists.txt 
b/compiler-rt/lib/builtins/CMakeLists.txt
index f9611574a562b..4c6de992204c1 100644
--- a/compiler-rt/lib/builtins/CMakeLists.txt
+++ b/compiler-rt/lib/builtins/CMakeLists.txt
@@ -28,6 +28,19 @@ if (CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
   if (NOT LLVM_RUNTIMES_BUILD)
 load_llvm_config()
   endif()
+  if(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR AND NOT APPLE)
+set(print_target_triple ${CMAKE_CXX_COMPILER} 
--target=${LLVM_RUNTIME_TRIPLE} -print-target-triple)
+execute_process(COMMAND ${print_target_triple}
+  RESULT_VARIABLE result
+  OUTPUT_VARIABLE output
+  OUTPUT_STRIP_TRAILING_WHITESPACE)
+if(result EQUAL 0)
+  set(LLVM_RUNTIME_TRIPLE ${output})
+else()
+  string(REPLACE ";" " " print_target_triple "${print_target_triple}")
+  message(WARNING "Failed to execute `${print_target_triple}` to normalize 
target triple.")
+endif()
+  endif()
   construct_compiler_rt_default_triple()
 
   include(SetPlatformToolchainTools)
diff --git a/runtimes/CMakeLists.txt b/runtimes/CMakeLists.txt
index 6f24fbcccec95..bb1f544706f2b 100644
--- a/runtimes/CMakeLists.txt
+++ b/runtimes/CMakeLists.txt
@@ -181,6 +181,20 @@ message(STATUS "LLVM default target triple: 
${LLVM_DEFAULT_TARGET_TRIPLE}")
 
 set(LLVM_TARGET_TRIPLE "${LLVM_DEFAULT_TARGET_TRIPLE}")
 
+if(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR AND NOT APPLE)
+  set(print_target_triple ${CMAKE_CXX_COMPILER} 
--target=${LLVM_RUNTIME_TRIPLE} -print-target-triple)
+  execute_process(COMMAND ${print_target_triple}
+RESULT_VARIABLE result
+OUTPUT_VARIABLE output
+OUTPUT_STRIP_TRAILING_WHITESPACE)
+  if(result EQUAL 0)
+set(LLVM_RUNTIME_TRIPLE ${output})
+  else()
+string(REPLACE ";" " " print_target_triple "${print_target_triple}")
+message(WARNING "Failed to execute `${print_target_triple}` to normalize 
target triple.")
+  endif()
+endif()
+
 option(LLVM_INCLUDE_TESTS "Generate build targets for the runtimes unit 
tests." ON)
 option(LLVM_INCLUDE_DOCS "Generate build targets for the runtimes 
documentation." ON)
 option(LLVM_ENABLE_SPHINX "Use Sphinx to generate the runtimes documentation." 
OFF)

>From 302fa322f445a40a299c2ff37bf215fb3d4754fd Mon Sep 17 00:00:00 2001
From: Petr Hosek 
Date: Tue, 25 Jun 2024 07:48:03 +
Subject: [PATCH 2/2] Update the patch to incorporate changes from #89234

---
 compiler-rt/cmake/Modules/CompilerRTUtils.cmake | 16 
 compiler-rt/lib/builtins/CMakeLists.txt | 13 -
 runtimes/CMakeLists.txt | 10 +++---
 3 files changed, 19 insertions(+), 20 deletions(-)

diff --git a/compiler-rt/cmake/Modules/CompilerRTUtils.cmake 
b/compiler-rt/cmake/Modules/CompilerRTUtils.cmake
index 9c7fe64d0bd35..b77b376b95f05 100644
--- a/compiler-rt/cmake/Modules/CompilerRTUtils.cmake
+++ b/compiler-rt/cmake/Modules/CompilerRTUtils.cmake
@@ -368,14 +368,22 @@ macro(construct_compiler_rt_default_triple)
   "Default triple for which compiler-rt runtimes will be built.")
   endif()
 
-  if ("${CMAKE_C_COMPILER_ID}" MATCHES "Clang")
+  if(CMAKE_C_COMPILER_ID MATCHES "Clang")
 set(option_prefix "")
 if (CMAKE_C_SIMULATE_ID MATCHES "MSVC")
   set(option_prefix "/clang:")
 endif()
-execute_process(COMMAND ${CMAKE_C_COMPILER} 
${option_prefix}--target=${COMPILER_RT_DEFAULT_TARGET_TRIPLE} 
${option_prefix}-print

[clang] [compiler-rt] [llvm] [CMake] Use Clang to infer the target triple (PR #89425)

2024-06-25 Thread Petr Hosek via cfe-commits


@@ -181,6 +181,20 @@ message(STATUS "LLVM default target triple: 
${LLVM_DEFAULT_TARGET_TRIPLE}")
 
 set(LLVM_TARGET_TRIPLE "${LLVM_DEFAULT_TARGET_TRIPLE}")
 
+if(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR AND NOT APPLE)
+  set(print_target_triple ${CMAKE_CXX_COMPILER} 
--target=${LLVM_RUNTIME_TRIPLE} -print-target-triple)
+  execute_process(COMMAND ${print_target_triple}
+RESULT_VARIABLE result
+OUTPUT_VARIABLE output
+OUTPUT_STRIP_TRAILING_WHITESPACE)
+  if(result EQUAL 0)
+set(LLVM_RUNTIME_TRIPLE ${output})

petrhosek wrote:

Thanks for catching this, it was replaced by `LLVM_DEFAULT_TARGET_TRIPLE`.

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


[clang] [compiler-rt] [llvm] [CMake] Use Clang to infer the target triple (PR #89425)

2024-06-25 Thread Petr Hosek via cfe-commits


@@ -28,6 +28,19 @@ if (CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
   if (NOT LLVM_RUNTIMES_BUILD)
 load_llvm_config()
   endif()
+  if(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR AND NOT APPLE)

petrhosek wrote:

I have updated the block in `compiler-rt/cmake/Modules/CompilerRTUtils.cmake` 
and removed this version which is no longer needed.

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


[clang] [compiler-rt] [llvm] [CMake] Use Clang to infer the target triple (PR #89425)

2024-06-25 Thread Petr Hosek via cfe-commits

petrhosek wrote:

> Does it really needed?

It is, #89234 only covers compiler-rt but not other runtime libraries such as 
libc or libc++ so you might end up with the following:

```
lib/19/clang/lib/x86_64-unknown-linux-gnu/libclang_rt.builtins.a
lib/x86_64-linux-gnu/libc++.a
```

The driver will then fail to fine `libc++.a` leading to a link failure.

This change expand the normalization to cover all runtime libraries.

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


[clang] [clang] Allow class with anonymous union member to be const-default-constructible even if a union member has a default member initializer (#95854) (PR #96301)

2024-06-25 Thread Rajveer Singh Bharadwaj via cfe-commits

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


[clang] [clang][CGRecordLayout] Remove dependency on isZeroSize (PR #96422)

2024-06-25 Thread Michael Buch via cfe-commits

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


[clang] [clang][CGRecordLayout] Remove dependency on isZeroSize (PR #96422)

2024-06-25 Thread Michael Buch via cfe-commits

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


[clang] [clang][CGRecordLayout] Remove dependency on isZeroSize (PR #96422)

2024-06-25 Thread Michael Buch via cfe-commits

Michael137 wrote:

> (Please move out of "draft" when you think this is ready.)

Updated the PR with some more context. There's still a few instances of 
`FieldDecl::isZeroSize`/`CXXRecordDecl::isEmpty` around `CodeGen` (see 
`CGClass`, `CGExprConstant`), but it wasn't obvious to me whether those needed 
replacing as well. Particularly `ConstStructBuilder::Build` has 
`[[no_unique_address]]` specific logic.

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


[clang] [clang][CGRecordLayout] Remove dependency on isZeroSize (PR #96422)

2024-06-25 Thread Michael Buch via cfe-commits

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


[clang] [clang][CGRecordLayout] Remove dependency on isZeroSize (PR #96422)

2024-06-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Michael Buch (Michael137)


Changes

This is a follow-up from the conversation starting at 
https://github.com/llvm/llvm-project/pull/93809#issuecomment-2173729801

The root problem that motivated the change are external AST sources that 
compute `ASTRecordLayout`s themselves instead of letting Clang compute them 
from the AST. One such example is LLDB using DWARF to get the definitive 
offsets and sizes of C++ structures. Such layouts should be considered correct 
(modulo buggy DWARF), but various assertions and lowering logic around the 
`CGRecordLayoutBuilder` relies on the AST having `[[no_unique_address]]` 
attached to them. This is a layout-altering attribute which is not encoded in 
DWARF. This causes us LLDB to trip over the various LLVM<->Clang layout 
consistency checks. There has been precedent for avoiding such layout-altering 
attributes from affecting lowering with externally-provided layouts (e.g., 
packed structs).

This patch proposes to replace the `isZeroSize` checks in 
`CGRecordLayoutBuilder` (which roughly means "empty field with 
[[no_unique_address]]") with checks for 
`CodeGen::isEmptyField`/`CodeGen::isEmptyRecord`.

**Details**
The main strategy here was to change the `isZeroSize` check in 
`CGRecordLowering::accumulateFields` and `CGRecordLowering::accumulateBases` to 
use the `isEmptyXXX` APIs instead, preventing empty fields from being added to 
the `Members` and `Bases` structures. The rest of the changes fall out from 
here, to prevent lookups into these structures (for field numbers or base 
indices) from failing.

Added `isEmptyRecordForLayout` and `isEmptyFieldForLayout` (open to better 
naming suggestions), which mostly just dispatch to the 
`isEmptyRecord`/`isEmptyField` respectively. The main difference is that 
`isEmptyFieldForLayout` doesn't treat `unnamed bitfields` as unconditionally 
empty (unlike `isEmptyField`).

---

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


26 Files Affected:

- (modified) clang/lib/CodeGen/ABIInfoImpl.cpp (+20-3) 
- (modified) clang/lib/CodeGen/ABIInfoImpl.h (+12-3) 
- (modified) clang/lib/CodeGen/CGExpr.cpp (+2-1) 
- (modified) clang/lib/CodeGen/CGExprConstant.cpp (+6-3) 
- (modified) clang/lib/CodeGen/CGRecordLayoutBuilder.cpp (+8-7) 
- (modified) clang/test/CodeGen/X86/x86_64-vaarg.c (+2-1) 
- (modified) clang/test/CodeGen/debug-info-packed-struct.c (+1-1) 
- (modified) clang/test/CodeGen/paren-list-agg-init.cpp (+6-9) 
- (modified) clang/test/CodeGen/voidptr-vaarg.c (+2-1) 
- (modified) clang/test/CodeGenCXX/2011-12-19-init-list-ctor.cpp (+3-3) 
- (modified) clang/test/CodeGenCXX/auto-var-init.cpp (+9-6) 
- (modified) clang/test/CodeGenCXX/bitfield-access-empty.cpp (+8-8) 
- (modified) clang/test/CodeGenCXX/class-layout.cpp (+1-1) 
- (modified) clang/test/CodeGenCXX/compound-literals.cpp (+1-1) 
- (modified) clang/test/CodeGenCXX/exceptions.cpp (+3-4) 
- (modified) clang/test/CodeGenCXX/lambda-deterministic-captures.cpp (+1-3) 
- (modified) clang/test/CodeGenCXX/ms_struct.cpp (+1-3) 
- (modified) clang/test/CodeGenCXX/partial-destruction.cpp (+4-7) 
- (modified) clang/test/CodeGenCXX/pr18962.cpp (+2-3) 
- (modified) clang/test/CodeGenCXX/references.cpp (+1-3) 
- (modified) clang/test/CodeGenCXX/temporaries.cpp (+6-6) 
- (modified) clang/test/CodeGenObjCXX/lambda-to-block.mm (+4-5) 
- (modified) clang/test/OpenMP/irbuilder_for_iterator.cpp (+4-6) 
- (modified) clang/test/OpenMP/irbuilder_for_rangefor.cpp (+6-8) 
- (modified) clang/test/OpenMP/task_member_call_codegen.cpp (+9-13) 
- (modified) clang/test/Sema/ms_class_layout.cpp (+2-12) 


``diff
diff --git a/clang/lib/CodeGen/ABIInfoImpl.cpp 
b/clang/lib/CodeGen/ABIInfoImpl.cpp
index e9a26abb77837..703e69e889967 100644
--- a/clang/lib/CodeGen/ABIInfoImpl.cpp
+++ b/clang/lib/CodeGen/ABIInfoImpl.cpp
@@ -248,7 +248,7 @@ Address CodeGen::emitMergePHI(CodeGenFunction &CGF, Address 
Addr1,
   return Address(PHI, Addr1.getElementType(), Align);
 }
 
-bool CodeGen::isEmptyField(ASTContext &Context, const FieldDecl *FD,
+bool CodeGen::isEmptyField(const ASTContext &Context, const FieldDecl *FD,
bool AllowArrays, bool AsIfNoUniqueAddr) {
   if (FD->isUnnamedBitField())
 return true;
@@ -289,8 +289,20 @@ bool CodeGen::isEmptyField(ASTContext &Context, const 
FieldDecl *FD,
   return isEmptyRecord(Context, FT, AllowArrays, AsIfNoUniqueAddr);
 }
 
-bool CodeGen::isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays,
-bool AsIfNoUniqueAddr) {
+bool CodeGen::isEmptyFieldForLayout(const ASTContext &Context,
+const FieldDecl *FD) {
+  if (FD->isZeroLengthBitField(Context))
+return true;
+
+  if (FD->isUnnamedBitField())
+return false;
+
+  return isEmptyField(Context, FD, /*AllowArrays=*/false,
+  /*AsIfNoUniqueAddr=*/true);
+}

[clang] [llvm] [Clang][ARM][AArch64] Alway emit protection attributes for functions. (PR #82819)

2024-06-25 Thread Daniel Kiss via cfe-commits

DanielKristofKiss wrote:

> For return-address signing, each function can make its own choice about 
> whether to sign; the function that's doing the signing is the same function 
> that does the auth, so it doesn't directly impact any other function. For 
> branch target enforcement, though, everything needs to agree that branch 
> targets are supposed to be enforced, or else the process crashes. So there's 
> no point to modifying whether it's enabled for a single function.

You are right in case of user space application but in some other use cases it 
is desired to keep the function properties because the executable is loaded 
differently (higher EL's).



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


[clang] [Clang] Remove preprocessor guards and global feature checks for NEON (PR #95224)

2024-06-25 Thread via cfe-commits

https://github.com/Lukacma updated 
https://github.com/llvm/llvm-project/pull/95224

>From d5caa1a22c90c7d3b1fd995c3ae980f02e4c14c9 Mon Sep 17 00:00:00 2001
From: Marian Lukac 
Date: Wed, 12 Jun 2024 11:13:48 +
Subject: [PATCH 1/6] fix for mve

---
 clang/lib/Sema/SemaType.cpp| 18 --
 clang/test/Sema/arm-vector-types-support.c | 11 ++-
 clang/test/SemaCUDA/neon-attrs.cu  | 22 --
 clang/utils/TableGen/NeonEmitter.cpp   |  5 -
 4 files changed, 14 insertions(+), 42 deletions(-)
 delete mode 100644 clang/test/SemaCUDA/neon-attrs.cu

diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 441fdcca0758f..9c0d043725dde 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -8086,23 +8086,21 @@ static void HandleNeonVectorTypeAttr(QualType &CurType, 
const ParsedAttr &Attr,
 
   // Target must have NEON (or MVE, whose vectors are similar enough
   // not to need a separate attribute)
-  if (!(S.Context.getTargetInfo().hasFeature("neon") ||
-S.Context.getTargetInfo().hasFeature("mve") ||
-S.Context.getTargetInfo().hasFeature("sve") ||
-S.Context.getTargetInfo().hasFeature("sme") ||
+  if (!(S.Context.getTargetInfo().hasFeature("mve") ||
 IsTargetCUDAAndHostARM) &&
-  VecKind == VectorKind::Neon) {
+  VecKind == VectorKind::Neon && 
+  S.Context.getTargetInfo().getTriple().isArmMClass()) {
 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
-<< Attr << "'neon', 'mve', 'sve' or 'sme'";
+<< Attr << "'mve'";
 Attr.setInvalid();
 return;
   }
-  if (!(S.Context.getTargetInfo().hasFeature("neon") ||
-S.Context.getTargetInfo().hasFeature("mve") ||
+  if (!(S.Context.getTargetInfo().hasFeature("mve") ||
 IsTargetCUDAAndHostARM) &&
-  VecKind == VectorKind::NeonPoly) {
+  VecKind == VectorKind::NeonPoly &&
+  S.Context.getTargetInfo().getTriple().isArmMClass()) {
 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
-<< Attr << "'neon' or 'mve'";
+<< Attr << "'mve'";
 Attr.setInvalid();
 return;
   }
diff --git a/clang/test/Sema/arm-vector-types-support.c 
b/clang/test/Sema/arm-vector-types-support.c
index ed5f5ba175a94..e648d791a2687 100644
--- a/clang/test/Sema/arm-vector-types-support.c
+++ b/clang/test/Sema/arm-vector-types-support.c
@@ -1,7 +1,8 @@
-// RUN: %clang_cc1 %s -triple armv7 -fsyntax-only -verify
-// RUN: %clang_cc1 %s -triple aarch64 -fsyntax-only -verify
-// RUN: %clang_cc1 %s -triple aarch64 -target-feature -fp-armv8 -target-abi 
aapcs-soft -fsyntax-only -verify
+// RUN: %clang_cc1 %s -triple armv8.1m.main -fsyntax-only -verify
+// RUN: %clang_cc1 %s -triple aarch64 -fsyntax-only -verify=sve-type
+// RUN: %clang_cc1 %s -triple aarch64 -target-feature -fp-armv8 -target-abi 
aapcs-soft -fsyntax-only -verify=sve-type
 
-typedef __attribute__((neon_vector_type(2))) int int32x2_t; // 
expected-error{{'neon_vector_type' attribute is not supported on targets 
missing 'neon', 'mve', 'sve' or 'sme'; specify an appropriate -march= or 
-mcpu=}}
-typedef __attribute__((neon_polyvector_type(16))) short poly8x16_t; // 
expected-error{{'neon_polyvector_type' attribute is not supported on targets 
missing 'neon' or 'mve'; specify an appropriate -march= or -mcpu=}}
+typedef __attribute__((neon_vector_type(2))) int int32x2_t; // 
expected-error{{'neon_vector_type' attribute is not supported on targets 
missing 'mve'; specify an appropriate -march= or -mcpu=}}
+typedef __attribute__((neon_polyvector_type(16))) unsigned char poly8x16_t; // 
expected-error{{'neon_polyvector_type' attribute is not supported on targets 
missing 'mve'; specify an appropriate -march= or -mcpu=}}
 typedef __attribute__((arm_sve_vector_bits(256))) void nosveflag; // 
expected-error{{'arm_sve_vector_bits' attribute is not supported on targets 
missing 'sve'; specify an appropriate -march= or -mcpu=}}
+  // 
sve-type-error@-1{{'arm_sve_vector_bits' attribute is not supported on targets 
missing 'sve'; specify an appropriate -march= or -mcpu=}}
diff --git a/clang/test/SemaCUDA/neon-attrs.cu 
b/clang/test/SemaCUDA/neon-attrs.cu
deleted file mode 100644
index 129056741ac9a..0
--- a/clang/test/SemaCUDA/neon-attrs.cu
+++ /dev/null
@@ -1,22 +0,0 @@
-// CPU-side compilation on ARM with neon enabled (no errors expected).
-// RUN: %clang_cc1 -triple arm64-linux-gnu -target-feature +neon -aux-triple 
nvptx64 -x cuda -fsyntax-only -verify=quiet %s
-
-// CPU-side compilation on ARM with neon disabled.
-// RUN: %clang_cc1 -triple arm64-linux-gnu -target-feature -neon -aux-triple 
nvptx64 -x cuda -fsyntax-only -verify %s
-
-// GPU-side compilation on ARM (no errors expected).
-// RUN: %clang_cc1 -triple nvptx64 -aux-triple arm64-linux-gnu 
-fcuda-is-device -x cuda -fsyntax-only -verify=quiet %s
-
-// Regular C++ compilation on ARM with

[clang] [llvm] [AMDGPU] Extend readlane, writelane and readfirstlane intrinsic lowering for generic types (PR #89217)

2024-06-25 Thread Vikram Hegde via cfe-commits

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


[clang] f09b024 - [clang] Remove a stale FIXME

2024-06-25 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2024-06-25T11:45:25+02:00
New Revision: f09b02484b865e4e6e2243ee2ff59d70b60d28e4

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

LOG: [clang] Remove a stale FIXME

This FIXME has already been addressed in #89358

Added: 


Modified: 
clang/lib/Sema/SemaTemplate.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index a032e3ec6f635..e36ee2d5a46cf 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -3170,10 +3170,6 @@ BuildDeductionGuideForTypeAlias(Sema &SemaRef,
 Expr *RequiresClause = buildAssociatedConstraints(
 SemaRef, F, AliasTemplate, DeduceResults, IsDeducible);
 
-// FIXME: implement the is_deducible constraint per C++
-// [over.match.class.deduct]p3.3:
-//... and a constraint that is satisfied if and only if the arguments
-//of A are deducible (see below) from the return type.
 auto *FPrimeTemplateParamList = TemplateParameterList::Create(
 Context, AliasTemplate->getTemplateParameters()->getTemplateLoc(),
 AliasTemplate->getTemplateParameters()->getLAngleLoc(),



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


[clang] [Clang] Extend lifetime bound analysis to support assignments (PR #96475)

2024-06-25 Thread Gábor Horváth via cfe-commits

Xazax-hun wrote:

+1, I like Ilya's suggestion. 

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


[clang] [clang][nullability] Improve modeling of `++`/`--` operators. (PR #96601)

2024-06-25 Thread Gábor Horváth via cfe-commits

https://github.com/Xazax-hun approved this pull request.


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


[clang] [clang] Emit bad shift warnings (PR #70307)

2024-06-25 Thread Budimir Aranđelović via cfe-commits

https://github.com/budimirarandjelovicsyrmia updated 
https://github.com/llvm/llvm-project/pull/70307

From 975000d3a8bfff223111bc5c119294d6fea929ae Mon Sep 17 00:00:00 2001
From: budimirarandjelovicsyrmia 
Date: Thu, 26 Oct 2023 10:39:52 +0200
Subject: [PATCH] [clang] Emit bad shift warnings

---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/lib/AST/ExprConstant.cpp |  7 ++
 clang/lib/Sema/SemaExpr.cpp| 35 +++---
 clang/test/C/drs/dr0xx.c   |  3 ++-
 clang/test/C/drs/dr2xx.c   |  4 ++-
 clang/test/Sema/builtins.c |  6 +++--
 clang/test/Sema/constant-builtins-2.c  | 12 ++---
 clang/test/Sema/integer-overflow.c |  2 ++
 clang/test/Sema/shift-count-negative.c |  8 ++
 clang/test/Sema/shift-count-overflow.c |  9 +++
 clang/test/Sema/shift-negative-value.c | 13 ++
 clang/test/Sema/vla-2.c|  6 +++--
 clang/test/SemaCXX/enum.cpp| 16 +++-
 clang/test/SemaCXX/shift.cpp   |  2 +-
 14 files changed, 104 insertions(+), 21 deletions(-)
 create mode 100644 clang/test/Sema/shift-count-negative.c
 create mode 100644 clang/test/Sema/shift-count-overflow.c
 create mode 100644 clang/test/Sema/shift-negative-value.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cf1ba02cbc4b2..95ce9f2c332ac 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -569,6 +569,8 @@ Improvements to Clang's diagnostics
 - Clang no longer emits a "declared here" note for a builtin function that has 
no declaration in source.
   Fixes #GH93369.
 
+- Clang now diagnoses non-C++11 integer constant expressions. Fixes #GH59863
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index af1f18aa8ef24..afb1838e572b1 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2856,6 +2856,9 @@ static bool handleIntIntBinOp(EvalInfo &Info, const 
BinaryOperator *E,
   else if (LHS.countl_zero() < SA)
 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
 }
+if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
+Info.getLangOpts().CPlusPlus11)
+  return false;
 Result = LHS << SA;
 return true;
   }
@@ -2879,6 +2882,10 @@ static bool handleIntIntBinOp(EvalInfo &Info, const 
BinaryOperator *E,
 if (SA != RHS)
   Info.CCEDiag(E, diag::note_constexpr_large_shift)
 << RHS << E->getType() << LHS.getBitWidth();
+
+if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
+Info.getLangOpts().CPlusPlus11)
+  return false;
 Result = LHS >> SA;
 return true;
   }
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 44f886bf54e3a..887f8355fad25 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -11246,7 +11246,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   if (Right.isNegative()) {
 S.DiagRuntimeBehavior(Loc, RHS.get(),
   S.PDiag(diag::warn_shift_negative)
-<< RHS.get()->getSourceRange());
+  << RHS.get()->getSourceRange());
 return;
   }
 
@@ -11261,7 +11261,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   if (Right.uge(LeftSize)) {
 S.DiagRuntimeBehavior(Loc, RHS.get(),
   S.PDiag(diag::warn_shift_gt_typewidth)
-<< RHS.get()->getSourceRange());
+  << RHS.get()->getSourceRange());
 return;
   }
 
@@ -11294,7 +11294,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   if (Left.isNegative()) {
 S.DiagRuntimeBehavior(Loc, LHS.get(),
   S.PDiag(diag::warn_shift_lhs_negative)
-<< LHS.get()->getSourceRange());
+  << LHS.get()->getSourceRange());
 return;
   }
 
@@ -17130,11 +17130,38 @@ Sema::VerifyIntegerConstantExpression(Expr *E, 
llvm::APSInt *Result,
   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
   // in the non-ICE case.
   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
+SmallVector Notes;
 if (Result)
-  *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
+  *Result = E->EvaluateKnownConstIntCheckOverflow(Context, &Notes);
 if (!isa(E))
   E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
  : ConstantExpr::Create(Context, E);
+
+if (Notes.empty())
+  return E;
+
+// If our only note is the usual "invalid subexpression" note, just point
+// the caret at its location rather than producing an essentially
+// redundant note.
+if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
+

[clang] [clang] Emit bad shift warnings (PR #70307)

2024-06-25 Thread Budimir Aranđelović via cfe-commits

https://github.com/budimirarandjelovicsyrmia updated 
https://github.com/llvm/llvm-project/pull/70307

From f19ddd1d381d7e1c79b1d841070deb461f442eb7 Mon Sep 17 00:00:00 2001
From: budimirarandjelovicsyrmia 
Date: Thu, 26 Oct 2023 10:39:52 +0200
Subject: [PATCH] [clang] Emit bad shift warnings

---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/lib/AST/ExprConstant.cpp |  7 ++
 clang/lib/Sema/SemaExpr.cpp| 35 +++---
 clang/test/C/drs/dr0xx.c   |  3 ++-
 clang/test/C/drs/dr2xx.c   |  4 ++-
 clang/test/Sema/builtins.c |  6 +++--
 clang/test/Sema/constant-builtins-2.c  | 12 ++---
 clang/test/Sema/integer-overflow.c |  2 ++
 clang/test/Sema/shift-count-negative.c |  8 ++
 clang/test/Sema/shift-count-overflow.c |  9 +++
 clang/test/Sema/shift-negative-value.c | 13 ++
 clang/test/Sema/vla-2.c|  6 +++--
 clang/test/SemaCXX/enum.cpp| 16 +++-
 clang/test/SemaCXX/shift.cpp   |  2 +-
 14 files changed, 104 insertions(+), 21 deletions(-)
 create mode 100644 clang/test/Sema/shift-count-negative.c
 create mode 100644 clang/test/Sema/shift-count-overflow.c
 create mode 100644 clang/test/Sema/shift-negative-value.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9c8f8c4a4fbaf..c8d1633406fd3 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -612,6 +612,8 @@ Improvements to Clang's diagnostics
   used rather than when they are needed for constant evaluation or when code 
is generated for them.
   The check is now stricter to prevent crashes for some unsupported 
declarations (Fixes #GH95495).
 
+- Clang now diagnoses non-C++11 integer constant expressions. Fixes #GH59863
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index fe4b9a569ab87..5196d85d2a985 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2858,6 +2858,9 @@ static bool handleIntIntBinOp(EvalInfo &Info, const 
BinaryOperator *E,
   else if (LHS.countl_zero() < SA)
 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
 }
+if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
+Info.getLangOpts().CPlusPlus11)
+  return false;
 Result = LHS << SA;
 return true;
   }
@@ -2881,6 +2884,10 @@ static bool handleIntIntBinOp(EvalInfo &Info, const 
BinaryOperator *E,
 if (SA != RHS)
   Info.CCEDiag(E, diag::note_constexpr_large_shift)
 << RHS << E->getType() << LHS.getBitWidth();
+
+if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
+Info.getLangOpts().CPlusPlus11)
+  return false;
 Result = LHS >> SA;
 return true;
   }
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 4a2f3a65eac96..0c7d0fc6173e1 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -11256,7 +11256,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   if (Right.isNegative()) {
 S.DiagRuntimeBehavior(Loc, RHS.get(),
   S.PDiag(diag::warn_shift_negative)
-<< RHS.get()->getSourceRange());
+  << RHS.get()->getSourceRange());
 return;
   }
 
@@ -11271,7 +11271,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   if (Right.uge(LeftSize)) {
 S.DiagRuntimeBehavior(Loc, RHS.get(),
   S.PDiag(diag::warn_shift_gt_typewidth)
-<< RHS.get()->getSourceRange());
+  << RHS.get()->getSourceRange());
 return;
   }
 
@@ -11304,7 +11304,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   if (Left.isNegative()) {
 S.DiagRuntimeBehavior(Loc, LHS.get(),
   S.PDiag(diag::warn_shift_lhs_negative)
-<< LHS.get()->getSourceRange());
+  << LHS.get()->getSourceRange());
 return;
   }
 
@@ -17138,11 +17138,38 @@ Sema::VerifyIntegerConstantExpression(Expr *E, 
llvm::APSInt *Result,
   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
   // in the non-ICE case.
   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
+SmallVector Notes;
 if (Result)
-  *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
+  *Result = E->EvaluateKnownConstIntCheckOverflow(Context, &Notes);
 if (!isa(E))
   E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
  : ConstantExpr::Create(Context, E);
+
+if (Notes.empty())
+  return E;
+
+// If our only note is the usual "invalid subexpression" note, just point
+// the caret at its location rather than producing an essentially
+// r

[clang] [compiler-rt] [llvm] [CMake] Use Clang to infer the target triple (PR #89425)

2024-06-25 Thread YunQiang Su via cfe-commits


@@ -183,6 +183,24 @@ message(STATUS "LLVM default target triple: 
${LLVM_DEFAULT_TARGET_TRIPLE}")
 
 set(LLVM_TARGET_TRIPLE "${LLVM_DEFAULT_TARGET_TRIPLE}")
 
+if(CMAKE_C_COMPILER_ID MATCHES "Clang")
+  set(option_prefix "")
+  if (CMAKE_C_SIMULATE_ID MATCHES "MSVC")
+set(option_prefix "/clang:")
+  endif()
+  set(print_target_triple ${CMAKE_C_COMPILER} 
${option_prefix}--target=${LLVM_DEFAULT_TARGET_TRIPLE} 
${option_prefix}-print-target-triple)
+  execute_process(COMMAND ${print_target_triple}
+RESULT_VARIABLE result
+OUTPUT_VARIABLE output
+OUTPUT_STRIP_TRAILING_WHITESPACE)
+  if(result EQUAL 0)
+set(LLVM_DEFAULT_TARGET_TRIPLE ${output})
+  else()
+string(REPLACE ";" " " print_target_triple "${print_target_triple}")

wzssyqa wrote:

Ditto.  I guess that we need to test on more target. As some target doesn't use 
the new filesystem struct.

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


[clang] [compiler-rt] [llvm] [CMake] Use Clang to infer the target triple (PR #89425)

2024-06-25 Thread YunQiang Su via cfe-commits


@@ -368,14 +368,22 @@ macro(construct_compiler_rt_default_triple)
   "Default triple for which compiler-rt runtimes will be built.")
   endif()
 
-  if ("${CMAKE_C_COMPILER_ID}" MATCHES "Clang")
+  if(CMAKE_C_COMPILER_ID MATCHES "Clang")
 set(option_prefix "")
 if (CMAKE_C_SIMULATE_ID MATCHES "MSVC")
   set(option_prefix "/clang:")
 endif()
-execute_process(COMMAND ${CMAKE_C_COMPILER} 
${option_prefix}--target=${COMPILER_RT_DEFAULT_TARGET_TRIPLE} 
${option_prefix}-print-target-triple
-OUTPUT_VARIABLE COMPILER_RT_DEFAULT_TARGET_TRIPLE
-OUTPUT_STRIP_TRAILING_WHITESPACE)
+set(print_target_triple ${CMAKE_C_COMPILER} 
${option_prefix}--target=${COMPILER_RT_DEFAULT_TARGET_TRIPLE} 
${option_prefix}-print-target-triple)
+execute_process(COMMAND ${print_target_triple}
+  RESULT_VARIABLE result
+  OUTPUT_VARIABLE output
+  OUTPUT_STRIP_TRAILING_WHITESPACE)
+if(result EQUAL 0)
+  set(COMPILER_RT_DEFAULT_TARGET_TRIPLE ${output})
+else()
+  string(REPLACE ";" " " print_target_triple "${print_target_triple}")
+  message(WARNING "Failed to execute `${print_target_triple}` to normalize 
target triple.")

wzssyqa wrote:

I think that it should be a fetal error instead of just a warning?

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


[clang] [analyzer] Refine invalidation caused by `fread` (PR #93408)

2024-06-25 Thread via cfe-commits

vabridgers wrote:

Hi @steakhal , this change seems to have exposed by div/0 error in a very 
particular corner we came across after integrating this change. Could you try 
this case to see if can repro?

The div/0 is occurring at line 1093: 
   bool IncompleteLastElement = (NumBytesRead % ElemSizeInChars) != 0;

clang -cc1 -analyze -analyzer-checker=unix.Stream -analyzer-opt-analyze-headers 
test.c 

This is the test source. 

# 1 "" 3
typedef FILE;
void *b;
a() {
  FILE f = fopen("", "");
  fread(b, 1, 1, f);
}

The crash ... 
`$ clang -cc1 -analyze -analyzer-checker=unix.Stream 
-analyzer-opt-analyze-headers test.c`
`PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and 
include the crash backtrace, preprocessed source, and associated run script.`
`Stack dump:`
`0.  Program arguments: clang -cc1 -analyze -analyzer-checker=unix.Stream 
-analyzer-opt-analyze-headers test.c`
`1.   parser at end of file`
`2.  While analyzing stack:`
`#0 Calling a`
`3.  :5:3: Error evaluating statement`
`4.  :5:3: Error evaluating statement`
` #0 0x0686046a llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
llvm/lib/Support/Unix/Signals.inc:723:22`
` #1 0x068608a4 PrintStackTraceSignalHandler(void*) 
llvm/lib/Support/Unix/Signals.inc:798:1`
` #2 0x0685e1bd llvm::sys::RunSignalHandlers() 
llvm/lib/Support/Signals.cpp:105:20`
` #3 0x0685fe54 SignalHandler(int) 
llvm/lib/Support/Unix/Signals.inc:413:1`
` #4 0x7f931d2c1630 __restore_rt sigaction.c:0:0`
` #5 0x09fc96ff 
tryToInvalidateFReadBufferByElements(llvm::IntrusiveRefCntPtr, clang::ento::CheckerContext&, clang::ento::CallEvent const&, 
clang::ento::NonLoc, clang::ento::NonLoc) 
clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:1093:48`




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


[clang-tools-extra] [clang-tidy]: Use correct term for user-provided constructor (PR #96617)

2024-06-25 Thread Anders Schau Knatten via cfe-commits

https://github.com/knatten created 
https://github.com/llvm/llvm-project/pull/96617

First of all, fix a confusion in the documentation for pro-type-member-init 
which used the wrong term for a user-provided constructor. (In the 
corresponding comment in ProTypeMemberInitCheck.h, which was added in the same 
commit that added this documentation, we already use the correct term).

Second, also fix a comment in the corresponding test that had the same mistake.

https://timsong-cpp.github.io/cppwp/std23/dcl.fct.def.default#5:

> A function is user-provided if it is user-declared and not explicitly
> defaulted or deleted on its first declaration.

("user-defined constructor" is not a thing in the standard)

>From 7bc0205abaeeeab058d6568b202a0d7f98496863 Mon Sep 17 00:00:00 2001
From: Anders Schau Knatten 
Date: Tue, 25 Jun 2024 12:13:35 +0200
Subject: [PATCH] [clang-tidy]: Use correct term for user-provided constructor

First of all, fix a confusion in the documentation for
pro-type-member-init which used the wrong term for a user-provided
constructor. (In the corresponding comment in ProTypeMemberInitCheck.h,
which was added in the same commit that added this documentation, we
already use the correct term).

Second, also fix a comment in the corresponding test that had the same
mistake.

https://timsong-cpp.github.io/cppwp/std23/dcl.fct.def.default#5:

> A function is user-provided if it is user-declared and not explicitly
> defaulted or deleted on its first declaration.

("user-defined constructor" is not a thing in the standard)
---
 .../checks/cppcoreguidelines/pro-type-member-init.rst   | 2 +-
 .../checkers/cppcoreguidelines/pro-type-member-init.cpp | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-member-init.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-member-init.rst
index ae55bf7bd7c86..97af01a895e1c 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-member-init.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-member-init.rst
@@ -3,7 +3,7 @@
 cppcoreguidelines-pro-type-member-init
 ==
 
-The check flags user-defined constructor definitions that do not
+The check flags user-provided constructor definitions that do not
 initialize all fields that would be left in an undefined state by
 default construction, e.g. builtins, pointers and record types without
 user-provided default constructors containing at least one such
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
index eaa73b906ce09..d999b84cae03e 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
@@ -243,7 +243,7 @@ struct PositiveUninitializedBaseOrdering : public 
NegativeAggregateType,
 };
 
 // We shouldn't need to initialize anything because PositiveUninitializedBase
-// has a user-defined constructor.
+// has a user-provided constructor.
 struct NegativeUninitializedBase : public PositiveUninitializedBase {
   NegativeUninitializedBase() {}
 };

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


[clang-tools-extra] [clang-tidy]: Use correct term for user-provided constructor (PR #96617)

2024-06-25 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang-tools-extra] [clang-tidy]: Use correct term for user-provided constructor (PR #96617)

2024-06-25 Thread via cfe-commits

llvmbot wrote:



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

@llvm/pr-subscribers-clang-tidy

Author: Anders Schau Knatten (knatten)


Changes

First of all, fix a confusion in the documentation for pro-type-member-init 
which used the wrong term for a user-provided constructor. (In the 
corresponding comment in ProTypeMemberInitCheck.h, which was added in the same 
commit that added this documentation, we already use the correct term).

Second, also fix a comment in the corresponding test that had the same mistake.

https://timsong-cpp.github.io/cppwp/std23/dcl.fct.def.default#5:

> A function is user-provided if it is user-declared and not explicitly
> defaulted or deleted on its first declaration.

("user-defined constructor" is not a thing in the standard)

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


2 Files Affected:

- (modified) 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-member-init.rst
 (+1-1) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
 (+1-1) 


``diff
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-member-init.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-member-init.rst
index ae55bf7bd7c86..97af01a895e1c 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-member-init.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-member-init.rst
@@ -3,7 +3,7 @@
 cppcoreguidelines-pro-type-member-init
 ==
 
-The check flags user-defined constructor definitions that do not
+The check flags user-provided constructor definitions that do not
 initialize all fields that would be left in an undefined state by
 default construction, e.g. builtins, pointers and record types without
 user-provided default constructors containing at least one such
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
index eaa73b906ce09..d999b84cae03e 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
@@ -243,7 +243,7 @@ struct PositiveUninitializedBaseOrdering : public 
NegativeAggregateType,
 };
 
 // We shouldn't need to initialize anything because PositiveUninitializedBase
-// has a user-defined constructor.
+// has a user-provided constructor.
 struct NegativeUninitializedBase : public PositiveUninitializedBase {
   NegativeUninitializedBase() {}
 };

``




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


[clang] [Clang][AMDGPU] Add builtins for instrinsic `llvm.amdgcn.raw.ptr.buffer.store` (PR #94576)

2024-06-25 Thread Matt Arsenault via cfe-commits

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


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


[clang] [llvm] [AMDGPU] Extend permlane16, permlanex16 and permlane64 intrinsic lowering for generic types (PR #92725)

2024-06-25 Thread Matt Arsenault via cfe-commits

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


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


[clang] [NFC][clang] Replace unreachable code in literal processing with assert (PR #96579)

2024-06-25 Thread Aaron Ballman via cfe-commits

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

LGTM!

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


[clang] [llvm] [AMDGPU] Enable atomic optimizer for 64 bit divergent values (PR #96473)

2024-06-25 Thread Matt Arsenault via cfe-commits


@@ -311,10 +312,11 @@ void 
AMDGPUAtomicOptimizerImpl::visitIntrinsicInst(IntrinsicInst &I) {
 
   // If the value operand is divergent, each lane is contributing a different
   // value to the atomic calculation. We can only optimize divergent values if
-  // we have DPP available on our subtarget, and the atomic operation is 32
-  // bits.
+  // we have DPP available on our subtarget, and the atomic operation is 32 or
+  // 64 bits.
   if (ValDivergent &&
-  (!ST->hasDPP() || DL->getTypeSizeInBits(I.getType()) != 32)) {
+  (!ST->hasDPP() || (DL->getTypeSizeInBits(I.getType()) != 32 &&

arsenm wrote:

Ditto 

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


[clang] [llvm] [AMDGPU] Enable atomic optimizer for 64 bit divergent values (PR #96473)

2024-06-25 Thread Matt Arsenault via cfe-commits


@@ -228,10 +228,11 @@ void 
AMDGPUAtomicOptimizerImpl::visitAtomicRMWInst(AtomicRMWInst &I) {
 
   // If the value operand is divergent, each lane is contributing a different
   // value to the atomic calculation. We can only optimize divergent values if
-  // we have DPP available on our subtarget, and the atomic operation is 32
-  // bits.
+  // we have DPP available on our subtarget, and the atomic operation is either
+  // 32 or 64 bits.
   if (ValDivergent &&
-  (!ST->hasDPP() || DL->getTypeSizeInBits(I.getType()) != 32)) {
+  (!ST->hasDPP() || (DL->getTypeSizeInBits(I.getType()) != 32 &&
+  DL->getTypeSizeInBits(I.getType()) != 64))) {

arsenm wrote:

You should move the type logic into a separate predicate function. But also, 
you should base this on the actual type and not just the bitwidth. Checking the 
bitwidth will break in the future when atomics support more vector operations

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


[clang] 9acb533 - [clang][Driver] Add HIPAMD Driver support for AMDGCN flavoured SPIR-V (#95061)

2024-06-25 Thread via cfe-commits

Author: Alex Voicu
Date: 2024-06-25T12:19:28+01:00
New Revision: 9acb533c38be833ec1d8daa06e127a9de8f0a5ef

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

LOG: [clang][Driver] Add HIPAMD Driver support for AMDGCN flavoured SPIR-V 
(#95061)

This patch augments the HIPAMD driver to allow it to target AMDGCN
flavoured SPIR-V compilation. It's mostly straightforward, as we re-use
some of the existing SPIRV infra, however there are a few notable
additions:

- we introduce an `amdgcnspirv` offload arch, rather than relying on
using `generic` (this is already fairly overloaded) or simply using
`spirv` or `spirv64` (we'll want to use these to denote unflavoured
SPIRV, once we bring up that capability)
- initially it is won't be possible to mix-in SPIR-V and concrete AMDGPU
targets, as it would require some relatively intrusive surgery in the
HIPAMD Toolchain and the Driver to deal with two triples
(`spirv64-amd-amdhsa` and `amdgcn-amd-amdhsa`, respectively)
- in order to retain user provided compiler flags and have them
available at JIT time, we rely on embedding the command line via
`-fembed-bitcode=marker`, which the bitcode writer had previously not
implemented for SPIRV; we only allow it conditionally for AMDGCN
flavoured SPIRV, and it is handled correctly by the Translator (it ends
up as a string literal)

Once the SPIRV BE is no longer experimental we'll switch to using that
rather than the translator. There's some additional work that'll come
via a separate PR around correctly piping through AMDGCN's
implementation of `printf`, for now we merely handle its flags
correctly.

Added: 


Modified: 
clang/include/clang/Basic/Cuda.h
clang/lib/Basic/Cuda.cpp
clang/lib/Basic/Targets/NVPTX.cpp
clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/HIPAMD.cpp
clang/lib/Driver/ToolChains/HIPAMD.h
clang/test/Driver/cuda-arch-translation.cu
clang/test/Frontend/embed-bitcode.ll
clang/test/Misc/target-invalid-cpu-note.c
llvm/lib/Bitcode/Writer/BitcodeWriter.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Cuda.h 
b/clang/include/clang/Basic/Cuda.h
index 0d5e38e825aa7..01cfe286c491b 100644
--- a/clang/include/clang/Basic/Cuda.h
+++ b/clang/include/clang/Basic/Cuda.h
@@ -128,6 +128,7 @@ enum class CudaArch {
   GFX12_GENERIC,
   GFX1200,
   GFX1201,
+  AMDGCNSPIRV,
   Generic, // A processor model named 'generic' if the target backend defines a
// public one.
   LAST,

diff  --git a/clang/lib/Basic/Cuda.cpp b/clang/lib/Basic/Cuda.cpp
index 1d96a929f95d8..af99c4d61021e 100644
--- a/clang/lib/Basic/Cuda.cpp
+++ b/clang/lib/Basic/Cuda.cpp
@@ -148,6 +148,7 @@ static const CudaArchToStringMap arch_names[] = {
 {CudaArch::GFX12_GENERIC, "gfx12-generic", "compute_amdgcn"},
 GFX(1200), // gfx1200
 GFX(1201), // gfx1201
+{CudaArch::AMDGCNSPIRV, "amdgcnspirv", "compute_amdgcn"},
 {CudaArch::Generic, "generic", ""},
 // clang-format on
 };

diff  --git a/clang/lib/Basic/Targets/NVPTX.cpp 
b/clang/lib/Basic/Targets/NVPTX.cpp
index ff7d2f1f92aa4..8e9006853db65 100644
--- a/clang/lib/Basic/Targets/NVPTX.cpp
+++ b/clang/lib/Basic/Targets/NVPTX.cpp
@@ -232,6 +232,7 @@ void NVPTXTargetInfo::getTargetDefines(const LangOptions 
&Opts,
   case CudaArch::GFX12_GENERIC:
   case CudaArch::GFX1200:
   case CudaArch::GFX1201:
+  case CudaArch::AMDGCNSPIRV:
   case CudaArch::Generic:
   case CudaArch::LAST:
 break;

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
index 6e9a1bacd9bf5..6df34774334fa 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -3541,6 +3541,7 @@ void CGOpenMPRuntimeGPU::processRequiresDirective(
   case CudaArch::GFX12_GENERIC:
   case CudaArch::GFX1200:
   case CudaArch::GFX1201:
+  case CudaArch::AMDGCNSPIRV:
   case CudaArch::Generic:
   case CudaArch::UNUSED:
   case CudaArch::UNKNOWN:

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 76534475e88f7..652f519d82488 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -907,7 +907,8 @@ void CodeGenModule::Release() {
   if (Context.getTargetInfo().getTriple().isWasm())
 EmitMainVoidAlias();
 
-  if (getTriple().isAMDGPU()) {
+  if (getTriple().isAMDGPU() ||
+  (getTriple().isSPIRV() && getTriple().getVendor() == llvm::Triple::AMD)) 
{
 // Emit amdhsa_code_object_version module flag, which is code object 
version
 // times 100.
 if (getTarget().getTargetOpts().CodeObjectVersion

[clang] [llvm] [clang][Driver] Add HIPAMD Driver support for AMDGCN flavoured SPIR-V (PR #95061)

2024-06-25 Thread Alex Voicu via cfe-commits

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


[clang] [TBAA] Emit int TBAA metadata on FP math libcalls (PR #96025)

2024-06-25 Thread via cfe-commits

https://github.com/vfdff updated https://github.com/llvm/llvm-project/pull/96025

>From ed6292fd0e9119322c39e5f37e2225c76e324101 Mon Sep 17 00:00:00 2001
From: zhongyunde 00443407 
Date: Tue, 18 Jun 2024 09:21:07 -0400
Subject: [PATCH 1/4] [TBAA] Emit int TBAA metadata on FP math libcalls

Base on the discussion 
https://discourse.llvm.org/t/fp-can-we-add-pure-attribute-for-math-library-functions-default/79459,
math libcalls set errno, so it should emit "int" TBAA metadata on FP libcalls
to solve the alias issue.

Fix https://github.com/llvm/llvm-project/issues/86635
---
 clang/lib/CodeGen/CGBuiltin.cpp   | 33 ++-
 clang/test/CodeGen/math-libcalls-tbaa.cpp | 22 +++
 2 files changed, 54 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGen/math-libcalls-tbaa.cpp

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 08a89bd123d03..dc4af109cdbdb 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -707,7 +707,38 @@ static RValue emitLibraryCall(CodeGenFunction &CGF, const 
FunctionDecl *FD,
   const CallExpr *E, llvm::Constant *calleeValue) {
   CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
   CGCallee callee = CGCallee::forDirect(calleeValue, GlobalDecl(FD));
-  return CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot());
+  RValue Call =
+  CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot());
+
+  // Check the supported intrinsic.
+  if (unsigned BuiltinID = FD->getBuiltinID()) {
+auto IntrinsicID = [&]() -> unsigned {
+  switch (BuiltinID) {
+  case Builtin::BIexpf:
+  case Builtin::BI__builtin_expf:
+  case Builtin::BI__builtin_expf128:
+return true;
+  }
+  // TODO: support more FP math libcalls
+  return false;
+}();
+
+if (IntrinsicID) {
+  llvm::MDBuilder MDHelper(CGF.getLLVMContext());
+  MDNode *RootMD;
+  if (CGF.getLangOpts().CPlusPlus)
+RootMD = MDHelper.createTBAARoot("Simple C++ TBAA");
+  else
+RootMD = MDHelper.createTBAARoot("Simple C/C++ TBAA");
+  // Emit "int" TBAA metadata on FP math libcalls.
+  MDNode *AliasType = MDHelper.createTBAANode("int", RootMD);
+  MDNode *MDInt = MDHelper.createTBAAStructTagNode(AliasType, AliasType, 
0);
+
+  Value *Val = Call.getScalarVal();
+  cast(Val)->setMetadata(LLVMContext::MD_tbaa, MDInt);
+}
+  }
+  return Call;
 }
 
 /// Emit a call to llvm.{sadd,uadd,ssub,usub,smul,umul}.with.overflow.*
diff --git a/clang/test/CodeGen/math-libcalls-tbaa.cpp 
b/clang/test/CodeGen/math-libcalls-tbaa.cpp
new file mode 100644
index 0..d5b0741a476cb
--- /dev/null
+++ b/clang/test/CodeGen/math-libcalls-tbaa.cpp
@@ -0,0 +1,22 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 2
+// RUN:  %clang -S -O3 -emit-llvm -o - -x c++ %s | FileCheck %s 
-check-prefixes=CHECK
+
+#include 
+
+
+// Emit int TBAA metadata on FP math libcalls, which is useful for alias 
analysis
+
+// CHECK-LABEL: define dso_local noundef float @_Z3fooPffi
+// CHECK-SAME: (ptr nocapture noundef readonly [[NUM:%.*]], float noundef 
[[R2INV:%.*]], i32 noundef [[N:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[ARRAYIDX:%.*]] = getelementptr inbounds i8, ptr [[NUM]], 
i64 40
+// CHECK-NEXT:[[TMP0:%.*]] = load float, ptr [[ARRAYIDX]], align 4, !tbaa 
[[TBAA6:![0-9]+]]
+// CHECK-NEXT:[[CALL_I:%.*]] = tail call noundef float @expf(float noundef 
[[TMP0]]) #[[ATTR2:[0-9]+]], !tbaa [[TBAA10:![0-9]+]]
+// CHECK-NEXT:[[MUL:%.*]] = fmul float [[TMP0]], [[CALL_I]]
+// CHECK-NEXT:ret float [[MUL]]
+//
+float foo (float num[], float r2inv, int n) {
+   const float expm2 =  std::exp(num[10]);  // Emit TBAA metadata on @expf
+   float tmp = expm2 * num[10];
+   return tmp;
+}

>From 9990877a2b9736c684c8cabeb03c6d98a3d078ce Mon Sep 17 00:00:00 2001
From: zhongyunde 00443407 
Date: Thu, 20 Jun 2024 02:29:11 -0400
Subject: [PATCH 2/4] Address comment, reuse CodeGenTBAA::getRoot

---
 clang/lib/CodeGen/CGBuiltin.cpp   |  6 +-
 clang/lib/CodeGen/CodeGenModule.h |  2 ++
 clang/lib/CodeGen/CodeGenTBAA.h   |  8 
 clang/test/CodeGen/math-libcalls-tbaa.cpp | 20 +++-
 4 files changed, 22 insertions(+), 14 deletions(-)

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index dc4af109cdbdb..3f448e11bca1a 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -725,11 +725,7 @@ static RValue emitLibraryCall(CodeGenFunction &CGF, const 
FunctionDecl *FD,
 
 if (IntrinsicID) {
   llvm::MDBuilder MDHelper(CGF.getLLVMContext());
-  MDNode *RootMD;
-  if (CGF.getLangOpts().CPlusPlus)
-RootMD = MDHelper.createTBAARoot("Simple C++ TBAA");
-  else
-RootMD = MDHelper.createTBAARoot("Si

[clang] [TBAA] Emit int TBAA metadata on FP math libcalls (PR #96025)

2024-06-25 Thread via cfe-commits


@@ -707,7 +707,34 @@ static RValue emitLibraryCall(CodeGenFunction &CGF, const 
FunctionDecl *FD,
   const CallExpr *E, llvm::Constant *calleeValue) {
   CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
   CGCallee callee = CGCallee::forDirect(calleeValue, GlobalDecl(FD));
-  return CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot());
+  RValue Call =
+  CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot());
+
+  // Check the supported intrinsic.
+  if (unsigned BuiltinID = FD->getBuiltinID()) {
+auto IntrinsicID = [&]() -> unsigned {
+  switch (BuiltinID) {
+  case Builtin::BIexpf:
+  case Builtin::BI__builtin_expf:
+  case Builtin::BI__builtin_expf128:
+return true;
+  }
+  // TODO: support more FP math libcalls
+  return false;
+}();
+
+if (IntrinsicID) {
+  llvm::MDBuilder MDHelper(CGF.getLLVMContext());
+  MDNode *RootMD = CGF.CGM.getTBAARoot();
+  // Emit "int" TBAA metadata on FP math libcalls.
+  MDNode *AliasType = MDHelper.createTBAANode("int", RootMD);

vfdff wrote:

Yes, apply your comment, thanks

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


[clang] [clang] Catch missing format attributes (PR #70024)

2024-06-25 Thread Budimir Aranđelović via cfe-commits

https://github.com/budimirarandjelovicsyrmia updated 
https://github.com/llvm/llvm-project/pull/70024

From 5bc76cd96f52cf8184712c8e1ffa521f05e3e29c Mon Sep 17 00:00:00 2001
From: budimirarandjelovicsyrmia 
Date: Fri, 5 Apr 2024 15:20:37 +0200
Subject: [PATCH] [clang] Catch missing format attributes

---
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/include/clang/Basic/DiagnosticGroups.td |   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   3 +
 clang/include/clang/Sema/Attr.h   |   7 +
 clang/include/clang/Sema/Sema.h   |   4 +
 clang/lib/Sema/SemaChecking.cpp   |   4 +-
 clang/lib/Sema/SemaDeclAttr.cpp   | 112 ++-
 clang/test/Sema/attr-format-missing.c | 304 ++
 clang/test/Sema/attr-format-missing.cpp   | 178 ++
 9 files changed, 612 insertions(+), 4 deletions(-)
 create mode 100644 clang/test/Sema/attr-format-missing.c
 create mode 100644 clang/test/Sema/attr-format-missing.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9ed3ff4507671..63be1b80b983a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -626,6 +626,9 @@ Improvements to Clang's diagnostics
   used rather than when they are needed for constant evaluation or when code 
is generated for them.
   The check is now stricter to prevent crashes for some unsupported 
declarations (Fixes #GH95495).
 
+- Clang now diagnoses missing format attributes for non-template functions and
+  class/struct/union members. Fixes #GH60718
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 1c4f305fb5d00..4836b499fbbee 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -505,7 +505,6 @@ def MainReturnType : DiagGroup<"main-return-type">;
 def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">;
 def MissingBraces : DiagGroup<"missing-braces">;
 def MissingDeclarations: DiagGroup<"missing-declarations">;
-def : DiagGroup<"missing-format-attribute">;
 def MissingIncludeDirs : DiagGroup<"missing-include-dirs">;
 def MissingNoreturn : DiagGroup<"missing-noreturn">;
 def MultiChar : DiagGroup<"multichar">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 46ad359751d7d..e4fd8904b9f4d 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -1021,6 +1021,9 @@ def err_opencl_invalid_param : Error<
 def err_opencl_invalid_return : Error<
   "declaring function return value of type %0 is not allowed %select{; did you 
forget * ?|}1">;
 def warn_enum_value_overflow : Warning<"overflow in enumeration value">;
+def warn_missing_format_attribute : Warning<
+  "diagnostic behavior may be improved by adding the %0 format attribute to 
the declaration of %1">,
+  InGroup>, DefaultIgnore;
 def warn_pragma_options_align_reset_failed : Warning<
   "#pragma options align=reset failed: %0">,
   InGroup;
diff --git a/clang/include/clang/Sema/Attr.h b/clang/include/clang/Sema/Attr.h
index 3f0b10212789a..37c124ca7b454 100644
--- a/clang/include/clang/Sema/Attr.h
+++ b/clang/include/clang/Sema/Attr.h
@@ -123,6 +123,13 @@ inline bool isInstanceMethod(const Decl *D) {
   return false;
 }
 
+inline bool checkIfMethodHasImplicitObjectParameter(const Decl *D) {
+  if (const auto *MethodDecl = dyn_cast(D))
+return MethodDecl->isInstance() &&
+   !MethodDecl->hasCXXExplicitFunctionObjectParameter();
+  return false;
+}
+
 /// Diagnose mutually exclusive attributes when present on a given
 /// declaration. Returns true if diagnosed.
 template 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 2e7af0f691cbb..74b6a8841da4a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3854,6 +3854,10 @@ class Sema final : public SemaBase {
 
   enum class RetainOwnershipKind { NS, CF, OS };
 
+  void DiagnoseMissingFormatAttributes(const FunctionDecl *FDecl,
+   ArrayRef Args,
+   SourceLocation Loc);
+
   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
   StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
 
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 87988519e7691..63697fab64ee1 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -4119,8 +4119,10 @@ void Sema::checkCall(NamedDecl *FDecl, const 
FunctionProtoType *Proto,
 }
   }
 
-  if (FD)
+  if (FD) {
 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
+DiagnoseMissingFormatAttributes(FD, Args, Range.getBegin());
+  }
 }
 
 void Sema::CheckConstrainedAuto(const AutoType *AutoT, Source

[clang] [llvm] [LLVM] Fix incorrect alignment on AMDGPU variadics (PR #96370)

2024-06-25 Thread Matt Arsenault via cfe-commits

arsenm wrote:

> > Incrementing by align is just a bug, of course the size is the real value. 
> > Whether we want to continue wasting space is another not-correctness 
> > discussion
> 
> Struct padding is pretty universal, AMDGPU seems the odd one out here. I 
> wouldn't mind it so much if it didn't require me to know which vendor I was 
> dealing with in the RPC implementation, but I suppose I could store that 
> information somewhere if we want to use a compressed option and we know it 
> works.

It's not about struct padding, but the base alignment. Any pointer increment 
should be alignTo(ptr + size, align), not += align. The += align won't even 
work for large structs 

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


[clang-tools-extra] [IncludeCleaner] display overview (PR #93932)

2024-06-25 Thread via cfe-commits

https://github.com/TheHillBright updated 
https://github.com/llvm/llvm-project/pull/93932

>From e803c635a64ed3c2ad0381e82ca308f63dcf4604 Mon Sep 17 00:00:00 2001
From: TheHillBright <150074496+thehillbri...@users.noreply.github.com>
Date: Fri, 31 May 2024 15:00:37 +0800
Subject: [PATCH] IncludeCleaner: display overview

---
 clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp 
b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
index 3bc449b0152bb..788ad87b1d4e8 100644
--- a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
+++ b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
@@ -279,7 +279,7 @@ int main(int argc, const char **argv) {
 
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
   auto OptionsParser =
-  clang::tooling::CommonOptionsParser::create(argc, argv, IncludeCleaner);
+  clang::tooling::CommonOptionsParser::create(argc, argv, IncludeCleaner, 
cl::OneOrMore, Overview);
   if (!OptionsParser) {
 llvm::errs() << toString(OptionsParser.takeError());
 return 1;

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


[clang-tools-extra] [IncludeCleaner] display overview (PR #93932)

2024-06-25 Thread via cfe-commits

TheHillBright wrote:

Ping @kadircet @sam-mccall for one month of inactivity for this simple PR.

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


[clang] [Clang] Clarify diagnostic notes for implicitly generated deduction guides (PR #96084)

2024-06-25 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 updated 
https://github.com/llvm/llvm-project/pull/96084

>From 23844cd8b8fad07bce0c34f58430322090c5a793 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 19 Jun 2024 23:25:13 +0800
Subject: [PATCH 1/4] [Clang] Add diagnostic notes for implcitly generated
 deduction guides

---
 clang/docs/ReleaseNotes.rst   |  3 ++
 .../clang/Basic/DiagnosticSemaKinds.td|  1 +
 clang/lib/Sema/SemaOverload.cpp   | 30 +++
 clang/test/CXX/drs/cwg26xx.cpp|  3 ++
 .../CXX/expr/expr.post/expr.type.conv/p1.cpp  |  2 +-
 .../over.match.class.deduct/p2.cpp|  2 +-
 .../temp.deduct/temp.deduct.call/p3-0x.cpp|  4 +--
 clang/test/Modules/template_name_lookup.cpp   |  2 ++
 clang/test/PCH/cxx-explicit-specifier.cpp |  2 +-
 clang/test/Sema/tls_alignment.cpp |  4 ++-
 ...xx1z-class-template-argument-deduction.cpp |  6 ++--
 clang/test/SemaCXX/cxx20-ctad-type-alias.cpp  | 17 +--
 clang/test/SemaCXX/cxx2a-explicit-bool.cpp|  2 ++
 clang/test/SemaCXX/gh65522.cpp|  3 +-
 ...deduction-guide-as-template-candidates.cpp |  4 ++-
 .../lookup-template-name-extern-CXX.cpp   |  6 ++--
 .../aggregate-deduction-candidate.cpp | 24 ---
 clang/test/SemaTemplate/class-template-id.cpp |  2 ++
 clang/test/SemaTemplate/ctad.cpp  |  6 ++--
 clang/test/SemaTemplate/deduction-crash.cpp   |  3 +-
 clang/test/SemaTemplate/deduction-guide.cpp   |  6 ++--
 .../nested-implicit-deduction-guides.cpp  |  3 ++
 clang/test/SemaTemplate/temp_arg.cpp  |  4 ++-
 23 files changed, 108 insertions(+), 31 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..423f1e9198948 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -580,6 +580,9 @@ Improvements to Clang's diagnostics
 - Clang no longer emits a "declared here" note for a builtin function that has 
no declaration in source.
   Fixes #GH93369.
 
+- Clang now emits implicit deduction guides corresponding to non-user-defined 
constructors while at a failure
+  of overload resolution.
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ab223f2b806d5..a65491b0c4399 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2405,6 +2405,7 @@ def err_selected_explicit_constructor : Error<
   "chosen constructor is explicit in copy-initialization">;
 def note_explicit_ctor_deduction_guide_here : Note<
   "explicit %select{constructor|deduction guide}0 declared here">;
+def note_implicit_deduction_guide : Note<"implicit deduction guide declared as 
'%0'">;
 
 // C++11 auto
 def warn_cxx98_compat_auto_type_specifier : Warning<
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index fb4ff72e42eb5..31b908eb3cc3c 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -40,6 +40,7 @@
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/STLForwardCompat.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
@@ -12114,6 +12115,35 @@ static void NoteFunctionCandidate(Sema &S, 
OverloadCandidate *Cand,
 return;
   }
 
+  // If this is an implicit deduction guide against a non-user-defined
+  // constructor, add a note for it. These deduction guides nor their
+  // corresponding constructors are not explicitly spelled in the source code,
+  // and simply producing a deduction failure note around the heading of the
+  // enclosing RecordDecl is confusing.
+  //
+  // We prefer adding such notes at the end of the last deduction failure
+  // reason because duplicate code snippets appearing in the diagnostic
+  // are likely becoming noisy.
+  auto _ = llvm::make_scope_exit([&] {
+auto *DG = dyn_cast(Fn);
+if (!DG || !DG->isImplicit() || DG->getCorrespondingConstructor())
+  return;
+std::string FunctionProto;
+llvm::raw_string_ostream OS(FunctionProto);
+FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
+// This also could be an instantiation. Find out the primary template.
+if (!Template) {
+  FunctionDecl *Pattern = DG->getTemplateInstantiationPattern();
+  assert(Pattern && Pattern->getDescribedFunctionTemplate() &&
+ "Cannot find the associated function template of "
+ "CXXDeductionGuideDecl?");
+  Template = Pattern->getDescribedFunctionTemplate();
+}
+Template->print(OS);
+S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
+<< FunctionProto;
+  });
+
   switch (Cand->FailureKind) {
   case ovl_fail_too_many_arguments:
   case ovl_fail_too_few_arguments:
dif

[clang] [Clang] Clarify diagnostic notes for implicitly generated deduction guides (PR #96084)

2024-06-25 Thread Younan Zhang via cfe-commits


@@ -12114,6 +12115,35 @@ static void NoteFunctionCandidate(Sema &S, 
OverloadCandidate *Cand,
 return;
   }
 
+  // If this is an implicit deduction guide against an implicitly defined
+  // constructor, add a note for it. Neither these deduction guides nor their
+  // corresponding constructors are explicitly spelled in the source code,
+  // and simply producing a deduction failure note around the heading of the
+  // enclosing RecordDecl would be confusing.
+  //
+  // We prefer adding such notes at the end of the last deduction failure
+  // reason because duplicate code snippets appearing in the diagnostic
+  // would likely become noisy.
+  auto _ = llvm::make_scope_exit([&] {
+auto *DG = dyn_cast(Fn);
+if (!DG || !DG->isImplicit() || DG->getCorrespondingConstructor())

zyn0217 wrote:

Done. I think this can be done by checking the origin template.

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


[clang] [llvm] [LLVM] Fix incorrect alignment on AMDGPU variadics (PR #96370)

2024-06-25 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

> > > Incrementing by align is just a bug, of course the size is the real 
> > > value. Whether we want to continue wasting space is another 
> > > not-correctness discussion
> > 
> > 
> > Struct padding is pretty universal, AMDGPU seems the odd one out here. I 
> > wouldn't mind it so much if it didn't require me to know which vendor I was 
> > dealing with in the RPC implementation, but I suppose I could store that 
> > information somewhere if we want to use a compressed option and we know it 
> > works.
> 
> It's not about struct padding, but the base alignment. Any pointer increment 
> should be alignTo(ptr + size, align), not += align. The += align won't even 
> work for large structs

Hm, that's what I'm doing in the `printf` implementation and it doesn't work 
without that patch. When I look at the varargs struct it didn't have any 
padding, which explained why `alignTo(ptr + size, align)` was wrong. So, I was 
trying to do the following, `printf("%d%ld", 1, 1l)`. With this patch I get the 
following,
```
0xbebebebe0001
0x0001
```
Without this patch, I get this. As you can see there's no struct padding so the 
8 byte value is right next to the 4 byte one.
```
0x00010001
0xbebebebe
```

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


[clang] [compiler-rt] [ubsan] Display correct runtime messages for negative _BitInt (PR #96240)

2024-06-25 Thread via cfe-commits

https://github.com/earnol updated 
https://github.com/llvm/llvm-project/pull/96240

>From d01c49f85902d2ec660db2cb32dc2d1e0d04c393 Mon Sep 17 00:00:00 2001
From: Vladislav Aranov 
Date: Fri, 24 May 2024 11:39:35 -0400
Subject: [PATCH] [ubsan] Display correct runtime messages for negative _BitInt

Without this patch compiler-rt ubsan library has a bug displaying
incorrect values for variables of the _BitInt (previousely called
_ExtInt) type. This patch affects both: generation of metadata
inside code generator and runtime part. The runtime part provided only
for i386 and x86_64 runtimes. Other runtimes should be updated to take
full benefit of this patch.
The patch is constructed the way to be backward compatible and
int and float type runtime diagnostics should be unaffected for not
yet updated runtimes.

Co-authored-by: Aaron Ballman 
---
 clang/lib/CodeGen/CGExpr.cpp  |  59 +-
 clang/test/CodeGen/bit-int-ubsan.c|  95 ++
 compiler-rt/lib/ubsan/ubsan_value.cpp |  17 +-
 compiler-rt/lib/ubsan/ubsan_value.h   |  34 +++-
 .../ubsan/TestCases/Integer/bit-int-pass.c|  42 +
 .../test/ubsan/TestCases/Integer/bit-int.c| 170 ++
 6 files changed, 404 insertions(+), 13 deletions(-)
 create mode 100644 clang/test/CodeGen/bit-int-ubsan.c
 create mode 100644 compiler-rt/test/ubsan/TestCases/Integer/bit-int-pass.c
 create mode 100644 compiler-rt/test/ubsan/TestCases/Integer/bit-int.c

diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 534f46da74862..cebfe98eda97f 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -41,6 +41,7 @@
 #include "llvm/IR/MatrixBuilder.h"
 #include "llvm/Passes/OptimizationLevel.h"
 #include "llvm/Support/ConvertUTF.h"
+#include "llvm/Support/Endian.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/SaveAndRestore.h"
@@ -64,6 +65,22 @@ static llvm::cl::opt ClSanitizeGuardChecks(
 "ubsan-guard-checks", llvm::cl::Optional,
 llvm::cl::desc("Guard UBSAN checks with `llvm.allow.ubsan.check()`."));
 
+//======//
+//Defines for metadata
+//======//
+
+// Those values are crucial to be the SAME as in ubsan runtime library.
+enum VariableTypeDescriptorKind : uint16_t {
+  /// An integer type.
+  TK_Integer = 0x,
+  /// A floating-point type.
+  TK_Float = 0x0001,
+  /// An _BitInt(N) type.
+  TK_BitInt = 0x0002,
+  /// Any other type. The value representation is unspecified.
+  TK_Unknown = 0x
+};
+
 //======//
 //Miscellaneous Helper Methods
 //======//
@@ -3298,22 +3315,40 @@ LValue CodeGenFunction::EmitPredefinedLValue(const 
PredefinedExpr *E) {
 ///   { i16 TypeKind, i16 TypeInfo }
 /// \endcode
 ///
-/// followed by an array of i8 containing the type name. TypeKind is 0 for an
-/// integer, 1 for a floating point value, and -1 for anything else.
+/// followed by an array of i8 containing the type name with extra information
+/// for BitInt. TypeKind is TK_Integer(0) for an integer, TK_Float(1) for a
+/// floating point value, TK_BitInt(2) for BitInt and TK_Unknown(0x) for
+/// anything else.
 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
   // Only emit each type's descriptor once.
   if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
 return C;
 
-  uint16_t TypeKind = -1;
+  uint16_t TypeKind = TK_Unknown;
   uint16_t TypeInfo = 0;
+  bool IsBitInt = false;
 
   if (T->isIntegerType()) {
-TypeKind = 0;
+TypeKind = TK_Integer;
 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
(T->isSignedIntegerType() ? 1 : 0);
+// Follow suggestion from https://github.com/llvm/llvm-project/issues/64100
+// So we can write the exact amount of bits in TypeName after '\0'
+// making it .'\0'.<32-bit width>.
+if (T->isSignedIntegerType() && T->getAs()) {
+  // Do a sanity checks as we are using 32-bit type to store bit length.
+  assert((getContext().getTypeSize(T) > 0) &&
+ " non positive amount of bits in __BitInt type");
+  assert((getContext().getTypeSize(T) <= 0x) &&
+ " too many bits in __BitInt type");
+
+  // Redefine TypeKind with the actual __BitInt type if we have signed
+  // BitInt.
+  TypeKind = TK_BitInt;
+  IsBitInt = true;
+}
   } else if (T->isFloatingType()) {
-TypeKind = 1;
+TypeKind = TK_Float;
 TypeInfo = getContext().getTypeSize(T);
   }
 
@@ -3324,6 +3359,20 @@ llvm::Constant 
*CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
   DiagnosticsEngine::ak_qualtype, (intptr_t)T.getAsOpaquePtr(), 
StringRef(

[clang] [llvm] [LLVM] Fix incorrect alignment on AMDGPU variadics (PR #96370)

2024-06-25 Thread Matt Arsenault via cfe-commits

arsenm wrote:

> > > > Incrementing by align is just a bug, of course the size is the real 
> > > > value. Whether we want to continue wasting space is another 
> > > > not-correctness discussion
> > > 
> > > 
> > > Struct padding is pretty universal, AMDGPU seems the odd one out here. I 
> > > wouldn't mind it so much if it didn't require me to know which vendor I 
> > > was dealing with in the RPC implementation, but I suppose I could store 
> > > that information somewhere if we want to use a compressed option and we 
> > > know it works.
> > 
> > 
> > It's not about struct padding, but the base alignment. Any pointer 
> > increment should be alignTo(ptr + size, align), not += align. The += align 
> > won't even work for large structs
> 
> Hm, that's what I'm doing in the `printf` implementation and it doesn't work 
> without that patch. When I look at the varargs struct it didn't have any 
> padding, which explained why `alignTo(ptr + size, align)` was wrong. So, I 
> was trying to do the following, `printf("%d%ld", 1, 1l)`. With this patch I 
> get the following,

For what IR? Is the small struct getting expanded into individual scalar 
pieces? 

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


[clang] [llvm] [LLVM] Fix incorrect alignment on AMDGPU variadics (PR #96370)

2024-06-25 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

> > Hm, that's what I'm doing in the `printf` implementation and it doesn't 
> > work without that patch. When I look at the varargs struct it didn't have 
> > any padding, which explained why `alignTo(ptr + size, align)` was wrong. 
> > So, I was trying to do the following, `printf("%d%ld", 1, 1l)`. With this 
> > patch I get the following,
> 
> For what IR? Is the small struct getting expanded into individual scalar 
> pieces?

The implementation intentionally states that the alignment is always `4` in 
this case, which results in there being no padding between the four byte and 
eight byte values when put into a `void *` buffer for varargs. You should be 
able to see it in the changes to the tests. Unfortunately, @JonChesterfield is 
on vacation so I can't ask about this as it seems to be a deliberate choice, 
but I don't know how it's correct.

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


[clang] [Clang] Clarify diagnostic notes for implicitly generated deduction guides (PR #96084)

2024-06-25 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 updated 
https://github.com/llvm/llvm-project/pull/96084

>From 23844cd8b8fad07bce0c34f58430322090c5a793 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Wed, 19 Jun 2024 23:25:13 +0800
Subject: [PATCH 1/5] [Clang] Add diagnostic notes for implcitly generated
 deduction guides

---
 clang/docs/ReleaseNotes.rst   |  3 ++
 .../clang/Basic/DiagnosticSemaKinds.td|  1 +
 clang/lib/Sema/SemaOverload.cpp   | 30 +++
 clang/test/CXX/drs/cwg26xx.cpp|  3 ++
 .../CXX/expr/expr.post/expr.type.conv/p1.cpp  |  2 +-
 .../over.match.class.deduct/p2.cpp|  2 +-
 .../temp.deduct/temp.deduct.call/p3-0x.cpp|  4 +--
 clang/test/Modules/template_name_lookup.cpp   |  2 ++
 clang/test/PCH/cxx-explicit-specifier.cpp |  2 +-
 clang/test/Sema/tls_alignment.cpp |  4 ++-
 ...xx1z-class-template-argument-deduction.cpp |  6 ++--
 clang/test/SemaCXX/cxx20-ctad-type-alias.cpp  | 17 +--
 clang/test/SemaCXX/cxx2a-explicit-bool.cpp|  2 ++
 clang/test/SemaCXX/gh65522.cpp|  3 +-
 ...deduction-guide-as-template-candidates.cpp |  4 ++-
 .../lookup-template-name-extern-CXX.cpp   |  6 ++--
 .../aggregate-deduction-candidate.cpp | 24 ---
 clang/test/SemaTemplate/class-template-id.cpp |  2 ++
 clang/test/SemaTemplate/ctad.cpp  |  6 ++--
 clang/test/SemaTemplate/deduction-crash.cpp   |  3 +-
 clang/test/SemaTemplate/deduction-guide.cpp   |  6 ++--
 .../nested-implicit-deduction-guides.cpp  |  3 ++
 clang/test/SemaTemplate/temp_arg.cpp  |  4 ++-
 23 files changed, 108 insertions(+), 31 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 69aea6c21ad39..423f1e9198948 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -580,6 +580,9 @@ Improvements to Clang's diagnostics
 - Clang no longer emits a "declared here" note for a builtin function that has 
no declaration in source.
   Fixes #GH93369.
 
+- Clang now emits implicit deduction guides corresponding to non-user-defined 
constructors while at a failure
+  of overload resolution.
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ab223f2b806d5..a65491b0c4399 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2405,6 +2405,7 @@ def err_selected_explicit_constructor : Error<
   "chosen constructor is explicit in copy-initialization">;
 def note_explicit_ctor_deduction_guide_here : Note<
   "explicit %select{constructor|deduction guide}0 declared here">;
+def note_implicit_deduction_guide : Note<"implicit deduction guide declared as 
'%0'">;
 
 // C++11 auto
 def warn_cxx98_compat_auto_type_specifier : Warning<
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index fb4ff72e42eb5..31b908eb3cc3c 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -40,6 +40,7 @@
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/STLForwardCompat.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
@@ -12114,6 +12115,35 @@ static void NoteFunctionCandidate(Sema &S, 
OverloadCandidate *Cand,
 return;
   }
 
+  // If this is an implicit deduction guide against a non-user-defined
+  // constructor, add a note for it. These deduction guides nor their
+  // corresponding constructors are not explicitly spelled in the source code,
+  // and simply producing a deduction failure note around the heading of the
+  // enclosing RecordDecl is confusing.
+  //
+  // We prefer adding such notes at the end of the last deduction failure
+  // reason because duplicate code snippets appearing in the diagnostic
+  // are likely becoming noisy.
+  auto _ = llvm::make_scope_exit([&] {
+auto *DG = dyn_cast(Fn);
+if (!DG || !DG->isImplicit() || DG->getCorrespondingConstructor())
+  return;
+std::string FunctionProto;
+llvm::raw_string_ostream OS(FunctionProto);
+FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
+// This also could be an instantiation. Find out the primary template.
+if (!Template) {
+  FunctionDecl *Pattern = DG->getTemplateInstantiationPattern();
+  assert(Pattern && Pattern->getDescribedFunctionTemplate() &&
+ "Cannot find the associated function template of "
+ "CXXDeductionGuideDecl?");
+  Template = Pattern->getDescribedFunctionTemplate();
+}
+Template->print(OS);
+S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
+<< FunctionProto;
+  });
+
   switch (Cand->FailureKind) {
   case ovl_fail_too_many_arguments:
   case ovl_fail_too_few_arguments:
dif

[clang] [Clang] Introduce 'clang-nvlink-wrappaer' to work around 'nvlink' (PR #96561)

2024-06-25 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/96561

>From 6c70e542bbb355160b833ede6f86be0366953b88 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Mon, 24 Jun 2024 15:14:52 -0500
Subject: [PATCH] [Clang] Introduce 'clang-nvlink-wrappaer' to work around
 'nvlink'

Summary:
The `clang-nvlink-wrapper` is a utility that I removed awhile back
during the transition to the new driver. This patch adds back in a new,
upgraded version that does LTO + archive linking. It's not an easy
choice to reintroduce something I happily deleted, but this is the only
way to move forward with improving GPU support in LLVM.

While NVIDIA provides a linker called 'nvlink', its main interface is
very difficult to work with. It does not provide LTO, or static linking,
requires all files to be named a non-standard `.cubin`, and rejects link
jobs that other linkers would be fine with (i.e empty). I have spent a
great deal of time hacking around this in the GPU `libc` implementation,
where I deliberately avoid LTO and static linking and have about 100
lines of hacky CMake dedicated to storing these files in a format that
the clang-linker-wrapper accepts to avoid this limitation.

The main reason I want to re-intorudce this tool is because I am
planning on creating a more standard C/C++ toolchain for GPUs to use.
This will install files like the following.
```
/lib/nvptx64-nvidia-cuda/libc.a
/lib/nvptx64-nvidia-cuda/libc++.a
/lib/nvptx64-nvidia-cuda/libomp.a
/lib/clang/19/lib/nvptx64-nvidia-cuda/libclang_rt.builtins.a
```
Linking in these libraries will then simply require passing `-lc` like
is already done for non-GPU toolchains. However, this doesn't work with
the currently deficient `nvlink` linker, so I consider this a blocking
issue to massively improving the state of building GPU libraries.

In the future we may be able to convince NVIDIA to port their linker to
`ld.lld`, but for now this is the only workable solution that allows us
to hack around the weird behavior of their closed-source software.
---
 clang/lib/Driver/ToolChains/Cuda.cpp  |  61 +-
 clang/lib/Driver/ToolChains/Cuda.h|   3 +
 clang/test/Driver/cuda-cross-compiling.c  |   8 +-
 clang/test/Driver/nvlink-wrapper.c|  65 ++
 clang/test/lit.cfg.py |   1 +
 clang/tools/CMakeLists.txt|   1 +
 .../tools/clang-nvlink-wrapper/CMakeLists.txt |  44 ++
 .../ClangNVLinkWrapper.cpp| 671 ++
 .../tools/clang-nvlink-wrapper/NVLinkOpts.td  |  68 ++
 9 files changed, 865 insertions(+), 57 deletions(-)
 create mode 100644 clang/test/Driver/nvlink-wrapper.c
 create mode 100644 clang/tools/clang-nvlink-wrapper/CMakeLists.txt
 create mode 100644 clang/tools/clang-nvlink-wrapper/ClangNVLinkWrapper.cpp
 create mode 100644 clang/tools/clang-nvlink-wrapper/NVLinkOpts.td

diff --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index 2dfc7457b0ac7..54724cc1ad08e 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -461,13 +461,6 @@ void NVPTX::Assembler::ConstructJob(Compilation &C, const 
JobAction &JA,
   CmdArgs.push_back("--output-file");
   std::string OutputFileName = TC.getInputFilename(Output);
 
-  // If we are invoking `nvlink` internally we need to output a `.cubin` file.
-  // FIXME: This should hopefully be removed if NVIDIA updates their tooling.
-  if (!C.getInputArgs().getLastArg(options::OPT_c)) {
-SmallString<256> Filename(Output.getFilename());
-llvm::sys::path::replace_extension(Filename, "cubin");
-OutputFileName = Filename.str();
-  }
   if (Output.isFilename() && OutputFileName != Output.getFilename())
 C.addTempFile(Args.MakeArgString(OutputFileName));
 
@@ -618,6 +611,11 @@ void NVPTX::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   // Add standard library search paths passed on the command line.
   Args.AddAllArgs(CmdArgs, options::OPT_L);
   getToolChain().AddFilePathLibArgs(Args, CmdArgs);
+  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
+
+  if (C.getDriver().isUsingLTO())
+addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],
+  C.getDriver().getLTOMode() == LTOK_Thin);
 
   // Add paths for the default clang library path.
   SmallString<256> DefaultLibPath =
@@ -625,51 +623,12 @@ void NVPTX::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
   CmdArgs.push_back(Args.MakeArgString(Twine("-L") + DefaultLibPath));
 
-  for (const auto &II : Inputs) {
-if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR 
||
-II.getType() == types::TY_LTO_BC || II.getType() == types::TY_LLVM_BC) 
{
-  C.getDriver().Diag(diag::err_drv_no_linker_llvm_support)
-  << getToolChain().getTripleString();
-  continue;
-}
-
-// The 'nvlink' application perfor

[clang] [Clang] Clarify diagnostic notes for implicitly generated deduction guides (PR #96084)

2024-06-25 Thread Younan Zhang via cfe-commits


@@ -108,8 +108,11 @@ struct Foo {
   Foo(T const (&)[N]);
 };
 
+// FIXME: Prefer non-canonical template arguments in the deduction guide?
 template 
 using Bar = Foo; // expected-note {{candidate template ignored: 
couldn't infer template argument 'X'}} \
+   // expected-note {{implicit deduction guide 
declared as 'template  Bar(Foo) -> Foo'}} \
+   // expected-note {{implicit deduction guide 
declared as 'template  Bar(const type-parameter-0-0 
(&)[sizeof(type-parameter-0-0)]) -> Foo'}} \
// expected-note {{candidate template ignored: 
constraints not satisfied [with X = int]}} \

zyn0217 wrote:

@hokein I think the `constraints not satisfied` is still a bit confusing after 
#92389? There is no constraint explicitly written in the code, although the 
note actually refers to the implicit constraint `__is_deducible`.

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


[clang] [Clang] Introduce 'clang-nvlink-wrappaer' to work around 'nvlink' (PR #96561)

2024-06-25 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

@MaskRay So, I think my symbol resolution is (unsurprisingly) subtly broken. Is 
there a canonical way to handle this? I first thought that we could simply 
perform the symbol resolutions as normal for every file, but keep track of 
which symbols were "lazy". However, I couldn't figure out how to then tell if a 
lazy symbol should be extracted or not because there's no information on which 
files use which symbols. Maybe I just scan all the files and see if they 
reference a symbol that's marked defined and lazy?

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


[clang] [clang] Emit bad shift warnings (PR #70307)

2024-06-25 Thread Budimir Aranđelović via cfe-commits

https://github.com/budimirarandjelovicsyrmia updated 
https://github.com/llvm/llvm-project/pull/70307

From 39c314b060959578ccfe70c5ef2aa5aba5688c11 Mon Sep 17 00:00:00 2001
From: budimirarandjelovicsyrmia 
Date: Thu, 26 Oct 2023 10:39:52 +0200
Subject: [PATCH] [clang] Emit bad shift warnings

---
 clang/lib/AST/ExprConstant.cpp |  7 +++
 clang/lib/Sema/SemaExpr.cpp| 17 +
 clang/test/C/drs/dr0xx.c   |  3 ++-
 clang/test/C/drs/dr2xx.c   |  4 +++-
 clang/test/Sema/builtins.c |  6 --
 clang/test/Sema/code_align.c   |  7 ---
 clang/test/Sema/constant-builtins-2.c  |  8 
 clang/test/Sema/shift-count-negative.c | 10 ++
 clang/test/Sema/shift-count-overflow.c |  7 +++
 clang/test/Sema/shift-negative-value.c | 10 ++
 clang/test/Sema/vla-2.c|  6 --
 clang/test/SemaCXX/enum.cpp|  6 --
 clang/test/SemaCXX/shift.cpp   |  2 +-
 13 files changed, 73 insertions(+), 20 deletions(-)
 create mode 100644 clang/test/Sema/shift-count-negative.c
 create mode 100644 clang/test/Sema/shift-count-overflow.c
 create mode 100644 clang/test/Sema/shift-negative-value.c

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index fe4b9a569ab874..80c4886e5d94ad 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2858,6 +2858,9 @@ static bool handleIntIntBinOp(EvalInfo &Info, const 
BinaryOperator *E,
   else if (LHS.countl_zero() < SA)
 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
 }
+if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
+Info.getLangOpts().CPlusPlus)
+  return false;
 Result = LHS << SA;
 return true;
   }
@@ -2881,6 +2884,10 @@ static bool handleIntIntBinOp(EvalInfo &Info, const 
BinaryOperator *E,
 if (SA != RHS)
   Info.CCEDiag(E, diag::note_constexpr_large_shift)
 << RHS << E->getType() << LHS.getBitWidth();
+
+if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
+Info.getLangOpts().CPlusPlus)
+  return false;
 Result = LHS >> SA;
 return true;
   }
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 4a2f3a65eac96f..9f5ec9f432df93 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -11256,7 +11256,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   if (Right.isNegative()) {
 S.DiagRuntimeBehavior(Loc, RHS.get(),
   S.PDiag(diag::warn_shift_negative)
-<< RHS.get()->getSourceRange());
+  << RHS.get()->getSourceRange());
 return;
   }
 
@@ -11271,7 +11271,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   if (Right.uge(LeftSize)) {
 S.DiagRuntimeBehavior(Loc, RHS.get(),
   S.PDiag(diag::warn_shift_gt_typewidth)
-<< RHS.get()->getSourceRange());
+  << RHS.get()->getSourceRange());
 return;
   }
 
@@ -11304,7 +11304,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   if (Left.isNegative()) {
 S.DiagRuntimeBehavior(Loc, LHS.get(),
   S.PDiag(diag::warn_shift_lhs_negative)
-<< LHS.get()->getSourceRange());
+  << LHS.get()->getSourceRange());
 return;
   }
 
@@ -17138,11 +17138,20 @@ Sema::VerifyIntegerConstantExpression(Expr *E, 
llvm::APSInt *Result,
   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
   // in the non-ICE case.
   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
+SmallVector Notes;
 if (Result)
-  *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
+  *Result = E->EvaluateKnownConstIntCheckOverflow(Context, &Notes);
 if (!isa(E))
   E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
  : ConstantExpr::Create(Context, E);
+
+if (Notes.size() && !Diagnoser.Suppress) {
+  Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
+  for (const PartialDiagnosticAt &Note : Notes)
+Diag(Note.first, Note.second);
+  return ExprError();
+}
+
 return E;
   }
 
diff --git a/clang/test/C/drs/dr0xx.c b/clang/test/C/drs/dr0xx.c
index 36de32a93da95d..530c216722cc3b 100644
--- a/clang/test/C/drs/dr0xx.c
+++ b/clang/test/C/drs/dr0xx.c
@@ -430,7 +430,8 @@ void dr081(void) {
   /* Demonstrate that we don't crash when left shifting a signed value; that's
* implementation defined behavior.
*/
- _Static_assert(-1 << 1 == -2, "fail"); /* Didn't shift a zero into the "sign 
bit". */
+ _Static_assert(-1 << 1 == -2, "fail"); /* c89only-error {{static assertion 
expression is not an integral constant expression}}
+   

[clang] [compiler-rt] [ubsan] Display correct runtime messages for negative _BitInt (PR #96240)

2024-06-25 Thread via cfe-commits

https://github.com/earnol updated 
https://github.com/llvm/llvm-project/pull/96240

>From 6e0294e5debf0fe694fcf56c8cd2d35e7225d639 Mon Sep 17 00:00:00 2001
From: Vladislav Aranov 
Date: Fri, 24 May 2024 11:39:35 -0400
Subject: [PATCH] [ubsan] Display correct runtime messages for negative _BitInt

Without this patch compiler-rt ubsan library has a bug displaying
incorrect values for variables of the _BitInt (previousely called
_ExtInt) type. This patch affects both: generation of metadata
inside code generator and runtime part. The runtime part provided only
for i386 and x86_64 runtimes. Other runtimes should be updated to take
full benefit of this patch.
The patch is constructed the way to be backward compatible and
int and float type runtime diagnostics should be unaffected for not
yet updated runtimes.

Co-authored-by: Aaron Ballman 
---
 clang/lib/CodeGen/CGExpr.cpp  |  59 +-
 clang/test/CodeGen/bit-int-ubsan.c|  96 ++
 compiler-rt/lib/ubsan/ubsan_value.cpp |  17 +-
 compiler-rt/lib/ubsan/ubsan_value.h   |  34 +++-
 .../ubsan/TestCases/Integer/bit-int-pass.c|  42 +
 .../test/ubsan/TestCases/Integer/bit-int.c| 170 ++
 6 files changed, 405 insertions(+), 13 deletions(-)
 create mode 100644 clang/test/CodeGen/bit-int-ubsan.c
 create mode 100644 compiler-rt/test/ubsan/TestCases/Integer/bit-int-pass.c
 create mode 100644 compiler-rt/test/ubsan/TestCases/Integer/bit-int.c

diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 534f46da74862..cebfe98eda97f 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -41,6 +41,7 @@
 #include "llvm/IR/MatrixBuilder.h"
 #include "llvm/Passes/OptimizationLevel.h"
 #include "llvm/Support/ConvertUTF.h"
+#include "llvm/Support/Endian.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/SaveAndRestore.h"
@@ -64,6 +65,22 @@ static llvm::cl::opt ClSanitizeGuardChecks(
 "ubsan-guard-checks", llvm::cl::Optional,
 llvm::cl::desc("Guard UBSAN checks with `llvm.allow.ubsan.check()`."));
 
+//======//
+//Defines for metadata
+//======//
+
+// Those values are crucial to be the SAME as in ubsan runtime library.
+enum VariableTypeDescriptorKind : uint16_t {
+  /// An integer type.
+  TK_Integer = 0x,
+  /// A floating-point type.
+  TK_Float = 0x0001,
+  /// An _BitInt(N) type.
+  TK_BitInt = 0x0002,
+  /// Any other type. The value representation is unspecified.
+  TK_Unknown = 0x
+};
+
 //======//
 //Miscellaneous Helper Methods
 //======//
@@ -3298,22 +3315,40 @@ LValue CodeGenFunction::EmitPredefinedLValue(const 
PredefinedExpr *E) {
 ///   { i16 TypeKind, i16 TypeInfo }
 /// \endcode
 ///
-/// followed by an array of i8 containing the type name. TypeKind is 0 for an
-/// integer, 1 for a floating point value, and -1 for anything else.
+/// followed by an array of i8 containing the type name with extra information
+/// for BitInt. TypeKind is TK_Integer(0) for an integer, TK_Float(1) for a
+/// floating point value, TK_BitInt(2) for BitInt and TK_Unknown(0x) for
+/// anything else.
 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
   // Only emit each type's descriptor once.
   if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
 return C;
 
-  uint16_t TypeKind = -1;
+  uint16_t TypeKind = TK_Unknown;
   uint16_t TypeInfo = 0;
+  bool IsBitInt = false;
 
   if (T->isIntegerType()) {
-TypeKind = 0;
+TypeKind = TK_Integer;
 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
(T->isSignedIntegerType() ? 1 : 0);
+// Follow suggestion from https://github.com/llvm/llvm-project/issues/64100
+// So we can write the exact amount of bits in TypeName after '\0'
+// making it .'\0'.<32-bit width>.
+if (T->isSignedIntegerType() && T->getAs()) {
+  // Do a sanity checks as we are using 32-bit type to store bit length.
+  assert((getContext().getTypeSize(T) > 0) &&
+ " non positive amount of bits in __BitInt type");
+  assert((getContext().getTypeSize(T) <= 0x) &&
+ " too many bits in __BitInt type");
+
+  // Redefine TypeKind with the actual __BitInt type if we have signed
+  // BitInt.
+  TypeKind = TK_BitInt;
+  IsBitInt = true;
+}
   } else if (T->isFloatingType()) {
-TypeKind = 1;
+TypeKind = TK_Float;
 TypeInfo = getContext().getTypeSize(T);
   }
 
@@ -3324,6 +3359,20 @@ llvm::Constant 
*CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
   DiagnosticsEngine::ak_qualtype, (intptr_t)T.getAsOpaquePtr(), 
StringRef(

[clang] [clang][FMV] Do not omit explicit default target_version attribute. (PR #96628)

2024-06-25 Thread Alexandros Lamprineas via cfe-commits

https://github.com/labrinea created 
https://github.com/llvm/llvm-project/pull/96628

Fixes a crash and cleans up some dead code.

namespace Foo {
int bar();
__attribute((target_version("default"))) int bar() { return 0; } 
__attribute((target_version("mops"))) int bar() { return 1; }
}

$ clang++ --target=aarch64-linux-gnu --rtlib=compiler-rt fmv.cpp

None multiversion type isn't valid here
UNREACHABLE executed at clang/lib/CodeGen/CodeGenModule.cpp:1840! ...
getMangledNameImpl
clang::CodeGen::CodeGenModule::getMangledName
clang::CodeGen::CodeGenModule::EmitGlobal

>From ff4635208e9cd83c6735c95ebf12125ca737029a Mon Sep 17 00:00:00 2001
From: Alexandros Lamprineas 
Date: Tue, 25 Jun 2024 00:27:45 +0100
Subject: [PATCH] [clang][FMV] Do not omit explicit default target_version
 attribute.

Fixes a crash and cleans up some dead code.

namespace Foo {
int bar();
__attribute((target_version("default"))) int bar() { return 0; }
__attribute((target_version("mops"))) int bar() { return 1; }
}

$ clang++ --target=aarch64-linux-gnu --rtlib=compiler-rt fmv.cpp

None multiversion type isn't valid here
UNREACHABLE executed at clang/lib/CodeGen/CodeGenModule.cpp:1840!
...
getMangledNameImpl
clang::CodeGen::CodeGenModule::getMangledName
clang::CodeGen::CodeGenModule::EmitGlobal
---
 clang/include/clang/Sema/Sema.h  |  3 +-
 clang/lib/Sema/SemaDecl.cpp  | 45 +---
 clang/lib/Sema/SemaDeclAttr.cpp  | 16 ++---
 clang/test/CodeGen/attr-target-version.c | 88 
 clang/test/CodeGenCXX/fmv-namespace.cpp  | 60 
 clang/test/Sema/attr-target-version.c|  5 +-
 6 files changed, 118 insertions(+), 99 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 2e7af0f691cbb..31bb81705a742 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3786,8 +3786,7 @@ class Sema final : public SemaBase {
 StringRef Name);
 
   bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
-  bool checkTargetVersionAttr(SourceLocation LiteralLoc, Decl *D,
-  StringRef &Str, bool &isDefault);
+  bool checkTargetVersionAttr(SourceLocation Loc, Decl *D, StringRef Str);
   bool checkTargetClonesAttrString(
   SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal,
   Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault,
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 029ccf944c513..572c46eed1aaa 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -11465,6 +11465,10 @@ static bool CheckMultiVersionFirstFunction(Sema &S, 
FunctionDecl *FD) {
   // otherwise it is treated as a normal function.
   if (TA && !TA->isDefaultVersion())
 return false;
+  // The target_version attribute only causes Multiversioning if this
+  // declaration is NOT the default version.
+  if (TVA && TVA->isDefaultVersion())
+return false;
 
   if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
 FD->setInvalidDecl();
@@ -11498,11 +11502,9 @@ static void patchDefaultTargetVersion(FunctionDecl 
*From, FunctionDecl *To) {
 
   if (MVKindTo == MultiVersionKind::None &&
   (MVKindFrom == MultiVersionKind::TargetVersion ||
-   MVKindFrom == MultiVersionKind::TargetClones)) {
-To->setIsMultiVersion();
+   MVKindFrom == MultiVersionKind::TargetClones))
 To->addAttr(TargetVersionAttr::CreateImplicit(
 To->getASTContext(), "default", To->getSourceRange()));
-  }
 }
 
 static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
@@ -11523,10 +11525,16 @@ static bool CheckTargetCausesMultiVersioning(Sema &S, 
FunctionDecl *OldFD,
   const auto *OldTVA = OldFD->getAttr();
   // If the old decl is NOT MultiVersioned yet, and we don't cause that
   // to change, this is a simple redeclaration.
-  if ((NewTA && !NewTA->isDefaultVersion() &&
-   (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
-  (NewTVA && !NewTVA->isDefaultVersion() &&
-   (!OldTVA || OldTVA->getName() == NewTVA->getName(
+  if (NewTA && !NewTA->isDefaultVersion() &&
+  (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
+return false;
+
+  // The target_version attribute only causes Multiversioning if this
+  // declaration is NOT the default version. Moreover, the old declaration
+  // must be the default version (either explicitly via the attribute,
+  // or implicitly without it).
+  if (NewTVA &&
+  (NewTVA->isDefaultVersion() || (OldTVA && !OldTVA->isDefaultVersion(
 return false;
 
   // Otherwise, this decl causes MultiVersioning.
@@ -11543,8 +11551,7 @@ static bool CheckTargetCausesMultiVersioning(Sema &S, 
FunctionDecl *OldFD,
   }
 
   // If this is 'default', permit the forward declaration.
-  if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
-  (NewTVA && NewTVA->isDefaultVersion() && !OldTV

[clang] [clang][FMV] Do not omit explicit default target_version attribute. (PR #96628)

2024-06-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alexandros Lamprineas (labrinea)


Changes

Fixes a crash and cleans up some dead code.

namespace Foo {
int bar();
__attribute((target_version("default"))) int bar() { return 0; } 
__attribute((target_version("mops"))) int bar() { return 1; }
}

$ clang++ --target=aarch64-linux-gnu --rtlib=compiler-rt fmv.cpp

None multiversion type isn't valid here
UNREACHABLE executed at clang/lib/CodeGen/CodeGenModule.cpp:1840! ...
getMangledNameImpl
clang::CodeGen::CodeGenModule::getMangledName
clang::CodeGen::CodeGenModule::EmitGlobal

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


6 Files Affected:

- (modified) clang/include/clang/Sema/Sema.h (+1-2) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+18-27) 
- (modified) clang/lib/Sema/SemaDeclAttr.cpp (+5-11) 
- (modified) clang/test/CodeGen/attr-target-version.c (+44-44) 
- (modified) clang/test/CodeGenCXX/fmv-namespace.cpp (+47-13) 
- (modified) clang/test/Sema/attr-target-version.c (+3-2) 


``diff
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 2e7af0f691cbb..31bb81705a742 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3786,8 +3786,7 @@ class Sema final : public SemaBase {
 StringRef Name);
 
   bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
-  bool checkTargetVersionAttr(SourceLocation LiteralLoc, Decl *D,
-  StringRef &Str, bool &isDefault);
+  bool checkTargetVersionAttr(SourceLocation Loc, Decl *D, StringRef Str);
   bool checkTargetClonesAttrString(
   SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal,
   Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault,
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 029ccf944c513..572c46eed1aaa 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -11465,6 +11465,10 @@ static bool CheckMultiVersionFirstFunction(Sema &S, 
FunctionDecl *FD) {
   // otherwise it is treated as a normal function.
   if (TA && !TA->isDefaultVersion())
 return false;
+  // The target_version attribute only causes Multiversioning if this
+  // declaration is NOT the default version.
+  if (TVA && TVA->isDefaultVersion())
+return false;
 
   if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
 FD->setInvalidDecl();
@@ -11498,11 +11502,9 @@ static void patchDefaultTargetVersion(FunctionDecl 
*From, FunctionDecl *To) {
 
   if (MVKindTo == MultiVersionKind::None &&
   (MVKindFrom == MultiVersionKind::TargetVersion ||
-   MVKindFrom == MultiVersionKind::TargetClones)) {
-To->setIsMultiVersion();
+   MVKindFrom == MultiVersionKind::TargetClones))
 To->addAttr(TargetVersionAttr::CreateImplicit(
 To->getASTContext(), "default", To->getSourceRange()));
-  }
 }
 
 static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
@@ -11523,10 +11525,16 @@ static bool CheckTargetCausesMultiVersioning(Sema &S, 
FunctionDecl *OldFD,
   const auto *OldTVA = OldFD->getAttr();
   // If the old decl is NOT MultiVersioned yet, and we don't cause that
   // to change, this is a simple redeclaration.
-  if ((NewTA && !NewTA->isDefaultVersion() &&
-   (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
-  (NewTVA && !NewTVA->isDefaultVersion() &&
-   (!OldTVA || OldTVA->getName() == NewTVA->getName(
+  if (NewTA && !NewTA->isDefaultVersion() &&
+  (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
+return false;
+
+  // The target_version attribute only causes Multiversioning if this
+  // declaration is NOT the default version. Moreover, the old declaration
+  // must be the default version (either explicitly via the attribute,
+  // or implicitly without it).
+  if (NewTVA &&
+  (NewTVA->isDefaultVersion() || (OldTVA && !OldTVA->isDefaultVersion(
 return false;
 
   // Otherwise, this decl causes MultiVersioning.
@@ -11543,8 +11551,7 @@ static bool CheckTargetCausesMultiVersioning(Sema &S, 
FunctionDecl *OldFD,
   }
 
   // If this is 'default', permit the forward declaration.
-  if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
-  (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
+  if (NewTA && NewTA->isDefaultVersion() && !OldTA) {
 Redeclaration = true;
 OldDecl = OldFD;
 OldFD->setIsMultiVersion();
@@ -11947,24 +11954,8 @@ static bool CheckMultiVersionFunction(Sema &S, 
FunctionDecl *NewFD,
 
   FunctionDecl *OldFD = OldDecl->getAsFunction();
 
-  if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
-if (NewTVA || !OldFD->getAttr())
-  return false;
-if (!NewFD->getType()->getAs()) {
-  // Multiversion declaration doesn't have prototype.
-  S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
-  NewFD->setInvalidDecl();
-} else {
-  // No "target

[clang] [clang][FMV] Do not omit explicit default target_version attribute. (PR #96628)

2024-06-25 Thread Alexandros Lamprineas via cfe-commits

labrinea wrote:

Alternative one liner:
```
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index dd4a665ebc78..0c96a6de091a 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3763,7 +3763,7 @@ void CodeGenModule::EmitGlobal(GlobalDecl GD) {
 // Forward declarations are emitted lazily on first use.
 if (!FD->doesThisDeclarationHaveABody()) {
   if (!FD->doesDeclarationForceExternallyVisibleDefinition() &&
-  (!FD->isMultiVersion() ||
+  (FD->getMultiVersionKind() == MultiVersionKind::None ||
!FD->getASTContext().getTargetInfo().getTriple().isAArch64()))
 return;
```
but I believe not emitting the explicit default and then patching it later is a 
hack.

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


[clang] Add documentation for `__builtin_object_size`. (PR #96573)

2024-06-25 Thread Allan Jude via cfe-commits


@@ -5368,16 +5368,85 @@ The ``#pragma comment(lib, ...)`` directive is 
supported on all ELF targets.
 The second parameter is the library name (without the traditional Unix prefix 
of
 ``lib``).  This allows you to provide an implicit link of dependent libraries.
 
-Evaluating Object Size Dynamically
-==
+Evaluating Object Size
+==
+
+Clang supports the builtins ``__builtin_object_size`` and
+``__builtin_dynamic_object_size``. The semantics are compatible with GCC's
+builtins of the same names, but the details are slightly different.
+
+.. code-block:: c
+
+  size_t __builtin_[dynamic_]object_size(const void *ptr, int type)
+
+Returns the number of accessible bytes ``n`` past ``ptr``. The value returned
+depends on ``type``, which is required to be an integer constant between 0 and
+3:
+
+* If ``type & 2 == 0``, the least ``n`` is returned such that accesses to
+  ``(const char*)ptr + n`` and beyond are known to be out of bounds. This is
+  ``(size_t)-1`` if no better bound is known.
+* If ``type & 2 == 2``, the greatest ``n`` is returned such that accesses to
+  ``(const char*)ptr + i`` are known to be in bounds, for 0 <= ``i`` < ``n``.
+  This is ``(size_t)0`` if no better bound is known.
 
-Clang supports the builtin ``__builtin_dynamic_object_size``, the semantics are
-the same as GCC's ``__builtin_object_size`` (which Clang also supports), but
-``__builtin_dynamic_object_size`` can evaluate the object's size at runtime.
-``__builtin_dynamic_object_size`` is meant to be used as a drop-in replacement
-for ``__builtin_object_size`` in libraries that support it.
+.. code-block:: c
+
+  char small[10], large[100];
+  bool cond;
+  // Returns 100: writes of more than 100 bytes are known to be out of bounds.
+  int n100 = __builtin_object_size(cond ? small : large, 0);
+  // Returns 10: writes of 10 or fewer bytes are known to be in bounds.
+  int n10 = __builtin_object_size(cond ? small : large, 2);
+
+* If ``type & 1 == 0``, pointers are considered to be in bounds if they point
+  into the same storage as ``ptr`` -- that is, the same stack object, global
+  variable, or heap allocation.
+* If ``type & 1 == 1``, pointers are considered to be in bounds if they point
+  to the same subobject that ``ptr`` points to. If ``ptr`` points to an array
+  element, other elements of the same array, but not of enclosing arrays, are
+  considered in bounds.
+
+.. code-block:: c
+
+  struct X { char a, b, c; } x;
+  static_assert(__builtin_object_size(&x, 0) == 3);
+  static_assert(__builtin_object_size(&x.b, 0) == 2);
+  static_assert(__builtin_object_size(&x.b, 1) == 1);
+
+.. code-block:: c
 
-For instance, here is a program that ``__builtin_dynamic_object_size`` will 
make
+  char a[10][10][10];
+  static_assert(__builtin_object_size(&a, 1) == 1000);
+  static_assert(__builtin_object_size(&a[1], 1) == 900);
+  static_assert(__builtin_object_size(&a[1][1], 1) == 90);
+  static_assert(__builtin_object_size(&a[1][1][1], 1) == 9);
+
+The values returned by this builtin are a best effort conservative 
approximation
+of the correct answers. When ``type & 2 == 0``, the true value is less than or
+equal to the value returned by the builtin, and when ``type & 2 == 1``, the 
true
+value is greater than or equal to the value returned by the builtin.
+
+For ``__builtin_object_size``, the value is determined entirely at compile 
time.
+With optimization enabled, better results will be produced, especially when the
+call to ``__builtin_object_size`` is in a different function from the formation
+of the pointer. Unlike in GCC, enabling optimization in Clang does not allow
+more information about subobjects to be determined, so the ``type & 1 == 1``
+case will often give imprecise results when used across a function call 
boundary
+even when optimization is enabled.
+
+`The ``pass_object_size`` and ``pass_dynamic_object_size`` attributes 
`_

allanjude wrote:

the leading ` here makes `pass_object_size` not get the right treatment

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


[clang] Add documentation for `__builtin_object_size`. (PR #96573)

2024-06-25 Thread Allan Jude via cfe-commits

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


[clang] [clang][FMV] Do not omit explicit default target_version attribute. (PR #96628)

2024-06-25 Thread Alexandros Lamprineas via cfe-commits

labrinea wrote:

@ilinpv, @DanielKristofKiss, the patch 
https://github.com/llvm/llvm-project/pull/65671/files doesn't seem right. I 
have basically reverted it with my change, ensuring the original crash you were 
trying to fix doesn't occur. FYI `MVKind == MultiVersionKind::None` is 
equivallent to `NewTVA == nullptr` in that context.

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


[clang] [Clang] Access tls_guard via llvm.threadlocal.address (PR #96633)

2024-06-25 Thread via cfe-commits

https://github.com/nikola-tesic-ns created 
https://github.com/llvm/llvm-project/pull/96633

This patch fixes compiler generated code in `tls_init` function to access TLS 
variable (`tls_guard`) via llvm.threadlocal.address intrinsic.

Related discussion:
https://discourse.llvm.org/t/address-thread-identification-problems-with-coroutine/62015/57?u=ntesic

>From 41427a3de345517025477257bfd4f614f06cbcfe Mon Sep 17 00:00:00 2001
From: Nikola Tesic 
Date: Tue, 25 Jun 2024 15:58:18 +0300
Subject: [PATCH] [Clang] Access tls_guard via llvm.threadlocal.address

This patch fixes compiler generated code in `tls_init` function to access
TLS variable (`tls_guard`) via llvm.threadlocal.address intrinsic.
---
 clang/lib/CodeGen/CGDeclCXX.cpp   | 29 +++---
 clang/test/CodeGenCXX/cxx11-thread-local.cpp  |  9 --
 .../static-initializer-branch-weights.cpp |  3 +-
 clang/test/OpenMP/parallel_copyin_codegen.cpp |  6 ++--
 .../OpenMP/target_has_device_addr_codegen.cpp |  6 ++--
 clang/test/OpenMP/threadprivate_codegen.cpp   | 30 ---
 6 files changed, 55 insertions(+), 28 deletions(-)

diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index e18b339b31d24..0663a083bf3e8 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -1059,9 +1059,10 @@ 
CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
 if (Guard.isValid()) {
   // If we have a guard variable, check whether we've already performed
   // these initializations. This happens for TLS initialization functions.
-  llvm::Value *GuardVal = Builder.CreateLoad(Guard);
-  llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
- "guard.uninitialized");
+  llvm::Value *GuardVal = EmitLoadOfScalar(
+  MakeAddrLValue(Guard, getContext().IntTy), SourceLocation());
+  llvm::Value *Uninit =
+  Builder.CreateIsNull(GuardVal, "guard.uninitialized");
   llvm::BasicBlock *InitBlock = createBasicBlock("init");
   ExitBlock = createBasicBlock("exit");
   EmitCXXGuardedInitBranch(Uninit, InitBlock, ExitBlock,
@@ -1070,13 +1071,21 @@ 
CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
   // Mark as initialized before initializing anything else. If the
   // initializers use previously-initialized thread_local vars, that's
   // probably supposed to be OK, but the standard doesn't say.
-  Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), 
Guard);
-
-  // The guard variable can't ever change again.
-  EmitInvariantStart(
-  Guard.getPointer(),
-  CharUnits::fromQuantity(
-  CGM.getDataLayout().getTypeAllocSize(GuardVal->getType(;
+  EmitStoreOfScalar(llvm::ConstantInt::get(GuardVal->getType(), 1),
+MakeAddrLValue(Guard, getContext().IntTy));
+
+  // Emit invariant start for TLS guard address.
+  if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
+uint64_t Width =
+CGM.getDataLayout().getTypeAllocSize(GuardVal->getType());
+llvm::Value *TLSAddr = Guard.getPointer();
+// Get the thread-local address via intrinsic.
+if (auto *GV = dyn_cast(Guard.getPointer()))
+  if (GV->isThreadLocal())
+TLSAddr = Builder.CreateThreadLocalAddress(Guard.getPointer());
+Builder.CreateInvariantStart(
+TLSAddr, llvm::ConstantInt::getSigned(Int64Ty, Width));
+  }
 }
 
 RunCleanupsScope Scope(*this);
diff --git a/clang/test/CodeGenCXX/cxx11-thread-local.cpp 
b/clang/test/CodeGenCXX/cxx11-thread-local.cpp
index bcc490bc32e6e..e9a0799cf8d9a 100644
--- a/clang/test/CodeGenCXX/cxx11-thread-local.cpp
+++ b/clang/test/CodeGenCXX/cxx11-thread-local.cpp
@@ -358,12 +358,15 @@ void set_anon_i() {
 
 
 // CHECK: define {{.*}}@__tls_init()
-// CHECK: load i8, ptr @__tls_guard
+// CHECK: [[TLS_GUARD_ADDR_1:%.+]] = call align 1 ptr 
@llvm.threadlocal.address.p0(ptr align 1 @__tls_guard)
+// CHECK: load i8, ptr [[TLS_GUARD_ADDR_1]]
 // CHECK: %[[NEED_TLS_INIT:.*]] = icmp eq i8 %{{.*}}, 0
 // CHECK: br i1 %[[NEED_TLS_INIT]],
 // init:
-// CHECK: store i8 1, ptr @__tls_guard
-// CHECK-OPT: call ptr @llvm.invariant.start.p0(i64 1, ptr @__tls_guard)
+// CHECK: [[TLS_GUARD_ADDR_2:%.+]] = call align 1 ptr 
@llvm.threadlocal.address.p0(ptr align 1 @__tls_guard)
+// CHECK: store i8 1, ptr [[TLS_GUARD_ADDR_2]]
+// CHECK-OPT: [[TLS_GUARD_ADDR_3:%.+]] = call align 1 ptr 
@llvm.threadlocal.address.p0(ptr align 1 @__tls_guard)
+// CHECK-OPT: call ptr @llvm.invariant.start.p0(i64 1, ptr 
[[TLS_GUARD_ADDR_3]])
 // CHECK-NOT: call void @[[V_M_INIT]]()
 // CHECK: call void @[[A_INIT]]()
 // CHECK-NOT: call void @[[V_M_INIT]]()
diff --git a/clang/test/CodeGenCXX/static-initializer-branch-weights.cpp 
b/clang/test/CodeGenCXX/static-initializer-branch-weights.cpp
index 121b9b2029959..e855f54643eae 100644
--- a/clang/test/Code

[clang] [Clang] Access tls_guard via llvm.threadlocal.address (PR #96633)

2024-06-25 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] [clang][FMV] Do not omit explicit default target_version attribute. (PR #96628)

2024-06-25 Thread Alexandros Lamprineas via cfe-commits


@@ -11543,8 +11551,7 @@ static bool CheckTargetCausesMultiVersioning(Sema &S, 
FunctionDecl *OldFD,
   }
 
   // If this is 'default', permit the forward declaration.
-  if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
-  (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {

labrinea wrote:

This is wrong. The new declaration cannot be a redeclaration of the old, and at 
the same time to be causing Multiversioning. Getting past the early return 
(line 11538 with the new code) means the new declaration is causing 
Multiversioning, so at this point (line 11554 with the new code) redeclaration 
is not possible for the target_version attribute.

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


[clang] [Clang] Access tls_guard via llvm.threadlocal.address (PR #96633)

2024-06-25 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-codegen

Author: None (nikola-tesic-ns)


Changes

This patch fixes compiler generated code in `tls_init` function to access TLS 
variable (`tls_guard`) via llvm.threadlocal.address intrinsic.

Related discussion:
https://discourse.llvm.org/t/address-thread-identification-problems-with-coroutine/62015/57?u=ntesic

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


6 Files Affected:

- (modified) clang/lib/CodeGen/CGDeclCXX.cpp (+19-10) 
- (modified) clang/test/CodeGenCXX/cxx11-thread-local.cpp (+6-3) 
- (modified) clang/test/CodeGenCXX/static-initializer-branch-weights.cpp (+2-1) 
- (modified) clang/test/OpenMP/parallel_copyin_codegen.cpp (+4-2) 
- (modified) clang/test/OpenMP/target_has_device_addr_codegen.cpp (+4-2) 
- (modified) clang/test/OpenMP/threadprivate_codegen.cpp (+20-10) 


``diff
diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index e18b339b31d24..0663a083bf3e8 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -1059,9 +1059,10 @@ 
CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
 if (Guard.isValid()) {
   // If we have a guard variable, check whether we've already performed
   // these initializations. This happens for TLS initialization functions.
-  llvm::Value *GuardVal = Builder.CreateLoad(Guard);
-  llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
- "guard.uninitialized");
+  llvm::Value *GuardVal = EmitLoadOfScalar(
+  MakeAddrLValue(Guard, getContext().IntTy), SourceLocation());
+  llvm::Value *Uninit =
+  Builder.CreateIsNull(GuardVal, "guard.uninitialized");
   llvm::BasicBlock *InitBlock = createBasicBlock("init");
   ExitBlock = createBasicBlock("exit");
   EmitCXXGuardedInitBranch(Uninit, InitBlock, ExitBlock,
@@ -1070,13 +1071,21 @@ 
CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
   // Mark as initialized before initializing anything else. If the
   // initializers use previously-initialized thread_local vars, that's
   // probably supposed to be OK, but the standard doesn't say.
-  Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), 
Guard);
-
-  // The guard variable can't ever change again.
-  EmitInvariantStart(
-  Guard.getPointer(),
-  CharUnits::fromQuantity(
-  CGM.getDataLayout().getTypeAllocSize(GuardVal->getType(;
+  EmitStoreOfScalar(llvm::ConstantInt::get(GuardVal->getType(), 1),
+MakeAddrLValue(Guard, getContext().IntTy));
+
+  // Emit invariant start for TLS guard address.
+  if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
+uint64_t Width =
+CGM.getDataLayout().getTypeAllocSize(GuardVal->getType());
+llvm::Value *TLSAddr = Guard.getPointer();
+// Get the thread-local address via intrinsic.
+if (auto *GV = dyn_cast(Guard.getPointer()))
+  if (GV->isThreadLocal())
+TLSAddr = Builder.CreateThreadLocalAddress(Guard.getPointer());
+Builder.CreateInvariantStart(
+TLSAddr, llvm::ConstantInt::getSigned(Int64Ty, Width));
+  }
 }
 
 RunCleanupsScope Scope(*this);
diff --git a/clang/test/CodeGenCXX/cxx11-thread-local.cpp 
b/clang/test/CodeGenCXX/cxx11-thread-local.cpp
index bcc490bc32e6e..e9a0799cf8d9a 100644
--- a/clang/test/CodeGenCXX/cxx11-thread-local.cpp
+++ b/clang/test/CodeGenCXX/cxx11-thread-local.cpp
@@ -358,12 +358,15 @@ void set_anon_i() {
 
 
 // CHECK: define {{.*}}@__tls_init()
-// CHECK: load i8, ptr @__tls_guard
+// CHECK: [[TLS_GUARD_ADDR_1:%.+]] = call align 1 ptr 
@llvm.threadlocal.address.p0(ptr align 1 @__tls_guard)
+// CHECK: load i8, ptr [[TLS_GUARD_ADDR_1]]
 // CHECK: %[[NEED_TLS_INIT:.*]] = icmp eq i8 %{{.*}}, 0
 // CHECK: br i1 %[[NEED_TLS_INIT]],
 // init:
-// CHECK: store i8 1, ptr @__tls_guard
-// CHECK-OPT: call ptr @llvm.invariant.start.p0(i64 1, ptr @__tls_guard)
+// CHECK: [[TLS_GUARD_ADDR_2:%.+]] = call align 1 ptr 
@llvm.threadlocal.address.p0(ptr align 1 @__tls_guard)
+// CHECK: store i8 1, ptr [[TLS_GUARD_ADDR_2]]
+// CHECK-OPT: [[TLS_GUARD_ADDR_3:%.+]] = call align 1 ptr 
@llvm.threadlocal.address.p0(ptr align 1 @__tls_guard)
+// CHECK-OPT: call ptr @llvm.invariant.start.p0(i64 1, ptr 
[[TLS_GUARD_ADDR_3]])
 // CHECK-NOT: call void @[[V_M_INIT]]()
 // CHECK: call void @[[A_INIT]]()
 // CHECK-NOT: call void @[[V_M_INIT]]()
diff --git a/clang/test/CodeGenCXX/static-initializer-branch-weights.cpp 
b/clang/test/CodeGenCXX/static-initializer-branch-weights.cpp
index 121b9b2029959..e855f54643eae 100644
--- a/clang/test/CodeGenCXX/static-initializer-branch-weights.cpp
+++ b/clang/test/CodeGenCXX/static-initializer-branch-weights.cpp
@@ -118,7 +118,8 @@ void use_b() {
 }
 
 // CHECK-LABEL: define {{.*}}tls_init()
-// CHECK: load i8, ptr @__tls_g

[clang] 70cfece - Revert "[clang-format] Add option to remove leading blank lines (#91221)"

2024-06-25 Thread via cfe-commits

Author: sstwcw
Date: 2024-06-25T13:12:32Z
New Revision: 70cfece24d6cbb57e35dd961cc97eb2a6bf1e387

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

LOG: Revert "[clang-format] Add option to remove leading blank lines (#91221)"

This reverts commit 9267f8f19a2e502ef5a216c0d52b352b3699d399.

I changed a formatter option.  I forgot to update other components that
depend on the formatter when the option name changed.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/unittests/Format/ConfigParseTest.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 080cba90c4a8bf..bb00c20922d361 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -4443,51 +4443,23 @@ the configuration (without a prefix: ``Auto``).
  false:
  import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, 
VeryLongImportsAreAnnoying,} from "some/module.js"
 
-.. _KeepEmptyLines:
-
-**KeepEmptyLines** (``KeepEmptyLinesStyle``) :versionbadge:`clang-format 19` 
:ref:`¶ `
-  Which empty lines are kept.  See ``MaxEmptyLinesToKeep`` for how many
-  consecutive empty lines are kept.
-
-  Nested configuration flags:
-
-  Options regarding which empty lines are kept.
-
-  For example, the config below will remove empty lines at start of the
-  file, end of the file, and start of blocks.
-
-
-  .. code-block:: c++
-
-KeepEmptyLines:
-  AtEndOfFile: false
-  AtStartOfBlock: false
-  AtStartOfFile: false
-
-  * ``bool AtEndOfFile`` Keep empty lines at end of file.
-
-  * ``bool AtStartOfBlock`` Keep empty lines at start of a block.
-
-.. code-block:: c++
-
-   true:  false:
-   if (foo) { vs. if (foo) {
-bar();
- bar();   }
-   }
-
-  * ``bool AtStartOfFile`` Keep empty lines at start of file.
-
-
 .. _KeepEmptyLinesAtEOF:
 
 **KeepEmptyLinesAtEOF** (``Boolean``) :versionbadge:`clang-format 17` :ref:`¶ 
`
-  This option is deprecated. See ``AtEndOfFile`` of ``KeepEmptyLines``.
+  Keep empty lines (up to ``MaxEmptyLinesToKeep``) at end of file.
 
 .. _KeepEmptyLinesAtTheStartOfBlocks:
 
 **KeepEmptyLinesAtTheStartOfBlocks** (``Boolean``) :versionbadge:`clang-format 
3.7` :ref:`¶ `
-  This option is deprecated. See ``AtStartOfBlock`` of ``KeepEmptyLines``.
+  If true, the empty line at the start of blocks is kept.
+
+  .. code-block:: c++
+
+ true:  false:
+ if (foo) { vs. if (foo) {
+  bar();
+   bar();   }
+ }
 
 .. _LambdaBodyIndentation:
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9ed3ff4507671c..df579ae398c5ef 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1110,8 +1110,6 @@ clang-format
 - Adds ``AllowShortCaseExpressionOnASingleLine`` option.
 - Adds ``AlignCaseArrows`` suboption to 
``AlignConsecutiveShortCaseStatements``.
 - Adds ``LeftWithLastLine`` suboption to ``AlignEscapedNewlines``.
-- Adds ``KeepEmptyLines`` option to deprecate ``KeepEmptyLinesAtEOF``
-  and ``KeepEmptyLinesAtTheStartOfBlocks``.
 
 libclang
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index efc2e450b723fa..7d257be10af42c 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -3095,49 +3095,20 @@ struct FormatStyle {
   bool JavaScriptWrapImports;
   // clang-format on
 
-  /// Options regarding which empty lines are kept.
-  ///
-  /// For example, the config below will remove empty lines at start of the
-  /// file, end of the file, and start of blocks.
-  ///
-  /// \code
-  ///   KeepEmptyLines:
-  /// AtEndOfFile: false
-  /// AtStartOfBlock: false
-  /// AtStartOfFile: false
-  /// \endcode
-  struct KeepEmptyLinesStyle {
-/// Keep empty lines at end of file.
-bool AtEndOfFile;
-/// Keep empty lines at start of a block.
-/// \code
-///true:  false:
-///if (foo) { vs. if (foo) {
-/// bar();
-///  bar();   }
-///}
-/// \endcode
-bool AtStartOfBlock;
-/// Keep empty lines at start of file.
-bool AtStartOfFile;
-bool operator==(const Kee

[clang-tools-extra] c69ea04 - Revert "[clangd] Fix the build broken (NFC)"

2024-06-25 Thread Jie Fu via cfe-commits

Author: Jie Fu
Date: 2024-06-25T21:30:02+08:00
New Revision: c69ea04fb9738db283263eb350669e00b77ee4fd

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

LOG: Revert "[clangd] Fix the build broken (NFC)"

This reverts commit 4c91b49bab0728d4bc136aa33c4aeb4e8ea37d01 after 
70cfece24d6cbb57e35dd961cc97eb2a6bf1e387.

Added: 


Modified: 
clang-tools-extra/clangd/Format.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Format.cpp 
b/clang-tools-extra/clangd/Format.cpp
index fc56a1c8c5030..272a34d4ed797 100644
--- a/clang-tools-extra/clangd/Format.cpp
+++ b/clang-tools-extra/clangd/Format.cpp
@@ -281,7 +281,7 @@ formatIncremental(llvm::StringRef OriginalCode, unsigned 
OriginalCursor,
   // Never *remove* lines in response to pressing enter! This annoys users.
   if (InsertedText == "\n") {
 Style.MaxEmptyLinesToKeep = 1000;
-Style.KeepEmptyLines.AtStartOfBlock = true;
+Style.KeepEmptyLinesAtTheStartOfBlocks = true;
   }
 
   // Compute the code we want to format:



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


[clang] [clang][FMV] Do not omit explicit default target_version attribute. (PR #96628)

2024-06-25 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [clang] Catch missing format attributes (PR #70024)

2024-06-25 Thread Budimir Aranđelović via cfe-commits


@@ -0,0 +1,277 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wmissing-format-attribute %s
+
+typedef unsigned short char16_t;
+typedef unsigned int char32_t;
+typedef __WCHAR_TYPE__ wchar_t;
+typedef __SIZE_TYPE__ size_t;
+typedef __builtin_va_list va_list;
+
+__attribute__((__format__(__printf__, 1, 2)))
+int printf(const char *, ...); // #printf
+
+__attribute__((__format__(__scanf__, 1, 2)))
+int scanf(const char *, ...); // #scanf
+
+__attribute__((__format__(__printf__, 1, 0)))
+int vprintf(const char *, va_list); // #vprintf
+
+__attribute__((__format__(__scanf__, 1, 0)))
+int vscanf(const char *, va_list); // #vscanf
+
+__attribute__((__format__(__printf__, 2, 0)))
+int vsprintf(char *, const char *, va_list); // #vsprintf
+
+__attribute__((__format__(__printf__, 3, 0)))
+int vsnprintf(char *ch, size_t, const char *, va_list); // #vsnprintf
+
+__attribute__((__format__(__scanf__, 1, 4)))
+void f1(char *out, const size_t len, const char *format, ... /* args */) // #f1
+{
+va_list args;
+vsnprintf(out, len, format, args); // expected-warning@#f1 {{diagnostic 
behavior may be improved by adding the 'printf' format attribute to the 
declaration of 'f1'}}
+   // CHECK-FIXES: 
__attribute__((format(printf, 3, 4)))
+}
+
+__attribute__((__format__(__printf__, 1, 4)))
+void f2(char *out, const size_t len, const char *format, ... /* args */) // #f2
+{
+va_list args;
+vsnprintf(out, len, format, args); // expected-warning@#f2 {{diagnostic 
behavior may be improved by adding the 'printf' format attribute to the 
declaration of 'f2'}}
+   // CHECK-FIXES: 
__attribute__((format(printf, 3, 4)))
+}
+
+void f3(char *out, va_list args) // #f3
+{
+vprintf(out, args); // expected-warning@#f3 {{diagnostic behavior may be 
improved by adding the 'printf' format attribute to the declaration of 'f3'}}
+// CHECK-FIXES: __attribute__((format(printf, 1, 0)))
+vscanf(out, args); // expected-warning@#f3 {{diagnostic behavior may be 
improved by adding the 'scanf' format attribute to the declaration of 'f3'}}
+   // CHECK-FIXES: __attribute__((format(scanf, 1, 0)))

budimirarandjelovicsyrmia wrote:

ping @AaronBallman
My view of this comment is next: it refers to function which calls both vprintf 
and vscanf format functions (let's call this function _fn_). As same format 
specifiers of calling functions mean different things and these two functions 
are called inside same function, there is pretty small chance of importance to 
mark function _fn_ to be format function.
Is this view correct?

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


[clang] [clang][FMV] Do not omit explicit default target_version attribute. (PR #96628)

2024-06-25 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll commented:

`Sema.h` changes look good to me.

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


[clang] [Clang][AMDGPU] Add builtins for instrinsic `llvm.amdgcn.raw.ptr.buffer.store` (PR #94576)

2024-06-25 Thread Shilei Tian via cfe-commits

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


[clang] c9f083a - [Clang][AMDGPU] Add builtins for instrinsic `llvm.amdgcn.raw.ptr.buffer.store` (#94576)

2024-06-25 Thread via cfe-commits

Author: Shilei Tian
Date: 2024-06-25T09:55:37-04:00
New Revision: c9f083a9940d1d62f77c39f05bb0fc186cc4832c

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

LOG: [Clang][AMDGPU] Add builtins for instrinsic 
`llvm.amdgcn.raw.ptr.buffer.store` (#94576)

Depends on https://github.com/llvm/llvm-project/pull/96313.

Added: 
clang/test/CodeGenOpenCL/builtins-amdgcn-raw-buffer-store.cl
clang/test/SemaOpenCL/builtins-amdgcn-raw-buffer-store-error.cl

Modified: 
clang/include/clang/Basic/BuiltinsAMDGPU.def
clang/lib/CodeGen/CGBuiltin.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsAMDGPU.def 
b/clang/include/clang/Basic/BuiltinsAMDGPU.def
index a73e63355cfd7..56bba448e12a4 100644
--- a/clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ b/clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -149,6 +149,12 @@ BUILTIN(__builtin_amdgcn_mqsad_pk_u16_u8, "WUiWUiUiWUi", 
"nc")
 BUILTIN(__builtin_amdgcn_mqsad_u32_u8, "V4UiWUiUiV4Ui", "nc")
 
 BUILTIN(__builtin_amdgcn_make_buffer_rsrc, "Qbv*sii", "nc")
+BUILTIN(__builtin_amdgcn_raw_buffer_store_b8, "vcQbiiIi", "n")
+BUILTIN(__builtin_amdgcn_raw_buffer_store_b16, "vsQbiiIi", "n")
+BUILTIN(__builtin_amdgcn_raw_buffer_store_b32, "viQbiiIi", "n")
+BUILTIN(__builtin_amdgcn_raw_buffer_store_b64, "vV2iQbiiIi", "n")
+BUILTIN(__builtin_amdgcn_raw_buffer_store_b96, "vV3iQbiiIi", "n")
+BUILTIN(__builtin_amdgcn_raw_buffer_store_b128, "vV4iQbiiIi", "n")
 
 
//===--===//
 // Ballot builtins.

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index ce22e13d0004f..2434dcc1f26d6 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -19141,6 +19141,14 @@ Value *CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned 
BuiltinID,
   case AMDGPU::BI__builtin_amdgcn_make_buffer_rsrc:
 return emitBuiltinWithOneOverloadedType<4>(
 *this, E, Intrinsic::amdgcn_make_buffer_rsrc);
+  case AMDGPU::BI__builtin_amdgcn_raw_buffer_store_b8:
+  case AMDGPU::BI__builtin_amdgcn_raw_buffer_store_b16:
+  case AMDGPU::BI__builtin_amdgcn_raw_buffer_store_b32:
+  case AMDGPU::BI__builtin_amdgcn_raw_buffer_store_b64:
+  case AMDGPU::BI__builtin_amdgcn_raw_buffer_store_b96:
+  case AMDGPU::BI__builtin_amdgcn_raw_buffer_store_b128:
+return emitBuiltinWithOneOverloadedType<5>(
+*this, E, Intrinsic::amdgcn_raw_ptr_buffer_store);
   default:
 return nullptr;
   }

diff  --git a/clang/test/CodeGenOpenCL/builtins-amdgcn-raw-buffer-store.cl 
b/clang/test/CodeGenOpenCL/builtins-amdgcn-raw-buffer-store.cl
new file mode 100644
index 0..37975d59730c5
--- /dev/null
+++ b/clang/test/CodeGenOpenCL/builtins-amdgcn-raw-buffer-store.cl
@@ -0,0 +1,172 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// REQUIRES: amdgpu-registered-target
+// RUN: %clang_cc1 -triple amdgcn-unknown-unknown -target-cpu verde -emit-llvm 
-o - %s | FileCheck %s
+
+typedef char i8;
+typedef short i16;
+typedef int i32;
+typedef int i64 __attribute__((ext_vector_type(2)));
+typedef int i96 __attribute__((ext_vector_type(3)));
+typedef int i128 __attribute__((ext_vector_type(4)));
+
+// CHECK-LABEL: @test_amdgcn_raw_ptr_buffer_store_b8(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void @llvm.amdgcn.raw.ptr.buffer.store.i8(i8 
[[VDATA:%.*]], ptr addrspace(8) [[RSRC:%.*]], i32 0, i32 0, i32 0)
+// CHECK-NEXT:ret void
+//
+void test_amdgcn_raw_ptr_buffer_store_b8(i8 vdata, __amdgpu_buffer_rsrc_t 
rsrc, int offset, int soffset) {
+  __builtin_amdgcn_raw_buffer_store_b8(vdata, rsrc, /*offset=*/0, 
/*soffset=*/0, /*aux=*/0);
+}
+
+// CHECK-LABEL: @test_amdgcn_raw_ptr_buffer_store_b16(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void @llvm.amdgcn.raw.ptr.buffer.store.i16(i16 
[[VDATA:%.*]], ptr addrspace(8) [[RSRC:%.*]], i32 0, i32 0, i32 0)
+// CHECK-NEXT:ret void
+//
+void test_amdgcn_raw_ptr_buffer_store_b16(i16 vdata, __amdgpu_buffer_rsrc_t 
rsrc, int offset, int soffset) {
+  __builtin_amdgcn_raw_buffer_store_b16(vdata, rsrc, /*offset=*/0, 
/*soffset=*/0, /*aux=*/0);
+}
+
+// CHECK-LABEL: @test_amdgcn_raw_ptr_buffer_store_b32(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void @llvm.amdgcn.raw.ptr.buffer.store.i32(i32 
[[VDATA:%.*]], ptr addrspace(8) [[RSRC:%.*]], i32 0, i32 0, i32 0)
+// CHECK-NEXT:ret void
+//
+void test_amdgcn_raw_ptr_buffer_store_b32(i32 vdata, __amdgpu_buffer_rsrc_t 
rsrc, int offset, int soffset) {
+  __builtin_amdgcn_raw_buffer_store_b32(vdata, rsrc, /*offset=*/0, 
/*soffset=*/0, /*aux=*/0);
+}
+
+// CHECK-LABEL: @test_amdgcn_raw_ptr_buffer_store_b64(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void @llvm.amdgcn.raw.ptr.buffer.store.v2i32(<2 x 
i32> [[V

[clang] [Clang] Introduce 'clang-nvlink-wrappaer' to work around 'nvlink' (PR #96561)

2024-06-25 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/96561

>From 859f6a7fce9503275ad7eb39512dc5833a11bb07 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Mon, 24 Jun 2024 15:14:52 -0500
Subject: [PATCH] [Clang] Introduce 'clang-nvlink-wrappaer' to work around
 'nvlink'

Summary:
The `clang-nvlink-wrapper` is a utility that I removed awhile back
during the transition to the new driver. This patch adds back in a new,
upgraded version that does LTO + archive linking. It's not an easy
choice to reintroduce something I happily deleted, but this is the only
way to move forward with improving GPU support in LLVM.

While NVIDIA provides a linker called 'nvlink', its main interface is
very difficult to work with. It does not provide LTO, or static linking,
requires all files to be named a non-standard `.cubin`, and rejects link
jobs that other linkers would be fine with (i.e empty). I have spent a
great deal of time hacking around this in the GPU `libc` implementation,
where I deliberately avoid LTO and static linking and have about 100
lines of hacky CMake dedicated to storing these files in a format that
the clang-linker-wrapper accepts to avoid this limitation.

The main reason I want to re-intorudce this tool is because I am
planning on creating a more standard C/C++ toolchain for GPUs to use.
This will install files like the following.
```
/lib/nvptx64-nvidia-cuda/libc.a
/lib/nvptx64-nvidia-cuda/libc++.a
/lib/nvptx64-nvidia-cuda/libomp.a
/lib/clang/19/lib/nvptx64-nvidia-cuda/libclang_rt.builtins.a
```
Linking in these libraries will then simply require passing `-lc` like
is already done for non-GPU toolchains. However, this doesn't work with
the currently deficient `nvlink` linker, so I consider this a blocking
issue to massively improving the state of building GPU libraries.

In the future we may be able to convince NVIDIA to port their linker to
`ld.lld`, but for now this is the only workable solution that allows us
to hack around the weird behavior of their closed-source software.
---
 clang/lib/Driver/ToolChains/Cuda.cpp  |  61 +-
 clang/lib/Driver/ToolChains/Cuda.h|   3 +
 clang/test/Driver/cuda-cross-compiling.c  |   8 +-
 clang/test/Driver/nvlink-wrapper.c|  65 ++
 clang/test/lit.cfg.py |   1 +
 clang/tools/CMakeLists.txt|   1 +
 .../tools/clang-nvlink-wrapper/CMakeLists.txt |  44 ++
 .../ClangNVLinkWrapper.cpp| 671 ++
 .../tools/clang-nvlink-wrapper/NVLinkOpts.td  |  68 ++
 9 files changed, 865 insertions(+), 57 deletions(-)
 create mode 100644 clang/test/Driver/nvlink-wrapper.c
 create mode 100644 clang/tools/clang-nvlink-wrapper/CMakeLists.txt
 create mode 100644 clang/tools/clang-nvlink-wrapper/ClangNVLinkWrapper.cpp
 create mode 100644 clang/tools/clang-nvlink-wrapper/NVLinkOpts.td

diff --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index 2dfc7457b0ac7..54724cc1ad08e 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -461,13 +461,6 @@ void NVPTX::Assembler::ConstructJob(Compilation &C, const 
JobAction &JA,
   CmdArgs.push_back("--output-file");
   std::string OutputFileName = TC.getInputFilename(Output);
 
-  // If we are invoking `nvlink` internally we need to output a `.cubin` file.
-  // FIXME: This should hopefully be removed if NVIDIA updates their tooling.
-  if (!C.getInputArgs().getLastArg(options::OPT_c)) {
-SmallString<256> Filename(Output.getFilename());
-llvm::sys::path::replace_extension(Filename, "cubin");
-OutputFileName = Filename.str();
-  }
   if (Output.isFilename() && OutputFileName != Output.getFilename())
 C.addTempFile(Args.MakeArgString(OutputFileName));
 
@@ -618,6 +611,11 @@ void NVPTX::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   // Add standard library search paths passed on the command line.
   Args.AddAllArgs(CmdArgs, options::OPT_L);
   getToolChain().AddFilePathLibArgs(Args, CmdArgs);
+  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
+
+  if (C.getDriver().isUsingLTO())
+addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],
+  C.getDriver().getLTOMode() == LTOK_Thin);
 
   // Add paths for the default clang library path.
   SmallString<256> DefaultLibPath =
@@ -625,51 +623,12 @@ void NVPTX::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   llvm::sys::path::append(DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME);
   CmdArgs.push_back(Args.MakeArgString(Twine("-L") + DefaultLibPath));
 
-  for (const auto &II : Inputs) {
-if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR 
||
-II.getType() == types::TY_LTO_BC || II.getType() == types::TY_LLVM_BC) 
{
-  C.getDriver().Diag(diag::err_drv_no_linker_llvm_support)
-  << getToolChain().getTripleString();
-  continue;
-}
-
-// The 'nvlink' application perfor

[clang] [Clang][AMDGPU] Add builtins for instrinsic `llvm.amdgcn.raw.ptr.buffer.store` (PR #94576)

2024-06-25 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `clang-hip-vega20` running 
on `hip-vega20-0` while building `clang` at step 3 "annotate".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/123/builds/594

Here is the relevant piece of the build log for the reference:
```
Step 3 (annotate) failure: 
'../llvm-zorg/zorg/buildbot/builders/annotated/hip-build.sh --jobs=' (failure)
...
[37/38] /buildbot/hip-vega20-0/clang-hip-vega20/llvm/bin/clang++ -DNDEBUG  -O3 
-DNDEBUG   -w -Werror=date-time --rocm-path=/buildbot/Externals/hip/rocm-6.0.2 
--offload-arch=gfx908 --offload-arch=gfx90a --offload-arch=gfx1030 
--offload-arch=gfx1100 -xhip -mfma -MD -MT 
External/HIP/CMakeFiles/TheNextWeek-hip-6.0.2.dir/workload/ray-tracing/TheNextWeek/main.cc.o
 -MF 
External/HIP/CMakeFiles/TheNextWeek-hip-6.0.2.dir/workload/ray-tracing/TheNextWeek/main.cc.o.d
 -o 
External/HIP/CMakeFiles/TheNextWeek-hip-6.0.2.dir/workload/ray-tracing/TheNextWeek/main.cc.o
 -c 
/buildbot/llvm-test-suite/External/HIP/workload/ray-tracing/TheNextWeek/main.cc
[38/38] : && /buildbot/hip-vega20-0/clang-hip-vega20/llvm/bin/clang++ -O3 
-DNDEBUG  
External/HIP/CMakeFiles/TheNextWeek-hip-6.0.2.dir/workload/ray-tracing/TheNextWeek/main.cc.o
 -o External/HIP/TheNextWeek-hip-6.0.2  
--rocm-path=/buildbot/Externals/hip/rocm-6.0.2 --hip-link -rtlib=compiler-rt 
-unwindlib=libgcc -frtlib-add-rpath && cd 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP && 
/usr/local/bin/cmake -E create_symlink 
/buildbot/llvm-test-suite/External/HIP/TheNextWeek.reference_output 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP/TheNextWeek.reference_output-hip-6.0.2
+ build_step 'Testing HIP test-suite'
+ echo '@@@BUILD_STEP Testing HIP test-suite@@@'
+ ninja -v check-hip-simple
@@@BUILD_STEP Testing HIP test-suite@@@
[0/1] cd /buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP 
&& /buildbot/hip-vega20-0/clang-hip-vega20/llvm/bin/llvm-lit -sv 
empty-hip-6.0.2.test with-fopenmp-hip-6.0.2.test saxpy-hip-6.0.2.test 
InOneWeekend-hip-6.0.2.test TheNextWeek-hip-6.0.2.test blender.test
-- Testing: 6 tests, 6 workers --
/usr/bin/strip: /bin/bash.stripped: Bad file descriptor
Testing:  0.. 10.. 20.. 30.. 40.. 50.. 60.
FAIL: test-suite :: External/HIP/InOneWeekend-hip-6.0.2.test (5 of 6)
 TEST 'test-suite :: 
External/HIP/InOneWeekend-hip-6.0.2.test' FAILED 

/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/tools/timeit-target 
--timeout 7200 --limit-core 0 --limit-cpu 7200 --limit-file-size 209715200 
--limit-rss-size 838860800 --append-exitstatus --redirect-output 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP/Output/InOneWeekend-hip-6.0.2.test.out
 --redirect-input /dev/null --summary 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP/Output/InOneWeekend-hip-6.0.2.test.time
 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP/InOneWeekend-hip-6.0.2
cd /buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP ; 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/tools/fpcmp-target 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP/Output/InOneWeekend-hip-6.0.2.test.out
 InOneWeekend.reference_output-hip-6.0.2

+ cd /buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP
+ /buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/tools/fpcmp-target 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP/Output/InOneWeekend-hip-6.0.2.test.out
 InOneWeekend.reference_output-hip-6.0.2
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/tools/fpcmp-target: 
Comparison failed, textual difference between 'M' and 'i'


Testing:  0.. 10.. 20.. 30.. 40.. 50.. 60.. 70.. 80.. 90.. 

Failed Tests (1):
  test-suite :: External/HIP/InOneWeekend-hip-6.0.2.test


Testing Time: 50.85s

Total Discovered Tests: 6
  Passed: 5 (83.33%)
  Failed: 1 (16.67%)
FAILED: External/HIP/CMakeFiles/check-hip-simple-hip-6.0.2 
cd /buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP && 
/buildbot/hip-vega20-0/clang-hip-vega20/llvm/bin/llvm-lit -sv 
empty-hip-6.0.2.test with-fopenmp-hip-6.0.2.test saxpy-hip-6.0.2.test 
InOneWeekend-hip-6.0.2.test TheNextWeek-hip-6.0.2.test blender.test
ninja: build stopped: subcommand failed.
Step 12 (Testing HIP test-suite) failure: Testing HIP test-suite (failure)
@@@BUILD_STEP Testing HIP test-suite@@@
[0/1] cd /buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP 
&& /buildbot/hip-vega20-0/clang-hip-vega20/llvm/bin/llvm-lit -sv 
empty-hip-6.0.2.test with-fopenmp-hip-6.0.2.test saxpy-hip-6.0.2.test 
InOneWeekend-hip-6.0.2.test TheNextWeek-hip-6.0.2.test blender.test
-- Testing: 6 tests, 6 workers --
/usr/bin/strip: /bin/bash.stripped: Bad file descriptor
Testing:  0.. 10.. 20.. 30.. 40.. 50.. 60.
FAIL: test-suite :: External/HIP/

[clang] [llvm] [mlir] [OpenMP] Migrate GPU Reductions CodeGen from Clang to OMPIRBuilder (PR #80343)

2024-06-25 Thread Jan Leyonberg via cfe-commits

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

This looks good to me now. You can wait a few days before merging to let 
@jdoerfert look it over again.


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


[clang] Reject half vector types without cl_khr_fp16 (PR #96640)

2024-06-25 Thread Sven van Haastregt via cfe-commits

https://github.com/svenvh created 
https://github.com/llvm/llvm-project/pull/96640

Reject `half` vector types (`halfn`) if the `cl_khr_fp16` extension is 
disabled, in line with the already existing rejection of `half` scalar types 
and `half` array types.

>From e26114f1aa6809e7b5f93f4e866e7ff25355edb3 Mon Sep 17 00:00:00 2001
From: Sven van Haastregt 
Date: Tue, 25 Jun 2024 14:59:14 +0100
Subject: [PATCH] Reject half vector types without cl_khr_fp16

Reject `half` vector types (`halfn`) if the `cl_khr_fp16` extension is
disabled, in line with the already existing rejection of `half` scalar
types and `half` array types.
---
 clang/lib/Sema/SemaDecl.cpp   | 12 +---
 clang/test/SemaOpenCL/half.cl |  4 
 2 files changed, 13 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 029ccf944c513..639729467e9e4 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -7448,9 +7448,15 @@ static bool diagnoseOpenCLTypes(Sema &Se, VarDecl 
*NewVD) {
 
   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
Se.getLangOpts())) {
-// OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
-// half array type (unless the cl_khr_fp16 extension is enabled).
-if (Se.Context.getBaseElementType(R)->isHalfType()) {
+// OpenCL v1.2 s6.1.1.1: reject declaring variables of the half/halfn and
+// half/halfn array type (unless the cl_khr_fp16 extension is enabled).
+auto HasHalfTy = [](QualType T) {
+  if (const auto *EVTy = T->getAs()) {
+return EVTy->getElementType()->isHalfType();
+  }
+  return T->isHalfType();
+};
+if (HasHalfTy(R) || HasHalfTy(Se.Context.getBaseElementType(R))) {
   Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
   NewVD->setInvalidDecl();
   return false;
diff --git a/clang/test/SemaOpenCL/half.cl b/clang/test/SemaOpenCL/half.cl
index d0cd529a8f9af..b86fc95ee1b83 100644
--- a/clang/test/SemaOpenCL/half.cl
+++ b/clang/test/SemaOpenCL/half.cl
@@ -23,6 +23,8 @@ half half_disabled(half *p, // expected-error{{declaring 
function return value o
   half *allowed3 = p + 1;
 
 #ifdef HAVE_BUILTINS
+  half2 h2; // expected-error{{declaring variable of type '__private half2' 
(vector of 2 'half' values) is not allowed}}
+  half4 h4a[2]; // expected-error{{declaring variable of type '__private 
half4[2]' is not allowed}}
   (void)ilogb(*p); // expected-error{{loading directly from pointer to type 
'__private half' requires cl_khr_fp16. Use vector data load builtin functions 
instead}}
   vstore_half(42.0f, 0, p);
 #endif
@@ -55,6 +57,8 @@ half half_enabled(half *p, half h)
   half *allowed3 = p + 1;
 
 #ifdef HAVE_BUILTINS
+  half2 h2;
+  half4 h4a[2];
   (void)ilogb(*p);
   vstore_half(42.0f, 0, p);
 #endif

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


[clang] Reject half vector types without cl_khr_fp16 (PR #96640)

2024-06-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Sven van Haastregt (svenvh)


Changes

Reject `half` vector types (`halfn`) if the `cl_khr_fp16` extension is 
disabled, in line with the already existing rejection of `half` scalar types 
and `half` array types.

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


2 Files Affected:

- (modified) clang/lib/Sema/SemaDecl.cpp (+9-3) 
- (modified) clang/test/SemaOpenCL/half.cl (+4) 


``diff
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 029ccf944c513..639729467e9e4 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -7448,9 +7448,15 @@ static bool diagnoseOpenCLTypes(Sema &Se, VarDecl 
*NewVD) {
 
   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
Se.getLangOpts())) {
-// OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
-// half array type (unless the cl_khr_fp16 extension is enabled).
-if (Se.Context.getBaseElementType(R)->isHalfType()) {
+// OpenCL v1.2 s6.1.1.1: reject declaring variables of the half/halfn and
+// half/halfn array type (unless the cl_khr_fp16 extension is enabled).
+auto HasHalfTy = [](QualType T) {
+  if (const auto *EVTy = T->getAs()) {
+return EVTy->getElementType()->isHalfType();
+  }
+  return T->isHalfType();
+};
+if (HasHalfTy(R) || HasHalfTy(Se.Context.getBaseElementType(R))) {
   Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
   NewVD->setInvalidDecl();
   return false;
diff --git a/clang/test/SemaOpenCL/half.cl b/clang/test/SemaOpenCL/half.cl
index d0cd529a8f9af..b86fc95ee1b83 100644
--- a/clang/test/SemaOpenCL/half.cl
+++ b/clang/test/SemaOpenCL/half.cl
@@ -23,6 +23,8 @@ half half_disabled(half *p, // expected-error{{declaring 
function return value o
   half *allowed3 = p + 1;
 
 #ifdef HAVE_BUILTINS
+  half2 h2; // expected-error{{declaring variable of type '__private half2' 
(vector of 2 'half' values) is not allowed}}
+  half4 h4a[2]; // expected-error{{declaring variable of type '__private 
half4[2]' is not allowed}}
   (void)ilogb(*p); // expected-error{{loading directly from pointer to type 
'__private half' requires cl_khr_fp16. Use vector data load builtin functions 
instead}}
   vstore_half(42.0f, 0, p);
 #endif
@@ -55,6 +57,8 @@ half half_enabled(half *p, half h)
   half *allowed3 = p + 1;
 
 #ifdef HAVE_BUILTINS
+  half2 h2;
+  half4 h4a[2];
   (void)ilogb(*p);
   vstore_half(42.0f, 0, p);
 #endif

``




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


[clang] 54b61ad - [NFC][clang] Replace unreachable code in literal processing with assert (#96579)

2024-06-25 Thread via cfe-commits

Author: Mike Rice
Date: 2024-06-25T07:14:40-07:00
New Revision: 54b61adc0cbefb7f923ef43c407704ba9f9d8b69

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

LOG: [NFC][clang] Replace unreachable code in literal processing with assert 
(#96579)

Address static verifier concerns about dead code in DoubleUnderscore
check. Replace it with an assert.

Added: 


Modified: 
clang/lib/Lex/LiteralSupport.cpp

Removed: 




diff  --git a/clang/lib/Lex/LiteralSupport.cpp 
b/clang/lib/Lex/LiteralSupport.cpp
index 3df0391bdda77..9d2720af5dbd9 100644
--- a/clang/lib/Lex/LiteralSupport.cpp
+++ b/clang/lib/Lex/LiteralSupport.cpp
@@ -1123,8 +1123,9 @@ NumericLiteralParser::NumericLiteralParser(StringRef 
TokSpelling,
 break; // Invalid for floats
   if (HasSize)
 break;
-  if (DoubleUnderscore)
-break; // Cannot be repeated.
+  // There is currently no way to reach this with DoubleUnderscore set.
+  // If new double underscope literals are added handle it here as above.
+  assert(!DoubleUnderscore && "unhandled double underscore case");
   if (LangOpts.CPlusPlus && s + 2 < ThisTokEnd &&
   s[1] == '_') { // s + 2 < ThisTokEnd to ensure some character exists
  // after __



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


[clang] [NFC][clang] Replace unreachable code in literal processing with assert (PR #96579)

2024-06-25 Thread Mike Rice via cfe-commits

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


[clang] [compiler-rt] [ubsan] Display correct runtime messages for negative _BitInt (PR #93612)

2024-06-25 Thread via cfe-commits

earnol wrote:

@mstorsjo It seems your compiler build does not have int128_t enabled. Could 
you please test https://github.com/llvm/llvm-project/pull/96240 in your 
environment to verify it has no such problem?

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


[clang] [llvm] [LV][LAA] Vectorize math lib calls with mem write-only attribute (PR #78432)

2024-06-25 Thread Paschalis Mpeis via cfe-commits

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


[clang] [C23] Add *_NORM_MAX macros to (PR #96643)

2024-06-25 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman created 
https://github.com/llvm/llvm-project/pull/96643

This adds the *_NORM_MAX macros to  for freestanding mode in Clang; 
the values were chosen based on the behavior seen coming from GCC and the 
values already produced for the *_MAX macros by Clang.

>From 408c34b84966a256bb6e7fdf45758f5c77380bbe Mon Sep 17 00:00:00 2001
From: Aaron Ballman 
Date: Tue, 25 Jun 2024 10:27:10 -0400
Subject: [PATCH] [C23] Add *_NORM_MAX macros to 

This adds the *_NORM_MAX macros to  for freestanding mode in
Clang; the values were chosen based on the behavior seen coming from
GCC and the values already produced for the *_MAX macros by Clang.
---
 clang/docs/ReleaseNotes.rst |  3 +++
 clang/lib/Frontend/InitPreprocessor.cpp |  7 ++-
 clang/lib/Headers/float.h   | 13 
 clang/test/Headers/float.c  | 27 +
 4 files changed, 49 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index df579ae398c5e..8879a77ba4dd9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -336,6 +336,9 @@ C23 Feature Support
 - Properly promote bit-fields of bit-precise integer types to the field's type
   rather than to ``int``. #GH87641
 
+- Added the ``FLT_NORM_MAX``, ``DBL_NORM_MAX``, and ``LDBL_NORM_MAX`` to the
+  freestanding implementation of  that ships with Clang.
+
 Non-comprehensive list of changes in this release
 -
 
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 55ec460064830..afc4c16ab685b 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -113,7 +113,11 @@ static T PickFP(const llvm::fltSemantics *Sem, T 
IEEEHalfVal, T IEEESingleVal,
 
 static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix,
   const llvm::fltSemantics *Sem, StringRef Ext) {
-  const char *DenormMin, *Epsilon, *Max, *Min;
+  const char *DenormMin, *NormMax, *Epsilon, *Max, *Min;
+  NormMax = PickFP(Sem, "6.5504e+4", "3.40282347e+38",
+   "1.7976931348623157e+308", "1.18973149535723176502e+4932",
+   "1.79769313486231580793728971405301e+308",
+   "1.18973149535723176508575932662800702e+4932");
   DenormMin = PickFP(Sem, "5.9604644775390625e-8", "1.40129846e-45",
  "4.9406564584124654e-324", "3.64519953188247460253e-4951",
  "4.94065645841246544176568792868221e-324",
@@ -144,6 +148,7 @@ static void DefineFloatMacros(MacroBuilder &Builder, 
StringRef Prefix,
   DefPrefix += "_";
 
   Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext);
+  Builder.defineMacro(DefPrefix + "NORM_MAX__", Twine(NormMax)+Ext);
   Builder.defineMacro(DefPrefix + "HAS_DENORM__");
   Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
   Builder.defineMacro(DefPrefix + "DECIMAL_DIG__", Twine(DecimalDigits));
diff --git a/clang/lib/Headers/float.h b/clang/lib/Headers/float.h
index 642c8f06cc938..61f65dad8debc 100644
--- a/clang/lib/Headers/float.h
+++ b/clang/lib/Headers/float.h
@@ -86,6 +86,12 @@
 #undef DBL_HAS_SUBNORM
 #undef LDBL_HAS_SUBNORM
 #  endif
+#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) ||  
\
+!defined(__STRICT_ANSI__)
+#undef FLT_NORM_MAX
+#undef DBL_NORM_MAX
+#undef LDBL_NORM_MAX
+#endif
 #endif
 
 /* Characteristics of floating point types, C99 5.2.4.2.2 */
@@ -155,6 +161,13 @@
 #  define LDBL_HAS_SUBNORM __LDBL_HAS_DENORM__
 #endif
 
+#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) ||  
\
+!defined(__STRICT_ANSI__)
+#  define FLT_NORM_MAX __FLT_NORM_MAX__
+#  define DBL_NORM_MAX __DBL_NORM_MAX__
+#  define LDBL_NORM_MAX __LDBL_NORM_MAX__
+#endif
+
 #ifdef __STDC_WANT_IEC_60559_TYPES_EXT__
 #  define FLT16_MANT_DIG__FLT16_MANT_DIG__
 #  define FLT16_DECIMAL_DIG __FLT16_DECIMAL_DIG__
diff --git a/clang/test/Headers/float.c b/clang/test/Headers/float.c
index 70c11b0537537..59cc0faa074db 100644
--- a/clang/test/Headers/float.c
+++ b/clang/test/Headers/float.c
@@ -1,17 +1,21 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c89 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c99 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c11 -ffreestanding %s
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c23 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -xc++ -std=c++11 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -xc++ -std=c++14 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -xc++ -std=c++17 -ffreestanding %s
+// RUN: %clang_cc1 -fsyntax-only -verify -xc++ -std=c++23 -ffreestanding %s
 // expected-no-diagnostics
 
 /* Basic floating point conformance checks against:
+- C23 Final Std.
 - N1570 draft of C11 Std.
 - N1256 draft of C9

[clang] [C23] Add *_NORM_MAX macros to (PR #96643)

2024-06-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-backend-x86

Author: Aaron Ballman (AaronBallman)


Changes

This adds the *_NORM_MAX macros to  for freestanding mode in 
Clang; the values were chosen based on the behavior seen coming from GCC and 
the values already produced for the *_MAX macros by Clang.

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


4 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/lib/Frontend/InitPreprocessor.cpp (+6-1) 
- (modified) clang/lib/Headers/float.h (+13) 
- (modified) clang/test/Headers/float.c (+27) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index df579ae398c5e..8879a77ba4dd9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -336,6 +336,9 @@ C23 Feature Support
 - Properly promote bit-fields of bit-precise integer types to the field's type
   rather than to ``int``. #GH87641
 
+- Added the ``FLT_NORM_MAX``, ``DBL_NORM_MAX``, and ``LDBL_NORM_MAX`` to the
+  freestanding implementation of  that ships with Clang.
+
 Non-comprehensive list of changes in this release
 -
 
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 55ec460064830..afc4c16ab685b 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -113,7 +113,11 @@ static T PickFP(const llvm::fltSemantics *Sem, T 
IEEEHalfVal, T IEEESingleVal,
 
 static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix,
   const llvm::fltSemantics *Sem, StringRef Ext) {
-  const char *DenormMin, *Epsilon, *Max, *Min;
+  const char *DenormMin, *NormMax, *Epsilon, *Max, *Min;
+  NormMax = PickFP(Sem, "6.5504e+4", "3.40282347e+38",
+   "1.7976931348623157e+308", "1.18973149535723176502e+4932",
+   "1.79769313486231580793728971405301e+308",
+   "1.18973149535723176508575932662800702e+4932");
   DenormMin = PickFP(Sem, "5.9604644775390625e-8", "1.40129846e-45",
  "4.9406564584124654e-324", "3.64519953188247460253e-4951",
  "4.94065645841246544176568792868221e-324",
@@ -144,6 +148,7 @@ static void DefineFloatMacros(MacroBuilder &Builder, 
StringRef Prefix,
   DefPrefix += "_";
 
   Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext);
+  Builder.defineMacro(DefPrefix + "NORM_MAX__", Twine(NormMax)+Ext);
   Builder.defineMacro(DefPrefix + "HAS_DENORM__");
   Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
   Builder.defineMacro(DefPrefix + "DECIMAL_DIG__", Twine(DecimalDigits));
diff --git a/clang/lib/Headers/float.h b/clang/lib/Headers/float.h
index 642c8f06cc938..61f65dad8debc 100644
--- a/clang/lib/Headers/float.h
+++ b/clang/lib/Headers/float.h
@@ -86,6 +86,12 @@
 #undef DBL_HAS_SUBNORM
 #undef LDBL_HAS_SUBNORM
 #  endif
+#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) ||  
\
+!defined(__STRICT_ANSI__)
+#undef FLT_NORM_MAX
+#undef DBL_NORM_MAX
+#undef LDBL_NORM_MAX
+#endif
 #endif
 
 /* Characteristics of floating point types, C99 5.2.4.2.2 */
@@ -155,6 +161,13 @@
 #  define LDBL_HAS_SUBNORM __LDBL_HAS_DENORM__
 #endif
 
+#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) ||  
\
+!defined(__STRICT_ANSI__)
+#  define FLT_NORM_MAX __FLT_NORM_MAX__
+#  define DBL_NORM_MAX __DBL_NORM_MAX__
+#  define LDBL_NORM_MAX __LDBL_NORM_MAX__
+#endif
+
 #ifdef __STDC_WANT_IEC_60559_TYPES_EXT__
 #  define FLT16_MANT_DIG__FLT16_MANT_DIG__
 #  define FLT16_DECIMAL_DIG __FLT16_DECIMAL_DIG__
diff --git a/clang/test/Headers/float.c b/clang/test/Headers/float.c
index 70c11b0537537..59cc0faa074db 100644
--- a/clang/test/Headers/float.c
+++ b/clang/test/Headers/float.c
@@ -1,17 +1,21 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c89 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c99 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c11 -ffreestanding %s
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c23 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -xc++ -std=c++11 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -xc++ -std=c++14 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -xc++ -std=c++17 -ffreestanding %s
+// RUN: %clang_cc1 -fsyntax-only -verify -xc++ -std=c++23 -ffreestanding %s
 // expected-no-diagnostics
 
 /* Basic floating point conformance checks against:
+- C23 Final Std.
 - N1570 draft of C11 Std.
 - N1256 draft of C99 Std.
 - http://port70.net/~nsz/c/c89/c89-draft.html draft of C89/C90 Std.
 */
 /*
+C23,5.2.5.3.3p21,   pp. 25
 C11,5.2.4.2.2p11,   pp. 30
 C99,5.2.4.2.2p9,pp. 25
 C89,2.2.4.2
@@ -207,6 +211,23 @@
 #error "Mandatory macros {FLT,DBL,LDBL}_MAX_10_EXP are invalid."
 #endif
 
+#if __STDC_VERSION__ >

[clang] fb463e1 - [C23] Remove WG14 N2379 from the C status page

2024-06-25 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2024-06-25T10:34:39-04:00
New Revision: fb463e154e7fe1200b9d91f82fafa532331ce764

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

LOG: [C23] Remove WG14 N2379 from the C status page

This paper was adopted at the Oct 2019 meeting in Ithaca, but the
changes from the paper were later removed (editorially) by the C
Floating Point study group due to being incorrect and unnecessary.

Added: 


Modified: 
clang/www/c_status.html

Removed: 




diff  --git a/clang/www/c_status.html b/clang/www/c_status.html
index 25656c0304da1..04c1df9ebc050 100644
--- a/clang/www/c_status.html
+++ b/clang/www/c_status.html
@@ -747,11 +747,8 @@ C23 implementation status
   Clang 15
 
 
-
-  *_IS_IEC_60559 feature test macros
-  https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2379.htm";>N2379
-  Unknown
-
+
 
   Annex F.8 update for implementation extensions and rounding
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2384.pdf";>N2384



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


[clang] [compiler-rt] [libcxx] [libunwind] [llvm] [openmp] [cmake] switch to CMake's native `check_{compiler,linker}_flag` (PR #96171)

2024-06-25 Thread Louis Dionne via cfe-commits

ldionne wrote:

@h-vetinari This one still looks like a real issue: 
https://buildkite.com/llvm-project/github-pull-requests/builds/74912#01903ca1-8089-4388-afdb-b65d400e6315

The rest looks good indeed.

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


[clang] [clang][test] Avoid writing to a potentially write-protected dir (PR #96457)

2024-06-25 Thread Mariya Podchishchaeva via cfe-commits

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

Whoops, sorry about that mistake in the test. The patch is LGTM. Thanks!

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


[clang] [LinkerWrapper][NFC] Simplify StringErrors (PR #96650)

2024-06-25 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 created 
https://github.com/llvm/llvm-project/pull/96650

Summary:
The StringError class has a specialized method that creates the
inconvertible error code for you. It's much easier to read this way.


>From 6860d0101f8babac086156087854e8f94e4f233e Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Tue, 25 Jun 2024 10:00:37 -0500
Subject: [PATCH] [LinkerWrapper][NFC] Simplify StringErrors

Summary:
The StringError class has a specialized method that creates the
inconvertible error code for you. It's much easier to read this way.
---
 .../ClangLinkerWrapper.cpp| 53 ---
 1 file changed, 21 insertions(+), 32 deletions(-)

diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index cdfe8cfbd9379..9027076119cf9 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -224,9 +224,8 @@ Error executeCommands(StringRef ExecutablePath, 
ArrayRef Args) {
 
   if (!DryRun)
 if (sys::ExecuteAndWait(ExecutablePath, Args))
-  return createStringError(inconvertibleErrorCode(),
-   "'" + sys::path::filename(ExecutablePath) + "'" 
+
-   " failed");
+  return createStringError(
+  "'%s' failed", sys::path::filename(ExecutablePath).str().c_str());
   return Error::success();
 }
 
@@ -259,7 +258,6 @@ Error relocateOffloadSection(const ArgList &Args, StringRef 
Output) {
   Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple()));
   if (Triple.isOSWindows())
 return createStringError(
-inconvertibleErrorCode(),
 "Relocatable linking is not supported on COFF targets");
 
   Expected ObjcopyPath =
@@ -272,8 +270,7 @@ Error relocateOffloadSection(const ArgList &Args, StringRef 
Output) {
   auto BufferOrErr = DryRun ? MemoryBuffer::getMemBuffer("")
 : MemoryBuffer::getFileOrSTDIN(Output);
   if (!BufferOrErr)
-return createStringError(inconvertibleErrorCode(), "Failed to open %s",
- Output.str().c_str());
+return createStringError("Failed to open %s", Output.str().c_str());
   std::string Suffix = "_" + getHash((*BufferOrErr)->getBuffer());
 
   SmallVector ObjcopyArgs = {
@@ -492,8 +489,7 @@ Expected clang(ArrayRef InputFiles, 
const ArgList &Args) {
 
 file_magic Magic;
 if (auto EC = identify_magic(Arg->getValue(), Magic))
-  return createStringError(inconvertibleErrorCode(),
-   "Failed to open %s", Arg->getValue());
+  return createStringError("Failed to open %s", Arg->getValue());
 if (Magic != file_magic::archive &&
 Magic != file_magic::elf_shared_object)
   continue;
@@ -568,9 +564,8 @@ Expected linkDevice(ArrayRef 
InputFiles,
   case Triple::systemz:
 return generic::clang(InputFiles, Args);
   default:
-return createStringError(inconvertibleErrorCode(),
- Triple.getArchName() +
- " linking is not supported");
+return createStringError(Triple.getArchName() +
+ " linking is not supported");
   }
 }
 
@@ -881,15 +876,13 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
 return Err;
 
   if (LTOError)
-return createStringError(inconvertibleErrorCode(),
- "Errors encountered inside the LTO pipeline.");
+return createStringError("Errors encountered inside the LTO pipeline.");
 
   // If we are embedding bitcode we only need the intermediate output.
   bool SingleOutput = Files.size() == 1;
   if (Args.hasArg(OPT_embed_bitcode)) {
 if (BitcodeOutput.size() != 1 || !SingleOutput)
-  return createStringError(inconvertibleErrorCode(),
-   "Cannot embed bitcode with multiple files.");
+  return createStringError("Cannot embed bitcode with multiple files.");
 OutputFiles.push_back(Args.MakeArgString(BitcodeOutput.front()));
 return Error::success();
   }
@@ -936,7 +929,7 @@ Expected compileModule(Module &M, OffloadKind 
Kind) {
   std::string Msg;
   const Target *T = TargetRegistry::lookupTarget(M.getTargetTriple(), Msg);
   if (!T)
-return createStringError(inconvertibleErrorCode(), Msg);
+return createStringError(Msg);
 
   auto Options =
   codegen::InitTargetOptionsFromCodeGenFlags(Triple(M.getTargetTriple()));
@@ -966,8 +959,7 @@ Expected compileModule(Module &M, OffloadKind 
Kind) {
   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
   if (TM->addPassesToEmitFile(CodeGenPasses, *OS, nullptr,
   CodeGenFileType::ObjectFile))
-return createStringError(inconvertibleErrorCode(),
- "Failed to execute host backend");
+return createStringError("Failed to execute host backe

[clang] [LinkerWrapper][NFC] Simplify StringErrors (PR #96650)

2024-06-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Joseph Huber (jhuber6)


Changes

Summary:
The StringError class has a specialized method that creates the
inconvertible error code for you. It's much easier to read this way.


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


1 Files Affected:

- (modified) clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp (+21-32) 


``diff
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index cdfe8cfbd9379..9027076119cf9 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -224,9 +224,8 @@ Error executeCommands(StringRef ExecutablePath, 
ArrayRef Args) {
 
   if (!DryRun)
 if (sys::ExecuteAndWait(ExecutablePath, Args))
-  return createStringError(inconvertibleErrorCode(),
-   "'" + sys::path::filename(ExecutablePath) + "'" 
+
-   " failed");
+  return createStringError(
+  "'%s' failed", sys::path::filename(ExecutablePath).str().c_str());
   return Error::success();
 }
 
@@ -259,7 +258,6 @@ Error relocateOffloadSection(const ArgList &Args, StringRef 
Output) {
   Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple()));
   if (Triple.isOSWindows())
 return createStringError(
-inconvertibleErrorCode(),
 "Relocatable linking is not supported on COFF targets");
 
   Expected ObjcopyPath =
@@ -272,8 +270,7 @@ Error relocateOffloadSection(const ArgList &Args, StringRef 
Output) {
   auto BufferOrErr = DryRun ? MemoryBuffer::getMemBuffer("")
 : MemoryBuffer::getFileOrSTDIN(Output);
   if (!BufferOrErr)
-return createStringError(inconvertibleErrorCode(), "Failed to open %s",
- Output.str().c_str());
+return createStringError("Failed to open %s", Output.str().c_str());
   std::string Suffix = "_" + getHash((*BufferOrErr)->getBuffer());
 
   SmallVector ObjcopyArgs = {
@@ -492,8 +489,7 @@ Expected clang(ArrayRef InputFiles, 
const ArgList &Args) {
 
 file_magic Magic;
 if (auto EC = identify_magic(Arg->getValue(), Magic))
-  return createStringError(inconvertibleErrorCode(),
-   "Failed to open %s", Arg->getValue());
+  return createStringError("Failed to open %s", Arg->getValue());
 if (Magic != file_magic::archive &&
 Magic != file_magic::elf_shared_object)
   continue;
@@ -568,9 +564,8 @@ Expected linkDevice(ArrayRef 
InputFiles,
   case Triple::systemz:
 return generic::clang(InputFiles, Args);
   default:
-return createStringError(inconvertibleErrorCode(),
- Triple.getArchName() +
- " linking is not supported");
+return createStringError(Triple.getArchName() +
+ " linking is not supported");
   }
 }
 
@@ -881,15 +876,13 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
 return Err;
 
   if (LTOError)
-return createStringError(inconvertibleErrorCode(),
- "Errors encountered inside the LTO pipeline.");
+return createStringError("Errors encountered inside the LTO pipeline.");
 
   // If we are embedding bitcode we only need the intermediate output.
   bool SingleOutput = Files.size() == 1;
   if (Args.hasArg(OPT_embed_bitcode)) {
 if (BitcodeOutput.size() != 1 || !SingleOutput)
-  return createStringError(inconvertibleErrorCode(),
-   "Cannot embed bitcode with multiple files.");
+  return createStringError("Cannot embed bitcode with multiple files.");
 OutputFiles.push_back(Args.MakeArgString(BitcodeOutput.front()));
 return Error::success();
   }
@@ -936,7 +929,7 @@ Expected compileModule(Module &M, OffloadKind 
Kind) {
   std::string Msg;
   const Target *T = TargetRegistry::lookupTarget(M.getTargetTriple(), Msg);
   if (!T)
-return createStringError(inconvertibleErrorCode(), Msg);
+return createStringError(Msg);
 
   auto Options =
   codegen::InitTargetOptionsFromCodeGenFlags(Triple(M.getTargetTriple()));
@@ -966,8 +959,7 @@ Expected compileModule(Module &M, OffloadKind 
Kind) {
   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
   if (TM->addPassesToEmitFile(CodeGenPasses, *OS, nullptr,
   CodeGenFileType::ObjectFile))
-return createStringError(inconvertibleErrorCode(),
- "Failed to execute host backend");
+return createStringError("Failed to execute host backend");
   CodeGenPasses.run(M);
 
   return *TempFileOrErr;
@@ -1012,9 +1004,8 @@ wrapDeviceImages(ArrayRef> 
Buffers,
   return std::move(Err);
 break;
   default:
-return createStringError(inconvertibleErrorCode(),
- getOffloadKind

[clang] [llvm] [clang][OpenMP] Shorten directive classification in ParseOpenMP (PR #94691)

2024-06-25 Thread Krzysztof Parzyszek via cfe-commits


@@ -2374,86 +2374,209 @@ Parser::DeclGroupPtrTy 
Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl(
   case OMPD_unknown:
 Diag(Tok, diag::err_omp_unknown_directive);
 break;
-  case OMPD_parallel:
-  case OMPD_simd:
-  case OMPD_tile:
-  case OMPD_unroll:
-  case OMPD_task:
-  case OMPD_taskyield:
+  default:
+switch (getDirectiveCategory(DKind)) {
+case Category::Executable:
+case Category::Meta:
+case Category::Subsidiary:
+case Category::Utility:
+  Diag(Tok, diag::err_omp_unexpected_directive)
+  << 1 << getOpenMPDirectiveName(DKind);
+  break;
+default:
+  break;

kparzysz wrote:

Done.

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


[clang] [llvm] [clang][OpenMP] Shorten directive classification in ParseOpenMP (PR #94691)

2024-06-25 Thread Krzysztof Parzyszek via cfe-commits


@@ -2374,86 +2374,209 @@ Parser::DeclGroupPtrTy 
Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl(
   case OMPD_unknown:
 Diag(Tok, diag::err_omp_unknown_directive);
 break;
-  case OMPD_parallel:
-  case OMPD_simd:
-  case OMPD_tile:
-  case OMPD_unroll:
-  case OMPD_task:
-  case OMPD_taskyield:
+  default:
+switch (getDirectiveCategory(DKind)) {
+case Category::Executable:
+case Category::Meta:
+case Category::Subsidiary:
+case Category::Utility:
+  Diag(Tok, diag::err_omp_unexpected_directive)
+  << 1 << getOpenMPDirectiveName(DKind);
+  break;
+default:
+  break;
+}
+  }
+  while (Tok.isNot(tok::annot_pragma_openmp_end))
+ConsumeAnyToken();
+  ConsumeAnyToken();
+  return nullptr;
+}
+
+StmtResult Parser::ParseOpenMPExecutableDirective(
+ParsedStmtContext StmtCtx, OpenMPDirectiveKind DKind, SourceLocation Loc,
+bool ReadDirectiveWithinMetadirective) {
+  bool HasAssociatedStatement = true;
+
+  switch (DKind) {

kparzysz wrote:

Done

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


[clang] [C23] Add *_NORM_MAX macros to (PR #96643)

2024-06-25 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman updated 
https://github.com/llvm/llvm-project/pull/96643

>From 408c34b84966a256bb6e7fdf45758f5c77380bbe Mon Sep 17 00:00:00 2001
From: Aaron Ballman 
Date: Tue, 25 Jun 2024 10:27:10 -0400
Subject: [PATCH 1/2] [C23] Add *_NORM_MAX macros to 

This adds the *_NORM_MAX macros to  for freestanding mode in
Clang; the values were chosen based on the behavior seen coming from
GCC and the values already produced for the *_MAX macros by Clang.
---
 clang/docs/ReleaseNotes.rst |  3 +++
 clang/lib/Frontend/InitPreprocessor.cpp |  7 ++-
 clang/lib/Headers/float.h   | 13 
 clang/test/Headers/float.c  | 27 +
 4 files changed, 49 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index df579ae398c5e..8879a77ba4dd9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -336,6 +336,9 @@ C23 Feature Support
 - Properly promote bit-fields of bit-precise integer types to the field's type
   rather than to ``int``. #GH87641
 
+- Added the ``FLT_NORM_MAX``, ``DBL_NORM_MAX``, and ``LDBL_NORM_MAX`` to the
+  freestanding implementation of  that ships with Clang.
+
 Non-comprehensive list of changes in this release
 -
 
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 55ec460064830..afc4c16ab685b 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -113,7 +113,11 @@ static T PickFP(const llvm::fltSemantics *Sem, T 
IEEEHalfVal, T IEEESingleVal,
 
 static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix,
   const llvm::fltSemantics *Sem, StringRef Ext) {
-  const char *DenormMin, *Epsilon, *Max, *Min;
+  const char *DenormMin, *NormMax, *Epsilon, *Max, *Min;
+  NormMax = PickFP(Sem, "6.5504e+4", "3.40282347e+38",
+   "1.7976931348623157e+308", "1.18973149535723176502e+4932",
+   "1.79769313486231580793728971405301e+308",
+   "1.18973149535723176508575932662800702e+4932");
   DenormMin = PickFP(Sem, "5.9604644775390625e-8", "1.40129846e-45",
  "4.9406564584124654e-324", "3.64519953188247460253e-4951",
  "4.94065645841246544176568792868221e-324",
@@ -144,6 +148,7 @@ static void DefineFloatMacros(MacroBuilder &Builder, 
StringRef Prefix,
   DefPrefix += "_";
 
   Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext);
+  Builder.defineMacro(DefPrefix + "NORM_MAX__", Twine(NormMax)+Ext);
   Builder.defineMacro(DefPrefix + "HAS_DENORM__");
   Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
   Builder.defineMacro(DefPrefix + "DECIMAL_DIG__", Twine(DecimalDigits));
diff --git a/clang/lib/Headers/float.h b/clang/lib/Headers/float.h
index 642c8f06cc938..61f65dad8debc 100644
--- a/clang/lib/Headers/float.h
+++ b/clang/lib/Headers/float.h
@@ -86,6 +86,12 @@
 #undef DBL_HAS_SUBNORM
 #undef LDBL_HAS_SUBNORM
 #  endif
+#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) ||  
\
+!defined(__STRICT_ANSI__)
+#undef FLT_NORM_MAX
+#undef DBL_NORM_MAX
+#undef LDBL_NORM_MAX
+#endif
 #endif
 
 /* Characteristics of floating point types, C99 5.2.4.2.2 */
@@ -155,6 +161,13 @@
 #  define LDBL_HAS_SUBNORM __LDBL_HAS_DENORM__
 #endif
 
+#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) ||  
\
+!defined(__STRICT_ANSI__)
+#  define FLT_NORM_MAX __FLT_NORM_MAX__
+#  define DBL_NORM_MAX __DBL_NORM_MAX__
+#  define LDBL_NORM_MAX __LDBL_NORM_MAX__
+#endif
+
 #ifdef __STDC_WANT_IEC_60559_TYPES_EXT__
 #  define FLT16_MANT_DIG__FLT16_MANT_DIG__
 #  define FLT16_DECIMAL_DIG __FLT16_DECIMAL_DIG__
diff --git a/clang/test/Headers/float.c b/clang/test/Headers/float.c
index 70c11b0537537..59cc0faa074db 100644
--- a/clang/test/Headers/float.c
+++ b/clang/test/Headers/float.c
@@ -1,17 +1,21 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c89 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c99 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c11 -ffreestanding %s
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c23 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -xc++ -std=c++11 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -xc++ -std=c++14 -ffreestanding %s
 // RUN: %clang_cc1 -fsyntax-only -verify -xc++ -std=c++17 -ffreestanding %s
+// RUN: %clang_cc1 -fsyntax-only -verify -xc++ -std=c++23 -ffreestanding %s
 // expected-no-diagnostics
 
 /* Basic floating point conformance checks against:
+- C23 Final Std.
 - N1570 draft of C11 Std.
 - N1256 draft of C99 Std.
 - http://port70.net/~nsz/c/c89/c89-draft.html draft of C89/C90 Std.
 */
 /*
+C23,5.2.5.3.3p21,   pp. 25
 C11,5.2.4.2.2p11,   pp. 30
 C99,5.2.4.2.2p9,pp. 25

[clang] [C23] Add *_NORM_MAX macros to (PR #96643)

2024-06-25 Thread Aaron Ballman via cfe-commits

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


[clang] [C23] Add *_NORM_MAX macros to (PR #96643)

2024-06-25 Thread Aaron Ballman via cfe-commits

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


[clang] [C23] Add *_NORM_MAX macros to (PR #96643)

2024-06-25 Thread Aaron Ballman via cfe-commits

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


[clang] [C23] Add *_NORM_MAX macros to (PR #96643)

2024-06-25 Thread Aaron Ballman via cfe-commits

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


[clang] [C23] Add *_NORM_MAX macros to (PR #96643)

2024-06-25 Thread Aaron Ballman via cfe-commits

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


[clang] Improve error message for invalid lambda captures (PR #94865)

2024-06-25 Thread via cfe-commits

https://github.com/CedricSwa updated 
https://github.com/llvm/llvm-project/pull/94865

>From 012849c5410960001ca5bbcb90ea2cf4a661b840 Mon Sep 17 00:00:00 2001
From: Cedric Schwarzer 
Date: Sat, 8 Jun 2024 17:52:02 +0200
Subject: [PATCH 1/3] Improve error message for invalid lambda captures

---
 clang/include/clang/Basic/DiagnosticSemaKinds.td | 2 ++
 clang/lib/Sema/SemaLambda.cpp| 7 ++-
 2 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 9f0b6f5a36389..fdf4409125c00 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -8173,6 +8173,8 @@ let CategoryName = "Lambda Issue" in {
 "'&' must precede a capture when the capture default is '='">;
   def err_capture_does_not_name_variable : Error<
 "%0 in capture list does not name a variable">;
+  def err_capture_class_member_does_not_name_variable : Error<
+"class member %0 cannot appear in capture list as it is not a variable">;
   def err_capture_non_automatic_variable : Error<
 "%0 cannot be captured because it does not have automatic storage "
 "duration">;
diff --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp
index e9476a0c93c5d..79c10c3bad6d7 100644
--- a/clang/lib/Sema/SemaLambda.cpp
+++ b/clang/lib/Sema/SemaLambda.cpp
@@ -1246,7 +1246,12 @@ void 
Sema::ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
 
   if (auto *BD = R.getAsSingle())
 Var = BD;
-  else
+  else if (auto *FD = R.getAsSingle()) {
+Var = R.getAsSingle();
+Diag(C->Loc, diag::err_capture_class_member_does_not_name_variable)
+<< C->Id;
+continue;
+  } else
 Var = R.getAsSingle();
   if (Var && DiagnoseUseOfDecl(Var, C->Loc))
 continue;

>From dc1ca518ea4a4b5407decd9d99e561282cf7f4e4 Mon Sep 17 00:00:00 2001
From: "cedric.SWA" 
Date: Mon, 10 Jun 2024 20:48:59 +0200
Subject: [PATCH 2/3] remove unnecessary variable assignment

---
 clang/lib/Sema/SemaLambda.cpp | 1 -
 1 file changed, 1 deletion(-)

diff --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp
index 79c10c3bad6d7..97f1d9428fef6 100644
--- a/clang/lib/Sema/SemaLambda.cpp
+++ b/clang/lib/Sema/SemaLambda.cpp
@@ -1247,7 +1247,6 @@ void 
Sema::ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
   if (auto *BD = R.getAsSingle())
 Var = BD;
   else if (auto *FD = R.getAsSingle()) {
-Var = R.getAsSingle();
 Diag(C->Loc, diag::err_capture_class_member_does_not_name_variable)
 << C->Id;
 continue;

>From 9ec08c86a22060a42996fdbc131a864e16ccb0d8 Mon Sep 17 00:00:00 2001
From: "cedric.SWA" 
Date: Tue, 25 Jun 2024 17:09:39 +0200
Subject: [PATCH 3/3] test for lambda try captureing class member

---
 clang/test/SemaCXX/lambda-expressions.cpp | 9 +
 1 file changed, 9 insertions(+)

diff --git a/clang/test/SemaCXX/lambda-expressions.cpp 
b/clang/test/SemaCXX/lambda-expressions.cpp
index 151d74f21d64d..acf8d014a9896 100644
--- a/clang/test/SemaCXX/lambda-expressions.cpp
+++ b/clang/test/SemaCXX/lambda-expressions.cpp
@@ -609,6 +609,15 @@ namespace PR25627_dont_odr_use_local_consts {
   }
 }
 
+namespace PR94764 {
+  struct X {
+int x;
+void foo() {
+  [x](){}; // expected-error{{class member 'x' cannot appear in capture 
list as it is not a variable}}
+}
+  };
+}
+
 namespace ConversionOperatorDoesNotHaveDeducedReturnType {
   auto x = [](int){};
   auto y = [](auto &v) -> void { v.n = 0; }; // cxx03-cxx11-error {{'auto' not 
allowed in lambda parameter}} cxx03-cxx11-note {{candidate function not 
viable}} cxx03-cxx11-note {{conversion candidate}}

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


[clang] [C23] Add *_NORM_MAX macros to (PR #96643)

2024-06-25 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 2ae09052477e1a966afbc5482d88585f95694c53 
486d9fb3f9f992831569e4b9e1eda0a54c777b3b --extensions 'h,cpp,c' -- 
clang/lib/Frontend/InitPreprocessor.cpp clang/lib/Headers/float.h 
clang/test/Headers/float.c clang/test/Preprocessor/init-aarch64.c 
clang/test/Preprocessor/init.c
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index afc4c16ab6..d3b264eede 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -148,7 +148,7 @@ static void DefineFloatMacros(MacroBuilder &Builder, 
StringRef Prefix,
   DefPrefix += "_";
 
   Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext);
-  Builder.defineMacro(DefPrefix + "NORM_MAX__", Twine(NormMax)+Ext);
+  Builder.defineMacro(DefPrefix + "NORM_MAX__", Twine(NormMax) + Ext);
   Builder.defineMacro(DefPrefix + "HAS_DENORM__");
   Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
   Builder.defineMacro(DefPrefix + "DECIMAL_DIG__", Twine(DecimalDigits));

``




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


[clang] Improve error message for invalid lambda captures (PR #94865)

2024-06-25 Thread via cfe-commits

CedricSwa wrote:

not sure if lambda expression is the best file but for lambda-invalid-capture i 
would need to add -Wno-unused-value to both run statements.

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


[clang] [Doc] Update documentation for no-transitive-change (PR #96453)

2024-06-25 Thread Ilya Biryukov via cfe-commits

ilya-biryukov wrote:

> > I really like the idea of documenting this, hopefully this create some 
> > fruitful discussions with the build system developers and other compiler 
> > users.
> > After trying to put myself into the shoes of the compiler users reading 
> > this, I can't help but think that the "no transitive changes" is slightly 
> > confusing and hard to grasp. The example does help quite a bit, but I also 
> > feel there should be a way to document this in shorter form. (E.g. we can 
> > double-down on the "this is a build optimization" angle and being explicit 
> > that we want people to try this and let them know how to report bugs about 
> > it?)
> > I wanted to take a little bit of time to think how to do it before 
> > providing concrete suggestions, but still wanted to mention this.
> 
> How about adding a sentence like "this section is primarily for build system 
> vendors. For end compiler users, if you don't want to read it all, this is 
> helpful to reduce recompilations. We encourage build system vendors and end 
> users try this out and bring feedbacks"?

Yeah, SG, I'd also recommend adding something like that to the release notes (I 
suspect many more people will read it initially when Clang 19 is released than 
the section on C++20 Modules)

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


[clang] 8a46bbb - [Clang] Remove preprocessor guards and global feature checks for NEON (#95224)

2024-06-25 Thread via cfe-commits

Author: Lukacma
Date: 2024-06-25T17:19:42+02:00
New Revision: 8a46bbbc22a51db57f05beb0026772b899a785b9

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

LOG: [Clang] Remove preprocessor guards and global feature checks for NEON 
(#95224)

To enable function multi-versioning (FMV), current checks which rely on
cmd line options or global macros to see if target feature is present
need to be removed. This patch removes those for NEON and also
implements changes to NEON header file as proposed in
[ACLE](https://github.com/ARM-software/acle/pull/321).

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaType.cpp
clang/test/Sema/arm-vector-types-support.c
clang/utils/TableGen/NeonEmitter.cpp

Removed: 
clang/test/SemaCUDA/neon-attrs.cu



diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 46ad359751d7d..af8d75f76a7d7 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3246,6 +3246,9 @@ def warn_unsupported_target_attribute
 def err_attribute_unsupported
 : Error<"%0 attribute is not supported on targets missing %1;"
 " specify an appropriate -march= or -mcpu=">;
+def err_attribute_unsupported_m_profile
+: Error<"on M-profile architectures %0 attribute is not supported on 
targets missing %1;"
+" specify an appropriate -march= or -mcpu=">;
 def err_duplicate_target_attribute
 : Error<"%select{unsupported|duplicate|unknown}0%select{| CPU|"
   " tune CPU}1 '%2' in the 
'%select{target|target_clones|target_version}3' "

diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 53b9083c95c1b..308274720d58d 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -8203,23 +8203,19 @@ static void HandleNeonVectorTypeAttr(QualType &CurType, 
const ParsedAttr &Attr,
 
   // Target must have NEON (or MVE, whose vectors are similar enough
   // not to need a separate attribute)
-  if (!(S.Context.getTargetInfo().hasFeature("neon") ||
-S.Context.getTargetInfo().hasFeature("mve") ||
-S.Context.getTargetInfo().hasFeature("sve") ||
-S.Context.getTargetInfo().hasFeature("sme") ||
-IsTargetCUDAAndHostARM) &&
-  VecKind == VectorKind::Neon) {
-S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
-<< Attr << "'neon', 'mve', 'sve' or 'sme'";
+  if (!S.Context.getTargetInfo().hasFeature("mve") &&
+  VecKind == VectorKind::Neon &&
+  S.Context.getTargetInfo().getTriple().isArmMClass()) {
+S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
+<< Attr << "'mve'";
 Attr.setInvalid();
 return;
   }
-  if (!(S.Context.getTargetInfo().hasFeature("neon") ||
-S.Context.getTargetInfo().hasFeature("mve") ||
-IsTargetCUDAAndHostARM) &&
-  VecKind == VectorKind::NeonPoly) {
-S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
-<< Attr << "'neon' or 'mve'";
+  if (!S.Context.getTargetInfo().hasFeature("mve") &&
+  VecKind == VectorKind::NeonPoly &&
+  S.Context.getTargetInfo().getTriple().isArmMClass()) {
+S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
+<< Attr << "'mve'";
 Attr.setInvalid();
 return;
   }

diff  --git a/clang/test/Sema/arm-vector-types-support.c 
b/clang/test/Sema/arm-vector-types-support.c
index ed5f5ba175a94..8b8c9634631d0 100644
--- a/clang/test/Sema/arm-vector-types-support.c
+++ b/clang/test/Sema/arm-vector-types-support.c
@@ -1,7 +1,8 @@
-// RUN: %clang_cc1 %s -triple armv7 -fsyntax-only -verify
-// RUN: %clang_cc1 %s -triple aarch64 -fsyntax-only -verify
-// RUN: %clang_cc1 %s -triple aarch64 -target-feature -fp-armv8 -target-abi 
aapcs-soft -fsyntax-only -verify
+// RUN: %clang_cc1 %s -triple armv8.1m.main -fsyntax-only -verify
+// RUN: %clang_cc1 %s -triple aarch64 -fsyntax-only -verify=sve-type
+// RUN: %clang_cc1 %s -triple aarch64 -target-feature -fp-armv8 -target-abi 
aapcs-soft -fsyntax-only -verify=sve-type
 
-typedef __attribute__((neon_vector_type(2))) int int32x2_t; // 
expected-error{{'neon_vector_type' attribute is not supported on targets 
missing 'neon', 'mve', 'sve' or 'sme'; specify an appropriate -march= or 
-mcpu=}}
-typedef __attribute__((neon_polyvector_type(16))) short poly8x16_t; // 
expected-error{{'neon_polyvector_type' attribute is not supported on targets 
missing 'neon' or 'mve'; specify an appropriate -march= or -mcpu=}}
+typedef __attribute__((neon_vector_type(2))) int int32x2_t; // 
expected-error{{on M-profile architectures 'neon_vector_type' attribute is not 
supported on targets missing 'mve'; specify an appropriate -mar

[clang] [Clang] Remove preprocessor guards and global feature checks for NEON (PR #95224)

2024-06-25 Thread via cfe-commits

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


[clang] [Clang] Access tls_guard via llvm.threadlocal.address (PR #96633)

2024-06-25 Thread via cfe-commits

nikola-tesic-ns wrote:

@nikic @ChuanqiXu9 
I couldn't add you to the reviewers list. Please, take a look at this fix. 
Thanks!

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


  1   2   3   4   >