[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-08 Thread Heejin Ahn via cfe-commits

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


[clang] [clang] Add optional pass to remove UBSAN traps using PGO (PR #84214)

2024-03-08 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka updated 
https://github.com/llvm/llvm-project/pull/84214

>From feb5bfa786d1660a7fe0b6c48ec9048cdd315800 Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 6 Mar 2024 10:03:46 -0800
Subject: [PATCH 1/6] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20in?=
 =?UTF-8?q?itial=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4
---
 clang/lib/CodeGen/BackendUtil.cpp   | 17 +
 clang/test/CodeGen/remote-traps.cpp | 15 +++
 2 files changed, 32 insertions(+)
 create mode 100644 clang/test/CodeGen/remote-traps.cpp

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 7310e3817c79a1..d89e53f69c4a51 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -76,6 +76,7 @@
 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
+#include "llvm/Transforms/Instrumentation/RemoveTrapsPass.h"
 #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
@@ -83,6 +84,7 @@
 #include "llvm/Transforms/Scalar/EarlyCSE.h"
 #include "llvm/Transforms/Scalar/GVN.h"
 #include "llvm/Transforms/Scalar/JumpThreading.h"
+#include "llvm/Transforms/Scalar/SimplifyCFG.h"
 #include "llvm/Transforms/Utils/Debugify.h"
 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
 #include "llvm/Transforms/Utils/ModuleUtils.h"
@@ -98,6 +100,10 @@ using namespace llvm;
 namespace llvm {
 extern cl::opt PrintPipelinePasses;
 
+cl::opt ClRemoveTraps("clang-remove-traps", cl::Optional,
+cl::desc("Insert remove-traps pass."),
+cl::init(false));
+
 // Experiment to move sanitizers earlier.
 static cl::opt ClSanitizeOnOptimizerEarlyEP(
 "sanitizer-early-opt-ep", cl::Optional,
@@ -744,6 +750,17 @@ static void addSanitizers(const Triple &TargetTriple,
 // LastEP does not need GlobalsAA.
 PB.registerOptimizerLastEPCallback(SanitizersCallback);
   }
+
+  if (ClRemoveTraps) {
+PB.registerOptimizerEarlyEPCallback([&](ModulePassManager &MPM,
+OptimizationLevel Level) {
+  FunctionPassManager FPM;
+  FPM.addPass(RemoveTrapsPass());
+  FPM.addPass(
+  
SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
+  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
+});
+  }
 }
 
 void EmitAssemblyHelper::RunOptimizationPipeline(
diff --git a/clang/test/CodeGen/remote-traps.cpp 
b/clang/test/CodeGen/remote-traps.cpp
new file mode 100644
index 00..7d4eb76a7d81e9
--- /dev/null
+++ b/clang/test/CodeGen/remote-traps.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -O1 -emit-llvm -fsanitize=signed-integer-overflow 
-fsanitize-trap=signed-integer-overflow %s -o - | FileCheck %s 
+// RUN: %clang_cc1 -O1 -emit-llvm -fsanitize=signed-integer-overflow 
-fsanitize-trap=signed-integer-overflow -mllvm -clang-remove-traps -mllvm 
-remove-traps-random-rate=1 %s -o - | FileCheck %s --implicit-check-not="call 
void @llvm.ubsantrap" --check-prefixes=REMOVE
+
+int f(int x) {
+  return x + 123;
+}
+
+// CHECK-LABEL: define dso_local noundef i32 @_Z1fi(
+// CHECK: call { i32, i1 } @llvm.sadd.with.overflow.i32(
+// CHECK: trap:
+// CHECK-NEXT: call void @llvm.ubsantrap(i8 0)
+// CHECK-NEXT: unreachable, !nosanitize !2 
+
+// REMOVE-LABEL: define dso_local noundef i32 @_Z1fi(
+// REMOVE: call { i32, i1 } @llvm.sadd.with.overflow.i32(

>From 0b2b44e04b8c900c29f52e340ebdfc6824607773 Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 6 Mar 2024 10:08:47 -0800
Subject: [PATCH 2/6] comment

Created using spr 1.3.4
---
 clang/lib/CodeGen/BackendUtil.cpp | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index d89e53f69c4a51..fa49a364cf5600 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -752,6 +752,9 @@ static void addSanitizers(const Triple &TargetTriple,
   }
 
   if (ClRemoveTraps) {
+// We can optimize after inliner, and PGO profile matching, which are part
+// of `buildModuleSimplificationPipeline`. The hook below is called after
+// that, from `buildModuleOptimizationPipeline`.
 PB.registerOptimizerEarlyEPCallback([&](ModulePassManager &MPM,
 OptimizationLevel Level) {
   FunctionPassManager FPM;

>From 000854eb9d18cd9cfd6eaf7d29e5954fb18d454c Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 6 Mar 2024 10:22:16 -0800
Subject: [PATCH 3/6] comment

Created using spr 1.3.4
---
 clang/lib/CodeGen/BackendUtil.cpp | 7 ---
 1 file changed, 4 insertions(+), 3 deletions(-)

[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-08 Thread Heejin Ahn via cfe-commits

aheejin wrote:

> In terms of getting this landed and tested, I wonder which path we should 
> take:
> 
> 1. Land this now, without tests, then update emscripten then come back and 
> flip the default, at which point the existing tests will get updated.
> 2. Duplicate/update the the existing tests to tests both modes, then delete 
> those changes once we flip the default.
> 
> Personally I think I'd be happy with (1) since this is a behind and 
> experimental flag.
> 
> What do others think? @aheejin ?

Come to think of it, should we even introduce this experimental option? Adding 
`if (NewOption) ... else ...` everywhere makes the code complicated. Can we 
just do
1. Add library functions in emscripten
2. Replace the current logic in LLVM with new code. (Without `if`~`else`). 
Tests can be updated with this.
3. Remove old library functions in emscripten.
?

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


[clang] [clang] Add optional pass to remove UBSAN traps using PGO (PR #84214)

2024-03-08 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka updated 
https://github.com/llvm/llvm-project/pull/84214

>From feb5bfa786d1660a7fe0b6c48ec9048cdd315800 Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 6 Mar 2024 10:03:46 -0800
Subject: [PATCH 1/5] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20in?=
 =?UTF-8?q?itial=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4
---
 clang/lib/CodeGen/BackendUtil.cpp   | 17 +
 clang/test/CodeGen/remote-traps.cpp | 15 +++
 2 files changed, 32 insertions(+)
 create mode 100644 clang/test/CodeGen/remote-traps.cpp

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 7310e3817c79a1..d89e53f69c4a51 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -76,6 +76,7 @@
 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
+#include "llvm/Transforms/Instrumentation/RemoveTrapsPass.h"
 #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
@@ -83,6 +84,7 @@
 #include "llvm/Transforms/Scalar/EarlyCSE.h"
 #include "llvm/Transforms/Scalar/GVN.h"
 #include "llvm/Transforms/Scalar/JumpThreading.h"
+#include "llvm/Transforms/Scalar/SimplifyCFG.h"
 #include "llvm/Transforms/Utils/Debugify.h"
 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
 #include "llvm/Transforms/Utils/ModuleUtils.h"
@@ -98,6 +100,10 @@ using namespace llvm;
 namespace llvm {
 extern cl::opt PrintPipelinePasses;
 
+cl::opt ClRemoveTraps("clang-remove-traps", cl::Optional,
+cl::desc("Insert remove-traps pass."),
+cl::init(false));
+
 // Experiment to move sanitizers earlier.
 static cl::opt ClSanitizeOnOptimizerEarlyEP(
 "sanitizer-early-opt-ep", cl::Optional,
@@ -744,6 +750,17 @@ static void addSanitizers(const Triple &TargetTriple,
 // LastEP does not need GlobalsAA.
 PB.registerOptimizerLastEPCallback(SanitizersCallback);
   }
+
+  if (ClRemoveTraps) {
+PB.registerOptimizerEarlyEPCallback([&](ModulePassManager &MPM,
+OptimizationLevel Level) {
+  FunctionPassManager FPM;
+  FPM.addPass(RemoveTrapsPass());
+  FPM.addPass(
+  
SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
+  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
+});
+  }
 }
 
 void EmitAssemblyHelper::RunOptimizationPipeline(
diff --git a/clang/test/CodeGen/remote-traps.cpp 
b/clang/test/CodeGen/remote-traps.cpp
new file mode 100644
index 00..7d4eb76a7d81e9
--- /dev/null
+++ b/clang/test/CodeGen/remote-traps.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -O1 -emit-llvm -fsanitize=signed-integer-overflow 
-fsanitize-trap=signed-integer-overflow %s -o - | FileCheck %s 
+// RUN: %clang_cc1 -O1 -emit-llvm -fsanitize=signed-integer-overflow 
-fsanitize-trap=signed-integer-overflow -mllvm -clang-remove-traps -mllvm 
-remove-traps-random-rate=1 %s -o - | FileCheck %s --implicit-check-not="call 
void @llvm.ubsantrap" --check-prefixes=REMOVE
+
+int f(int x) {
+  return x + 123;
+}
+
+// CHECK-LABEL: define dso_local noundef i32 @_Z1fi(
+// CHECK: call { i32, i1 } @llvm.sadd.with.overflow.i32(
+// CHECK: trap:
+// CHECK-NEXT: call void @llvm.ubsantrap(i8 0)
+// CHECK-NEXT: unreachable, !nosanitize !2 
+
+// REMOVE-LABEL: define dso_local noundef i32 @_Z1fi(
+// REMOVE: call { i32, i1 } @llvm.sadd.with.overflow.i32(

>From 0b2b44e04b8c900c29f52e340ebdfc6824607773 Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 6 Mar 2024 10:08:47 -0800
Subject: [PATCH 2/5] comment

Created using spr 1.3.4
---
 clang/lib/CodeGen/BackendUtil.cpp | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index d89e53f69c4a51..fa49a364cf5600 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -752,6 +752,9 @@ static void addSanitizers(const Triple &TargetTriple,
   }
 
   if (ClRemoveTraps) {
+// We can optimize after inliner, and PGO profile matching, which are part
+// of `buildModuleSimplificationPipeline`. The hook below is called after
+// that, from `buildModuleOptimizationPipeline`.
 PB.registerOptimizerEarlyEPCallback([&](ModulePassManager &MPM,
 OptimizationLevel Level) {
   FunctionPassManager FPM;

>From 000854eb9d18cd9cfd6eaf7d29e5954fb18d454c Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 6 Mar 2024 10:22:16 -0800
Subject: [PATCH 3/5] comment

Created using spr 1.3.4
---
 clang/lib/CodeGen/BackendUtil.cpp | 7 ---
 1 file changed, 4 insertions(+), 3 deletions(-)

[clang] [clang-tools-extra] [llvm] [llvm][Support] Add and use errnoAsErrorCode (PR #84423)

2024-03-08 Thread Michael Spencer via cfe-commits

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


[clang] ba13fa2 - [llvm][Support] Add and use errnoAsErrorCode (#84423)

2024-03-08 Thread via cfe-commits

Author: Michael Spencer
Date: 2024-03-08T23:30:33-08:00
New Revision: ba13fa2a5d57581bff1a7e9322234af30f4882f6

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

LOG: [llvm][Support] Add and use errnoAsErrorCode (#84423)

LLVM is inconsistent about how it converts `errno` to `std::error_code`.
This can cause problems because values outside of `std::errc` compare
differently if one is system and one is generic on POSIX systems.

This is even more of a problem on Windows where use of the system
category is just wrong, as that is for Windows errors, which have a
completely different mapping than POSIX/generic errors. This patch fixes
one instance of this mistake in `JSONTransport.cpp`.

This patch adds `errnoAsErrorCode()` which makes it so people do not
need to think about this issue in the future. It also cleans up a lot of
usage of `errno` in LLVM and Clang.

Added: 


Modified: 
clang-tools-extra/clangd/JSONTransport.cpp
clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
llvm/include/llvm/Support/Error.h
llvm/lib/ExecutionEngine/Orc/MemoryMapper.cpp

llvm/lib/ExecutionEngine/Orc/TargetProcess/ExecutorSharedMemoryMapperService.cpp
llvm/lib/Object/ArchiveWriter.cpp
llvm/lib/Support/AutoConvert.cpp
llvm/lib/Support/LockFileManager.cpp
llvm/lib/Support/Path.cpp
llvm/lib/Support/RandomNumberGenerator.cpp
llvm/lib/Support/Unix/Memory.inc
llvm/lib/Support/Unix/Path.inc
llvm/lib/Support/Unix/Process.inc
llvm/lib/Support/Windows/Process.inc
llvm/lib/Support/Windows/Program.inc
llvm/lib/Support/raw_ostream.cpp
llvm/lib/Support/raw_socket_stream.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/JSONTransport.cpp 
b/clang-tools-extra/clangd/JSONTransport.cpp
index 346c7dfb66a1db..3c0e198433f360 100644
--- a/clang-tools-extra/clangd/JSONTransport.cpp
+++ b/clang-tools-extra/clangd/JSONTransport.cpp
@@ -107,8 +107,7 @@ class JSONTransport : public Transport {
 return error(std::make_error_code(std::errc::operation_canceled),
  "Got signal, shutting down");
   if (ferror(In))
-return llvm::errorCodeToError(
-std::error_code(errno, std::system_category()));
+return llvm::errorCodeToError(llvm::errnoAsErrorCode());
   if (readRawMessage(JSON)) {
 ThreadCrashReporter ScopedReporter([&JSON]() {
   auto &OS = llvm::errs();

diff  --git a/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp 
b/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
index beca9586988b52..2ffbc1a226958a 100644
--- a/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
+++ b/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
@@ -333,8 +333,7 @@ llvm::Expected> 
clang::DirectoryWatcher::creat
   const int InotifyFD = inotify_init1(IN_CLOEXEC);
   if (InotifyFD == -1)
 return llvm::make_error(
-std::string("inotify_init1() error: ") + strerror(errno),
-llvm::inconvertibleErrorCode());
+llvm::errnoAsErrorCode(), std::string(": inotify_init1()"));
 
   const int InotifyWD = inotify_add_watch(
   InotifyFD, Path.str().c_str(),
@@ -346,15 +345,13 @@ llvm::Expected> 
clang::DirectoryWatcher::creat
   );
   if (InotifyWD == -1)
 return llvm::make_error(
-std::string("inotify_add_watch() error: ") + strerror(errno),
-llvm::inconvertibleErrorCode());
+llvm::errnoAsErrorCode(), std::string(": inotify_add_watch()"));
 
   auto InotifyPollingStopper = SemaphorePipe::create();
 
   if (!InotifyPollingStopper)
 return llvm::make_error(
-std::string("SemaphorePipe::create() error: ") + strerror(errno),
-llvm::inconvertibleErrorCode());
+llvm::errnoAsErrorCode(), std::string(": SemaphorePipe::create()"));
 
   return std::make_unique(
   Path, Receiver, WaitForInitialSync, InotifyFD, InotifyWD,

diff  --git a/llvm/include/llvm/Support/Error.h 
b/llvm/include/llvm/Support/Error.h
index bb4f38f7ec355e..894b6484336aef 100644
--- a/llvm/include/llvm/Support/Error.h
+++ b/llvm/include/llvm/Support/Error.h
@@ -1180,6 +1180,20 @@ Error errorCodeToError(std::error_code EC);
 /// will trigger a call to abort().
 std::error_code errorToErrorCode(Error Err);
 
+/// Helper to get errno as an std::error_code.
+///
+/// errno should always be represented using the generic category as that's 
what
+/// both libc++ and libstdc++ do. On POSIX systems you can also represent them
+/// using the system category, however this makes them compare 
diff erently for
+/// values outside of those used by `std::errc` if one is generic and the other
+/// is system.
+///
+/// See the libc++ and libstdc++ implementations of `default_error_condition` 
on
+/// the system category for more

[clang-tools-extra] ba13fa2 - [llvm][Support] Add and use errnoAsErrorCode (#84423)

2024-03-08 Thread via cfe-commits

Author: Michael Spencer
Date: 2024-03-08T23:30:33-08:00
New Revision: ba13fa2a5d57581bff1a7e9322234af30f4882f6

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

LOG: [llvm][Support] Add and use errnoAsErrorCode (#84423)

LLVM is inconsistent about how it converts `errno` to `std::error_code`.
This can cause problems because values outside of `std::errc` compare
differently if one is system and one is generic on POSIX systems.

This is even more of a problem on Windows where use of the system
category is just wrong, as that is for Windows errors, which have a
completely different mapping than POSIX/generic errors. This patch fixes
one instance of this mistake in `JSONTransport.cpp`.

This patch adds `errnoAsErrorCode()` which makes it so people do not
need to think about this issue in the future. It also cleans up a lot of
usage of `errno` in LLVM and Clang.

Added: 


Modified: 
clang-tools-extra/clangd/JSONTransport.cpp
clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
llvm/include/llvm/Support/Error.h
llvm/lib/ExecutionEngine/Orc/MemoryMapper.cpp

llvm/lib/ExecutionEngine/Orc/TargetProcess/ExecutorSharedMemoryMapperService.cpp
llvm/lib/Object/ArchiveWriter.cpp
llvm/lib/Support/AutoConvert.cpp
llvm/lib/Support/LockFileManager.cpp
llvm/lib/Support/Path.cpp
llvm/lib/Support/RandomNumberGenerator.cpp
llvm/lib/Support/Unix/Memory.inc
llvm/lib/Support/Unix/Path.inc
llvm/lib/Support/Unix/Process.inc
llvm/lib/Support/Windows/Process.inc
llvm/lib/Support/Windows/Program.inc
llvm/lib/Support/raw_ostream.cpp
llvm/lib/Support/raw_socket_stream.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/JSONTransport.cpp 
b/clang-tools-extra/clangd/JSONTransport.cpp
index 346c7dfb66a1db..3c0e198433f360 100644
--- a/clang-tools-extra/clangd/JSONTransport.cpp
+++ b/clang-tools-extra/clangd/JSONTransport.cpp
@@ -107,8 +107,7 @@ class JSONTransport : public Transport {
 return error(std::make_error_code(std::errc::operation_canceled),
  "Got signal, shutting down");
   if (ferror(In))
-return llvm::errorCodeToError(
-std::error_code(errno, std::system_category()));
+return llvm::errorCodeToError(llvm::errnoAsErrorCode());
   if (readRawMessage(JSON)) {
 ThreadCrashReporter ScopedReporter([&JSON]() {
   auto &OS = llvm::errs();

diff  --git a/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp 
b/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
index beca9586988b52..2ffbc1a226958a 100644
--- a/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
+++ b/clang/lib/DirectoryWatcher/linux/DirectoryWatcher-linux.cpp
@@ -333,8 +333,7 @@ llvm::Expected> 
clang::DirectoryWatcher::creat
   const int InotifyFD = inotify_init1(IN_CLOEXEC);
   if (InotifyFD == -1)
 return llvm::make_error(
-std::string("inotify_init1() error: ") + strerror(errno),
-llvm::inconvertibleErrorCode());
+llvm::errnoAsErrorCode(), std::string(": inotify_init1()"));
 
   const int InotifyWD = inotify_add_watch(
   InotifyFD, Path.str().c_str(),
@@ -346,15 +345,13 @@ llvm::Expected> 
clang::DirectoryWatcher::creat
   );
   if (InotifyWD == -1)
 return llvm::make_error(
-std::string("inotify_add_watch() error: ") + strerror(errno),
-llvm::inconvertibleErrorCode());
+llvm::errnoAsErrorCode(), std::string(": inotify_add_watch()"));
 
   auto InotifyPollingStopper = SemaphorePipe::create();
 
   if (!InotifyPollingStopper)
 return llvm::make_error(
-std::string("SemaphorePipe::create() error: ") + strerror(errno),
-llvm::inconvertibleErrorCode());
+llvm::errnoAsErrorCode(), std::string(": SemaphorePipe::create()"));
 
   return std::make_unique(
   Path, Receiver, WaitForInitialSync, InotifyFD, InotifyWD,

diff  --git a/llvm/include/llvm/Support/Error.h 
b/llvm/include/llvm/Support/Error.h
index bb4f38f7ec355e..894b6484336aef 100644
--- a/llvm/include/llvm/Support/Error.h
+++ b/llvm/include/llvm/Support/Error.h
@@ -1180,6 +1180,20 @@ Error errorCodeToError(std::error_code EC);
 /// will trigger a call to abort().
 std::error_code errorToErrorCode(Error Err);
 
+/// Helper to get errno as an std::error_code.
+///
+/// errno should always be represented using the generic category as that's 
what
+/// both libc++ and libstdc++ do. On POSIX systems you can also represent them
+/// using the system category, however this makes them compare 
diff erently for
+/// values outside of those used by `std::errc` if one is generic and the other
+/// is system.
+///
+/// See the libc++ and libstdc++ implementations of `default_error_condition` 
on
+/// the system category for more

[clang] [clang] Add optional pass to remove UBSAN traps using PGO (PR #84214)

2024-03-08 Thread Vitaly Buka via cfe-commits

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-08 Thread Heejin Ahn via cfe-commits


@@ -999,25 +1017,43 @@ bool 
WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
   // Register __wasm_longjmp function, which calls __builtin_wasm_longjmp.
   FunctionType *FTy = FunctionType::get(
   IRB.getVoidTy(), {Int8PtrTy, IRB.getInt32Ty()}, false);
-  WasmLongjmpF = getEmscriptenFunction(FTy, "__wasm_longjmp", &M);
+  if (EnableWasmAltSjLj) {
+WasmLongjmpF = getEmscriptenFunction(FTy, "__wasm_sjlj_longjmp", &M);

aheejin wrote:

Is this the final name? It's unclear what the difference between 
`__wasm_longjmp` and `__wasm_sjlj_longjmp` to people who are not familiar with 
the history... If the goal is to eventually to replace the current library, I'd 
want this to be new `__wasm_longjmp`. But given that we have to maintain both 
at this point, how about `__wasm_longjmp_new` or something? (I'm not too 
opinionated on this specific name, so please feel free to suggest otherwise.. 
but what I'm saying is, mainly, in the final version, I'd like to have only 
`__wasm_setjmp` and `__wasm_longjmp`, with your version. I think `_sjlj_` is a 
redundancy.

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-08 Thread Heejin Ahn via cfe-commits


@@ -1291,19 +1327,29 @@ bool 
WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
   Type *IntPtrTy = getAddrIntType(&M);
   Constant *size = ConstantInt::get(IntPtrTy, 40);
   IRB.SetInsertPoint(SetjmpTableSize);
-  auto *SetjmpTable = IRB.CreateMalloc(IntPtrTy, IRB.getInt32Ty(), size,
-   nullptr, nullptr, "setjmpTable");
-  SetjmpTable->setDebugLoc(FirstDL);
-  // CallInst::CreateMalloc may return a bitcast instruction if the result 
types
-  // mismatch. We need to set the debug loc for the original call too.
-  auto *MallocCall = SetjmpTable->stripPointerCasts();
-  if (auto *MallocCallI = dyn_cast(MallocCall)) {
-MallocCallI->setDebugLoc(FirstDL);
+  Instruction *SetjmpTable;
+  if (EnableWasmAltSjLj) {
+// This alloca'ed pointer is used by the runtime to identify function
+// inovactions. It's just for pointer comparisons. It will never
+// be dereferenced.
+SetjmpTable = IRB.CreateAlloca(IRB.getInt32Ty());
+SetjmpTable->setDebugLoc(FirstDL);
+SetjmpTableInsts.push_back(SetjmpTable);
+  } else {

aheejin wrote:

https://github.com/llvm/llvm-project/blob/578e66ac45dfcc5c739f3525bfb82d71282d925c/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp#L1278-L1293
This can be moved into this `else` part too. Also we don't need to create 
`SetjmpTableSize`, in which case we should do something like 
`IRB.setInsertPoint(Entry.getTerminator()` instead.

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-08 Thread Heejin Ahn via cfe-commits


@@ -1291,19 +1327,29 @@ bool 
WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
   Type *IntPtrTy = getAddrIntType(&M);
   Constant *size = ConstantInt::get(IntPtrTy, 40);
   IRB.SetInsertPoint(SetjmpTableSize);
-  auto *SetjmpTable = IRB.CreateMalloc(IntPtrTy, IRB.getInt32Ty(), size,
-   nullptr, nullptr, "setjmpTable");
-  SetjmpTable->setDebugLoc(FirstDL);
-  // CallInst::CreateMalloc may return a bitcast instruction if the result 
types
-  // mismatch. We need to set the debug loc for the original call too.
-  auto *MallocCall = SetjmpTable->stripPointerCasts();
-  if (auto *MallocCallI = dyn_cast(MallocCall)) {
-MallocCallI->setDebugLoc(FirstDL);
+  Instruction *SetjmpTable;

aheejin wrote:

What we create with this option is not really a 'table' anymore... Can we 
rename it? I don't think we have to share the variable with the old mechanism, 
no? (I think using `SetjmpTable` variable with two different meanings is more 
confusing.)

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-08 Thread Heejin Ahn via cfe-commits


@@ -1291,19 +1327,29 @@ bool 
WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
   Type *IntPtrTy = getAddrIntType(&M);
   Constant *size = ConstantInt::get(IntPtrTy, 40);
   IRB.SetInsertPoint(SetjmpTableSize);
-  auto *SetjmpTable = IRB.CreateMalloc(IntPtrTy, IRB.getInt32Ty(), size,
-   nullptr, nullptr, "setjmpTable");
-  SetjmpTable->setDebugLoc(FirstDL);
-  // CallInst::CreateMalloc may return a bitcast instruction if the result 
types
-  // mismatch. We need to set the debug loc for the original call too.
-  auto *MallocCall = SetjmpTable->stripPointerCasts();
-  if (auto *MallocCallI = dyn_cast(MallocCall)) {
-MallocCallI->setDebugLoc(FirstDL);
+  Instruction *SetjmpTable;
+  if (EnableWasmAltSjLj) {
+// This alloca'ed pointer is used by the runtime to identify function
+// inovactions. It's just for pointer comparisons. It will never
+// be dereferenced.
+SetjmpTable = IRB.CreateAlloca(IRB.getInt32Ty());
+SetjmpTable->setDebugLoc(FirstDL);
+SetjmpTableInsts.push_back(SetjmpTable);

aheejin wrote:

```suggestion
```
`SetjmpTableInsts` (and `SetjmpTableSizeInsts`) is for the SSA updates at the 
end of the transformation, because in the current version `setjmpTable` and 
`setjmpTableTableSize` are assigned every time we call `saveSetjmp`. Now that 
we don't do this I don't think we need to insert it here.

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-08 Thread Heejin Ahn via cfe-commits


@@ -54,6 +54,9 @@ cl::opt
 // setjmp/longjmp handling using wasm EH instrutions
 cl::opt WebAssembly::WasmEnableSjLj(
 "wasm-enable-sjlj", cl::desc("WebAssembly setjmp/longjmp handling"));
+cl::opt WebAssembly::WasmEnableAltSjLj(
+"experimental-wasm-enable-alt-sjlj",
+cl::desc("Use experimental alternate ABI for --wasm-enable-sjlj"));

aheejin wrote:

```suggestion
cl::opt WebAssembly::WasmEnableExperimentalNewSjLj(
"wasm-enable-experimental-new-sjlj",
cl::desc("Use experimental new ABI for -wasm-enable-sjlj"));
```

I've been trying to make all Wasm related option variable names start with 
`Wasm`. Also, if we are to replace the current impl with this, how about just 
'new' than 'alt', which sounds like we are planning to keep both?

If we are to change this, we have to fix other places that includes either of 
`WasmEnableAltSjLj` and `experimental-wasm-enable-alt-sjlj` as well.

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-08 Thread Heejin Ahn via cfe-commits


@@ -1738,10 +1792,16 @@ void 
WebAssemblyLowerEmscriptenEHSjLj::handleLongjmpableCallsForWasmSjLj(
   BasicBlock *ThenBB = BasicBlock::Create(C, "if.then", &F);
   BasicBlock *EndBB = BasicBlock::Create(C, "if.end", &F);
   Value *EnvP = IRB.CreateBitCast(Env, getAddrPtrType(&M), "env.p");
-  Value *SetjmpID = IRB.CreateLoad(getAddrIntType(&M), EnvP, "setjmp.id");
-  Value *Label =
-  IRB.CreateCall(TestSetjmpF, {SetjmpID, SetjmpTable, SetjmpTableSize},
- OperandBundleDef("funclet", CatchPad), "label");
+  Value *Label;
+  if (EnableWasmAltSjLj) {
+Label = IRB.CreateCall(TestSetjmpF, {EnvP, SetjmpTable},
+   OperandBundleDef("funclet", CatchPad), "label");
+  } else {

aheejin wrote:

We can move 
https://github.com/llvm/llvm-project/blob/6c765069112e31ec66cd4387f2a39f70583e626b/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp#L1685-L1688
 into this `else`, given that `SetjmpTableInsts` and `SetjmpTableSizeInsts` are 
empty in this new mode.

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-08 Thread Heejin Ahn via cfe-commits


@@ -386,6 +386,20 @@ void WebAssembly::addClangTargetOptions(const ArgList 
&DriverArgs,
   // Backend needs '-exception-model=wasm' to use Wasm EH instructions
   CC1Args.push_back("-exception-model=wasm");
 }
+
+if (Opt.starts_with("-experimental-wasm-enable-alt-sjlj")) {
+  // '-mllvm -experimental-wasm-enable-alt-sjlj'  should be used with

aheejin wrote:

```suggestion
  // '-mllvm -experimental-wasm-enable-alt-sjlj' should be used with
```

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-08 Thread Heejin Ahn via cfe-commits


@@ -300,6 +315,7 @@ class WebAssemblyLowerEmscriptenEHSjLj final : public 
ModulePass {
   bool EnableEmEH; // Enable Emscripten exception handling
   bool EnableEmSjLj;   // Enable Emscripten setjmp/longjmp handling
   bool EnableWasmSjLj; // Enable Wasm setjmp/longjmp handling
+  bool EnableWasmAltSjLj; // Alt ABI for EnableWasmSjLj

aheejin wrote:

```suggestion
  bool EnableWasmNewSjLj; // New ABI for EnableWasmSjLj
```
Also running clang-format around this line will likely to change the comment 
indentation.

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-08 Thread Heejin Ahn via cfe-commits

https://github.com/aheejin commented:

Nice work! Sorry for the late reply. I thought we needed the table because we 
need to distinguish two different calls from the same function, for example, if 
`foo` calls `setjmp` and also recursively calls `foo` again, so the same 
callsite can have two different `setjmpId` (e.g., 
https://github.com/emscripten-core/emscripten/blob/main/test/core/test_longjmp3.c).
 But this fixes that problem by adding `function_invocation_id`, which is 
simpler and nicer.

I also ran all Emscripten SjLj tests with this implementation (+ your `rt.c`) 
and all of them seemed to pass. 🎉

---

I left some inline comments. 

+ Given that we don't need `setjmpTableSize` anymore and `setjmpTable` doesn't 
change, we don't need the whole block here from line 1463 ~ line 1503 doing SSA 
updates anymore: 
https://github.com/llvm/llvm-project/blob/578e66ac45dfcc5c739f3525bfb82d71282d925c/llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp#L1409-L1449

So you can wrap this part with `(!EnableWasmAltSjLj)`.

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-08 Thread Heejin Ahn via cfe-commits

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


[clang] [C++20][Coroutines] lambda-coroutine with promise_type ctor. (PR #84519)

2024-03-08 Thread Andreas Fertig via cfe-commits

https://github.com/andreasfertig updated 
https://github.com/llvm/llvm-project/pull/84519

>From 3083833f9e87947c7e45c5ed5bd6a983294717c9 Mon Sep 17 00:00:00 2001
From: Andreas Fertig 
Date: Fri, 8 Mar 2024 17:49:15 +0100
Subject: [PATCH] [C++20][Coroutines] lambda-coroutine with promise_type ctor.

This is a follow-up of #84064. It turned out that a coroutine-lambda
with a `promise_type` and a user-defined constructor ignores the `this`
pointer. Per http://eel.is/c++draft/dcl.fct.def.coroutine#4, in such a
case, the first parameter to the constructor is an lvalue of `*this`.
---
 clang/lib/Sema/SemaCoroutine.cpp  | 19 -
 .../SemaCXX/coroutine-promise-ctor-lambda.cpp | 71 +++
 ...tine-promise-ctor-static-callop-lambda.cpp | 47 
 3 files changed, 134 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/SemaCXX/coroutine-promise-ctor-lambda.cpp
 create mode 100644 
clang/test/SemaCXX/cxx23-coroutine-promise-ctor-static-callop-lambda.cpp

diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp
index 301a5ff72a3b2a..fd8eb81ba55fa4 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -596,8 +596,21 @@ VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
 
   // Add implicit object parameter.
   if (auto *MD = dyn_cast(FD)) {
-if (MD->isImplicitObjectMemberFunction() && !isLambdaCallOperator(MD)) {
-  ExprResult ThisExpr = ActOnCXXThis(Loc);
+if (MD->isImplicitObjectMemberFunction()) {
+  ExprResult ThisExpr{};
+
+  if (isLambdaCallOperator(MD) && !MD->isStatic()) {
+Qualifiers ThisQuals = MD->getMethodQualifiers();
+CXXRecordDecl *Record = MD->getParent();
+
+Sema::CXXThisScopeRAII ThisScope(*this, Record, ThisQuals,
+ /*Enabled=*/Record != nullptr);
+
+ThisExpr = ActOnCXXThis(Loc, /*ThisRefersToClosureObject=*/true);
+  } else {
+ThisExpr = ActOnCXXThis(Loc);
+  }
+
   if (ThisExpr.isInvalid())
 return nullptr;
   ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
@@ -1387,7 +1400,7 @@ static bool collectPlacementArgs(Sema &S, FunctionDecl 
&FD, SourceLocation Loc,
 CXXRecordDecl *Record = MD->getParent();
 
 Sema::CXXThisScopeRAII ThisScope(S, Record, ThisQuals,
- Record != nullptr);
+ /*Enabled=*/Record != nullptr);
 
 ThisExpr = S.ActOnCXXThis(Loc, /*ThisRefersToClosureObject=*/true);
   } else {
diff --git a/clang/test/SemaCXX/coroutine-promise-ctor-lambda.cpp 
b/clang/test/SemaCXX/coroutine-promise-ctor-lambda.cpp
new file mode 100644
index 00..92e9a006c3a8d9
--- /dev/null
+++ b/clang/test/SemaCXX/coroutine-promise-ctor-lambda.cpp
@@ -0,0 +1,71 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -I%S/Inputs -std=c++20 %s
+
+// expected-no-diagnostics
+
+#include "std-coroutine.h"
+
+using size_t = decltype(sizeof(0));
+
+struct Generator {
+  struct promise_type {
+int _val{};
+
+Generator get_return_object() noexcept
+{
+  return {};
+}
+
+std::suspend_never initial_suspend() noexcept
+{
+  return {};
+}
+
+std::suspend_always final_suspend() noexcept
+{
+  return {};
+}
+
+void return_void() noexcept {}
+void unhandled_exception() noexcept {}
+
+template
+promise_type(This&,
+ TheRest&&...)
+{
+}
+  };
+};
+
+struct CapturingThisTest
+{
+int x{};
+
+void AsPointer()
+{
+  auto lamb = [=,this]() -> Generator {
+int y = x;
+co_return;
+  };
+
+  static_assert(sizeof(decltype(lamb)) == sizeof(void*));
+}
+
+void AsStarThis()
+{
+  auto lamb = [*this]() -> Generator {
+int y = x;
+co_return;
+  };
+
+  static_assert(sizeof(decltype(lamb)) == sizeof(int));
+}
+};
+
+int main()
+{
+  auto lamb = []() -> Generator {
+co_return;
+  };
+
+  static_assert(sizeof(decltype(lamb)) == 1);
+}
diff --git 
a/clang/test/SemaCXX/cxx23-coroutine-promise-ctor-static-callop-lambda.cpp 
b/clang/test/SemaCXX/cxx23-coroutine-promise-ctor-static-callop-lambda.cpp
new file mode 100644
index 00..0e9e63bce86b87
--- /dev/null
+++ b/clang/test/SemaCXX/cxx23-coroutine-promise-ctor-static-callop-lambda.cpp
@@ -0,0 +1,47 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -I%S/Inputs -std=c++23 %s
+
+// expected-no-diagnostics
+
+#include "std-coroutine.h"
+
+using size_t = decltype(sizeof(0));
+
+struct Generator {
+  struct promise_type {
+int _val{};
+
+Generator get_return_object() noexcept
+{
+  return {};
+}
+
+std::suspend_never initial_suspend() noexcept
+{
+  return {};
+}
+
+std::suspend_always final_suspend() noexcept
+{
+  return {};
+}
+
+void return_void() noexcept {}
+void unhandled_exception() noexcept {}
+
+templa

[clang] [llvm] [RISCV] Support RISC-V Profiles in -march option (PR #76357)

2024-03-08 Thread Wang Pengcheng via cfe-commits


@@ -0,0 +1,189 @@
+//===-- RISCVProfiles.td - RISC-V Profiles -*- tablegen 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+class RISCVProfile features>

wangpc-pp wrote:

Yeah, `-mcpu=generic-profile` may be a better way. I will remove these profile 
features and create another PR for profile CPUs.

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


[clang] [clang] Add optional pass to remove UBSAN traps using PGO (PR #84214)

2024-03-08 Thread Vitaly Buka via cfe-commits

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


[clang] [clang] Add optional pass to remove UBSAN traps using PGO (PR #84214)

2024-03-08 Thread Vitaly Buka via cfe-commits


@@ -744,6 +750,21 @@ static void addSanitizers(const Triple &TargetTriple,
 // LastEP does not need GlobalsAA.
 PB.registerOptimizerLastEPCallback(SanitizersCallback);
   }
+
+  if (ClRemoveTraps) {
+// We can optimize after inliner, and PGO profile matching. The hook below
+// is called from `buildModuleOptimizationPipeline` just after profile use,
+// and inliner is a part of `buildModuleSimplificationPipeline`, which is
+// before `buildModuleOptimizationPipeline`.
+PB.registerOptimizerEarlyEPCallback([&](ModulePassManager &MPM,

vitalybuka wrote:

It's bisected to SimplifyCFG , the one after ScalarOptimizerLateEPCallback.
Most trap blocks preceded by empty blocks with unconditional branch as 
terminator. And they are always cold.
Inserting `SimplifyCFGPass` solves the issue and now I see no regression.


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


[clang] [clang] Add optional pass to remove UBSAN traps using PGO (PR #84214)

2024-03-08 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka updated 
https://github.com/llvm/llvm-project/pull/84214

>From feb5bfa786d1660a7fe0b6c48ec9048cdd315800 Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 6 Mar 2024 10:03:46 -0800
Subject: [PATCH 1/5] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20in?=
 =?UTF-8?q?itial=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4
---
 clang/lib/CodeGen/BackendUtil.cpp   | 17 +
 clang/test/CodeGen/remote-traps.cpp | 15 +++
 2 files changed, 32 insertions(+)
 create mode 100644 clang/test/CodeGen/remote-traps.cpp

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 7310e3817c79a1..d89e53f69c4a51 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -76,6 +76,7 @@
 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
+#include "llvm/Transforms/Instrumentation/RemoveTrapsPass.h"
 #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
@@ -83,6 +84,7 @@
 #include "llvm/Transforms/Scalar/EarlyCSE.h"
 #include "llvm/Transforms/Scalar/GVN.h"
 #include "llvm/Transforms/Scalar/JumpThreading.h"
+#include "llvm/Transforms/Scalar/SimplifyCFG.h"
 #include "llvm/Transforms/Utils/Debugify.h"
 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
 #include "llvm/Transforms/Utils/ModuleUtils.h"
@@ -98,6 +100,10 @@ using namespace llvm;
 namespace llvm {
 extern cl::opt PrintPipelinePasses;
 
+cl::opt ClRemoveTraps("clang-remove-traps", cl::Optional,
+cl::desc("Insert remove-traps pass."),
+cl::init(false));
+
 // Experiment to move sanitizers earlier.
 static cl::opt ClSanitizeOnOptimizerEarlyEP(
 "sanitizer-early-opt-ep", cl::Optional,
@@ -744,6 +750,17 @@ static void addSanitizers(const Triple &TargetTriple,
 // LastEP does not need GlobalsAA.
 PB.registerOptimizerLastEPCallback(SanitizersCallback);
   }
+
+  if (ClRemoveTraps) {
+PB.registerOptimizerEarlyEPCallback([&](ModulePassManager &MPM,
+OptimizationLevel Level) {
+  FunctionPassManager FPM;
+  FPM.addPass(RemoveTrapsPass());
+  FPM.addPass(
+  
SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
+  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
+});
+  }
 }
 
 void EmitAssemblyHelper::RunOptimizationPipeline(
diff --git a/clang/test/CodeGen/remote-traps.cpp 
b/clang/test/CodeGen/remote-traps.cpp
new file mode 100644
index 00..7d4eb76a7d81e9
--- /dev/null
+++ b/clang/test/CodeGen/remote-traps.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -O1 -emit-llvm -fsanitize=signed-integer-overflow 
-fsanitize-trap=signed-integer-overflow %s -o - | FileCheck %s 
+// RUN: %clang_cc1 -O1 -emit-llvm -fsanitize=signed-integer-overflow 
-fsanitize-trap=signed-integer-overflow -mllvm -clang-remove-traps -mllvm 
-remove-traps-random-rate=1 %s -o - | FileCheck %s --implicit-check-not="call 
void @llvm.ubsantrap" --check-prefixes=REMOVE
+
+int f(int x) {
+  return x + 123;
+}
+
+// CHECK-LABEL: define dso_local noundef i32 @_Z1fi(
+// CHECK: call { i32, i1 } @llvm.sadd.with.overflow.i32(
+// CHECK: trap:
+// CHECK-NEXT: call void @llvm.ubsantrap(i8 0)
+// CHECK-NEXT: unreachable, !nosanitize !2 
+
+// REMOVE-LABEL: define dso_local noundef i32 @_Z1fi(
+// REMOVE: call { i32, i1 } @llvm.sadd.with.overflow.i32(

>From 0b2b44e04b8c900c29f52e340ebdfc6824607773 Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 6 Mar 2024 10:08:47 -0800
Subject: [PATCH 2/5] comment

Created using spr 1.3.4
---
 clang/lib/CodeGen/BackendUtil.cpp | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index d89e53f69c4a51..fa49a364cf5600 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -752,6 +752,9 @@ static void addSanitizers(const Triple &TargetTriple,
   }
 
   if (ClRemoveTraps) {
+// We can optimize after inliner, and PGO profile matching, which are part
+// of `buildModuleSimplificationPipeline`. The hook below is called after
+// that, from `buildModuleOptimizationPipeline`.
 PB.registerOptimizerEarlyEPCallback([&](ModulePassManager &MPM,
 OptimizationLevel Level) {
   FunctionPassManager FPM;

>From 000854eb9d18cd9cfd6eaf7d29e5954fb18d454c Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 6 Mar 2024 10:22:16 -0800
Subject: [PATCH 3/5] comment

Created using spr 1.3.4
---
 clang/lib/CodeGen/BackendUtil.cpp | 7 ---
 1 file changed, 4 insertions(+), 3 deletions(-)

[clang] [clang] Add optional pass to remove UBSAN traps using PGO (PR #84214)

2024-03-08 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka updated 
https://github.com/llvm/llvm-project/pull/84214

>From feb5bfa786d1660a7fe0b6c48ec9048cdd315800 Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 6 Mar 2024 10:03:46 -0800
Subject: [PATCH 1/4] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20in?=
 =?UTF-8?q?itial=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4
---
 clang/lib/CodeGen/BackendUtil.cpp   | 17 +
 clang/test/CodeGen/remote-traps.cpp | 15 +++
 2 files changed, 32 insertions(+)
 create mode 100644 clang/test/CodeGen/remote-traps.cpp

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 7310e3817c79a1..d89e53f69c4a51 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -76,6 +76,7 @@
 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
+#include "llvm/Transforms/Instrumentation/RemoveTrapsPass.h"
 #include "llvm/Transforms/Instrumentation/SanitizerBinaryMetadata.h"
 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
@@ -83,6 +84,7 @@
 #include "llvm/Transforms/Scalar/EarlyCSE.h"
 #include "llvm/Transforms/Scalar/GVN.h"
 #include "llvm/Transforms/Scalar/JumpThreading.h"
+#include "llvm/Transforms/Scalar/SimplifyCFG.h"
 #include "llvm/Transforms/Utils/Debugify.h"
 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
 #include "llvm/Transforms/Utils/ModuleUtils.h"
@@ -98,6 +100,10 @@ using namespace llvm;
 namespace llvm {
 extern cl::opt PrintPipelinePasses;
 
+cl::opt ClRemoveTraps("clang-remove-traps", cl::Optional,
+cl::desc("Insert remove-traps pass."),
+cl::init(false));
+
 // Experiment to move sanitizers earlier.
 static cl::opt ClSanitizeOnOptimizerEarlyEP(
 "sanitizer-early-opt-ep", cl::Optional,
@@ -744,6 +750,17 @@ static void addSanitizers(const Triple &TargetTriple,
 // LastEP does not need GlobalsAA.
 PB.registerOptimizerLastEPCallback(SanitizersCallback);
   }
+
+  if (ClRemoveTraps) {
+PB.registerOptimizerEarlyEPCallback([&](ModulePassManager &MPM,
+OptimizationLevel Level) {
+  FunctionPassManager FPM;
+  FPM.addPass(RemoveTrapsPass());
+  FPM.addPass(
+  
SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
+  MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
+});
+  }
 }
 
 void EmitAssemblyHelper::RunOptimizationPipeline(
diff --git a/clang/test/CodeGen/remote-traps.cpp 
b/clang/test/CodeGen/remote-traps.cpp
new file mode 100644
index 00..7d4eb76a7d81e9
--- /dev/null
+++ b/clang/test/CodeGen/remote-traps.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -O1 -emit-llvm -fsanitize=signed-integer-overflow 
-fsanitize-trap=signed-integer-overflow %s -o - | FileCheck %s 
+// RUN: %clang_cc1 -O1 -emit-llvm -fsanitize=signed-integer-overflow 
-fsanitize-trap=signed-integer-overflow -mllvm -clang-remove-traps -mllvm 
-remove-traps-random-rate=1 %s -o - | FileCheck %s --implicit-check-not="call 
void @llvm.ubsantrap" --check-prefixes=REMOVE
+
+int f(int x) {
+  return x + 123;
+}
+
+// CHECK-LABEL: define dso_local noundef i32 @_Z1fi(
+// CHECK: call { i32, i1 } @llvm.sadd.with.overflow.i32(
+// CHECK: trap:
+// CHECK-NEXT: call void @llvm.ubsantrap(i8 0)
+// CHECK-NEXT: unreachable, !nosanitize !2 
+
+// REMOVE-LABEL: define dso_local noundef i32 @_Z1fi(
+// REMOVE: call { i32, i1 } @llvm.sadd.with.overflow.i32(

>From 0b2b44e04b8c900c29f52e340ebdfc6824607773 Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 6 Mar 2024 10:08:47 -0800
Subject: [PATCH 2/4] comment

Created using spr 1.3.4
---
 clang/lib/CodeGen/BackendUtil.cpp | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index d89e53f69c4a51..fa49a364cf5600 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -752,6 +752,9 @@ static void addSanitizers(const Triple &TargetTriple,
   }
 
   if (ClRemoveTraps) {
+// We can optimize after inliner, and PGO profile matching, which are part
+// of `buildModuleSimplificationPipeline`. The hook below is called after
+// that, from `buildModuleOptimizationPipeline`.
 PB.registerOptimizerEarlyEPCallback([&](ModulePassManager &MPM,
 OptimizationLevel Level) {
   FunctionPassManager FPM;

>From 000854eb9d18cd9cfd6eaf7d29e5954fb18d454c Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 6 Mar 2024 10:22:16 -0800
Subject: [PATCH 3/4] comment

Created using spr 1.3.4
---
 clang/lib/CodeGen/BackendUtil.cpp | 7 ---
 1 file changed, 4 insertions(+), 3 deletions(-)

[clang] [X86] Finally handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)

2024-03-08 Thread Freddy Ye via cfe-commits

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


[clang] fc0fc76 - [X86] Finally handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (#84136)

2024-03-08 Thread via cfe-commits

Author: Freddy Ye
Date: 2024-03-09T13:49:15+08:00
New Revision: fc0fc768cc2122c81fd37aa59d9f31fc0d5694d8

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

LOG: [X86] Finally handle target of __builtin_ia32_cmp[p|s][s|d] from avx into 
sse/sse2/avx (#84136)

This patch relands #67410 and fixes the cmpfail below:
#include 
__attribute__((target("avx"))) void test(__m128 a, __m128 b) {
  _mm_cmp_ps(a, b, 14);
}

According to Intel SDM, SSE/SSE2 instructions cmp[p|s][s|d] are
supported when imm8 is in range of [0, 7]

Added: 
clang/test/CodeGen/X86/attribute-cmpsd-no-error.c
clang/test/CodeGen/X86/cmp-avx-builtins-error.c

Modified: 
clang/include/clang/Basic/BuiltinsX86.def
clang/lib/CodeGen/CodeGenFunction.cpp
clang/lib/Headers/avxintrin.h
clang/lib/Headers/emmintrin.h
clang/lib/Headers/xmmintrin.h
clang/test/CodeGen/X86/avx-builtins.c
clang/test/CodeGen/X86/sse-builtins.c
clang/test/CodeGen/X86/sse2-builtins.c
clang/test/CodeGen/target-features-error-2.c

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsX86.def 
b/clang/include/clang/Basic/BuiltinsX86.def
index 207cde0414b54e..eafcc219c10966 100644
--- a/clang/include/clang/Basic/BuiltinsX86.def
+++ b/clang/include/clang/Basic/BuiltinsX86.def
@@ -226,6 +226,8 @@ TARGET_BUILTIN(__builtin_ia32_minps, "V4fV4fV4f", 
"ncV:128:", "sse")
 TARGET_BUILTIN(__builtin_ia32_maxps, "V4fV4fV4f", "ncV:128:", "sse")
 TARGET_BUILTIN(__builtin_ia32_minss, "V4fV4fV4f", "ncV:128:", "sse")
 TARGET_BUILTIN(__builtin_ia32_maxss, "V4fV4fV4f", "ncV:128:", "sse")
+TARGET_BUILTIN(__builtin_ia32_cmpps, "V4fV4fV4fIc", "ncV:128:", "sse")
+TARGET_BUILTIN(__builtin_ia32_cmpss, "V4fV4fV4fIc", "ncV:128:", "sse")
 
 TARGET_BUILTIN(__builtin_ia32_cmpeqpd, "V2dV2dV2d", "ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_cmpltpd, "V2dV2dV2d", "ncV:128:", "sse2")
@@ -243,6 +245,8 @@ TARGET_BUILTIN(__builtin_ia32_cmpneqsd, "V2dV2dV2d", 
"ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_cmpnltsd, "V2dV2dV2d", "ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_cmpnlesd, "V2dV2dV2d", "ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_cmpordsd, "V2dV2dV2d", "ncV:128:", "sse2")
+TARGET_BUILTIN(__builtin_ia32_cmpsd, "V2dV2dV2dIc", "ncV:128:", "sse2")
+TARGET_BUILTIN(__builtin_ia32_cmppd, "V2dV2dV2dIc", "ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_minpd, "V2dV2dV2d", "ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_maxpd, "V2dV2dV2d", "ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_minsd, "V2dV2dV2d", "ncV:128:", "sse2")
@@ -462,12 +466,8 @@ TARGET_BUILTIN(__builtin_ia32_blendvps256, "V8fV8fV8fV8f", 
"ncV:256:", "avx")
 TARGET_BUILTIN(__builtin_ia32_shufpd256, "V4dV4dV4dIi", "ncV:256:", "avx")
 TARGET_BUILTIN(__builtin_ia32_shufps256, "V8fV8fV8fIi", "ncV:256:", "avx")
 TARGET_BUILTIN(__builtin_ia32_dpps256, "V8fV8fV8fIc", "ncV:256:", "avx")
-TARGET_BUILTIN(__builtin_ia32_cmppd, "V2dV2dV2dIc", "ncV:128:", "avx")
 TARGET_BUILTIN(__builtin_ia32_cmppd256, "V4dV4dV4dIc", "ncV:256:", "avx")
-TARGET_BUILTIN(__builtin_ia32_cmpps, "V4fV4fV4fIc", "ncV:128:", "avx")
 TARGET_BUILTIN(__builtin_ia32_cmpps256, "V8fV8fV8fIc", "ncV:256:", "avx")
-TARGET_BUILTIN(__builtin_ia32_cmpsd, "V2dV2dV2dIc", "ncV:128:", "avx")
-TARGET_BUILTIN(__builtin_ia32_cmpss, "V4fV4fV4fIc", "ncV:128:", "avx")
 TARGET_BUILTIN(__builtin_ia32_vextractf128_pd256, "V2dV4dIi", "ncV:256:", 
"avx")
 TARGET_BUILTIN(__builtin_ia32_vextractf128_ps256, "V4fV8fIi", "ncV:256:", 
"avx")
 TARGET_BUILTIN(__builtin_ia32_vextractf128_si256, "V4iV8iIi", "ncV:256:", 
"avx")

diff  --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index b87fc86f4e635f..4a3ff49b0007a3 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -31,6 +31,7 @@
 #include "clang/AST/StmtObjC.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/TargetBuiltins.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/CodeGen/CGFunctionInfo.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
@@ -2613,6 +2614,24 @@ void CGBuilderInserter::InsertHelper(
 // called function.
 void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
   const FunctionDecl *TargetDecl) {
+  // SemaChecking cannot handle below x86 builtins because they have 
diff erent
+  // parameter ranges with 
diff erent TargetAttribute of caller.
+  if (CGM.getContext().getTargetInfo().getTriple().isX86()) {
+unsigned BuiltinID = TargetDecl->getBuiltinID();
+if (BuiltinID == X86::BI__builtin_ia32_cmpps ||
+BuiltinID == X86::BI__builtin_ia32_cmpss ||
+BuiltinID == X86::BI__builtin_ia32_cmppd ||
+BuiltinID == X86::BI__builtin_ia32_cmpsd) {
+

[clang] [X86] Finally handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)

2024-03-08 Thread Freddy Ye via cfe-commits

FreddyLeaf wrote:

> Thanks for the heads-up @RKSimon I've made suggestions for consistency with 
> existing practice in emmintrin.h which I've adopted in the latest revision to 
> #83316.
> 
> I'm unsure how replacing a function declaration with an \fn directive will 
> play with our documentation tooling. But we can figure that out later.

I've committed your suggestions. FYI \fn usage was referring 
https://github.com/llvm/llvm-project/blob/c58c8278f98c189d149d5f062b8d4f56efcada90/clang/lib/Headers/avxvnniintrin.h#L32


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


[clang] [X86] Finally handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)

2024-03-08 Thread Freddy Ye via cfe-commits


@@ -4745,6 +4745,77 @@ static __inline__ __m128d __DEFAULT_FN_ATTRS 
_mm_castsi128_pd(__m128i __a) {
   return (__m128d)__a;
 }
 
+/// Compares each of the corresponding double-precision values of two
+///128-bit vectors of [2 x double], using the operation specified by the
+///immediate integer operand.
+///
+///Returns a [2 x double] vector consisting of two doubles corresponding to
+///the two comparison results: zero if the comparison is false, and all 1's
+///if the comparison is true.

FreddyLeaf wrote:

71641346ebadf8d21a109813fcf66f78e0932955

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


[clang] [X86] Finally handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)

2024-03-08 Thread Freddy Ye via cfe-commits


@@ -4745,6 +4745,77 @@ static __inline__ __m128d __DEFAULT_FN_ATTRS 
_mm_castsi128_pd(__m128i __a) {
   return (__m128d)__a;
 }
 
+/// Compares each of the corresponding double-precision values of two
+///128-bit vectors of [2 x double], using the operation specified by the
+///immediate integer operand.
+///
+///Returns a [2 x double] vector consisting of two doubles corresponding to
+///the two comparison results: zero if the comparison is false, and all 1's
+///if the comparison is true.
+///
+/// \headerfile 
+///
+/// \code
+/// __m128d _mm_cmp_pd(__m128d a, __m128d b, const int c);
+/// \endcode
+///
+/// This intrinsic corresponds to the  (V)CMPPD  instruction.
+///
+/// \param a
+///A 128-bit vector of [2 x double].
+/// \param b
+///A 128-bit vector of [2 x double].
+/// \param c
+///An immediate integer operand, with bits [4:0] specifying which 
comparison
+///operation to use: \n
+///0x00: Equal (ordered, non-signaling) \n
+///0x01: Less-than (ordered, signaling) \n
+///0x02: Less-than-or-equal (ordered, signaling) \n
+///0x03: Unordered (non-signaling) \n
+///0x04: Not-equal (unordered, non-signaling) \n
+///0x05: Not-less-than (unordered, signaling) \n
+///0x06: Not-less-than-or-equal (unordered, signaling) \n
+///0x07: Ordered (non-signaling) \n
+/// \returns A 128-bit vector of [2 x double] containing the comparison 
results.
+#define _mm_cmp_pd(a, b, c)
\
+  ((__m128d)__builtin_ia32_cmppd((__v2df)(__m128d)(a), (__v2df)(__m128d)(b),   
\
+ (c)))
+
+/// Compares each of the corresponding scalar double-precision values of
+///two 128-bit vectors of [2 x double], using the operation specified by 
the
+///immediate integer operand.
+///
+///If the result is true, all 64 bits of the destination vector are set;
+///otherwise they are cleared.

FreddyLeaf wrote:

71641346ebadf8d21a109813fcf66f78e0932955

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


[clang] [X86] Finally handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)

2024-03-08 Thread Freddy Ye via cfe-commits


@@ -2940,6 +2940,84 @@ _mm_movemask_ps(__m128 __a)
   return __builtin_ia32_movmskps((__v4sf)__a);
 }
 
+/* Compare */
+#define _CMP_EQ_OQ0x00 /* Equal (ordered, non-signaling)  */
+#define _CMP_LT_OS0x01 /* Less-than (ordered, signaling)  */
+#define _CMP_LE_OS0x02 /* Less-than-or-equal (ordered, signaling)  */
+#define _CMP_UNORD_Q  0x03 /* Unordered (non-signaling)  */
+#define _CMP_NEQ_UQ   0x04 /* Not-equal (unordered, non-signaling)  */
+#define _CMP_NLT_US   0x05 /* Not-less-than (unordered, signaling)  */
+#define _CMP_NLE_US   0x06 /* Not-less-than-or-equal (unordered, signaling)  */
+#define _CMP_ORD_Q0x07 /* Ordered (non-signaling)   */
+
+/// Compares each of the corresponding values of two 128-bit vectors of
+///[4 x float], using the operation specified by the immediate integer
+///operand.
+///
+///Returns a [4 x float] vector consisting of four floats corresponding to
+///the four comparison results: zero if the comparison is false, and all 
1's
+///if the comparison is true.

FreddyLeaf wrote:

71641346ebadf8d21a109813fcf66f78e0932955

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


[clang] [X86] Finally handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)

2024-03-08 Thread Freddy Ye via cfe-commits


@@ -2940,6 +2940,84 @@ _mm_movemask_ps(__m128 __a)
   return __builtin_ia32_movmskps((__v4sf)__a);
 }
 
+/* Compare */
+#define _CMP_EQ_OQ0x00 /* Equal (ordered, non-signaling)  */
+#define _CMP_LT_OS0x01 /* Less-than (ordered, signaling)  */
+#define _CMP_LE_OS0x02 /* Less-than-or-equal (ordered, signaling)  */
+#define _CMP_UNORD_Q  0x03 /* Unordered (non-signaling)  */
+#define _CMP_NEQ_UQ   0x04 /* Not-equal (unordered, non-signaling)  */
+#define _CMP_NLT_US   0x05 /* Not-less-than (unordered, signaling)  */
+#define _CMP_NLE_US   0x06 /* Not-less-than-or-equal (unordered, signaling)  */
+#define _CMP_ORD_Q0x07 /* Ordered (non-signaling)   */
+
+/// Compares each of the corresponding values of two 128-bit vectors of
+///[4 x float], using the operation specified by the immediate integer
+///operand.
+///
+///Returns a [4 x float] vector consisting of four floats corresponding to
+///the four comparison results: zero if the comparison is false, and all 
1's
+///if the comparison is true.
+///
+/// \headerfile 
+///
+/// \code
+/// __m128 _mm_cmp_ps(__m128 a, __m128 b, const int c);
+/// \endcode
+///
+/// This intrinsic corresponds to the  (V)CMPPS  instruction.
+///
+/// \param a
+///A 128-bit vector of [4 x float].
+/// \param b
+///A 128-bit vector of [4 x float].
+/// \param c
+///An immediate integer operand, with bits [4:0] specifying which 
comparison
+///operation to use: \n
+///0x00: Equal (ordered, non-signaling) \n
+///0x01: Less-than (ordered, signaling) \n
+///0x02: Less-than-or-equal (ordered, signaling) \n
+///0x03: Unordered (non-signaling) \n
+///0x04: Not-equal (unordered, non-signaling) \n
+///0x05: Not-less-than (unordered, signaling) \n
+///0x06: Not-less-than-or-equal (unordered, signaling) \n
+///0x07: Ordered (non-signaling) \n
+/// \returns A 128-bit vector of [4 x float] containing the comparison results.
+#define _mm_cmp_ps(a, b, c)
\
+  ((__m128)__builtin_ia32_cmpps((__v4sf)(__m128)(a), (__v4sf)(__m128)(b), (c)))
+
+/// Compares each of the corresponding scalar values of two 128-bit
+///vectors of [4 x float], using the operation specified by the immediate
+///integer operand.
+///
+///If the result is true, all 32 bits of the destination vector are set;
+///otherwise they are cleared.

FreddyLeaf wrote:

71641346ebadf8d21a109813fcf66f78e0932955

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


[clang] [X86] Finally handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)

2024-03-08 Thread Freddy Ye via cfe-commits

https://github.com/FreddyLeaf updated 
https://github.com/llvm/llvm-project/pull/84136

>From 2ba698b222fa1dc963d21850d5931562aa65533d Mon Sep 17 00:00:00 2001
From: Freddy Ye 
Date: Tue, 26 Sep 2023 16:44:01 +0800
Subject: [PATCH 1/6] [X86] Change target of __builtin_ia32_cmp[p|s][s|d] from
 avx into sse/sse2

---
 clang/include/clang/Basic/BuiltinsX86.def |   8 +-
 clang/lib/Headers/avxintrin.h | 247 --
 clang/lib/Headers/emmintrin.h | 121 +
 clang/lib/Headers/xmmintrin.h | 128 +
 clang/test/CodeGen/X86/avx-builtins.c |  96 ---
 .../test/CodeGen/X86/cmp-avx-builtins-error.c |  22 ++
 clang/test/CodeGen/X86/sse-builtins.c |  54 
 clang/test/CodeGen/X86/sse2-builtins.c|  54 
 clang/test/CodeGen/target-features-error-2.c  |   4 +-
 9 files changed, 385 insertions(+), 349 deletions(-)
 create mode 100644 clang/test/CodeGen/X86/cmp-avx-builtins-error.c

diff --git a/clang/include/clang/Basic/BuiltinsX86.def 
b/clang/include/clang/Basic/BuiltinsX86.def
index 207cde0414b54e..eafcc219c10966 100644
--- a/clang/include/clang/Basic/BuiltinsX86.def
+++ b/clang/include/clang/Basic/BuiltinsX86.def
@@ -226,6 +226,8 @@ TARGET_BUILTIN(__builtin_ia32_minps, "V4fV4fV4f", 
"ncV:128:", "sse")
 TARGET_BUILTIN(__builtin_ia32_maxps, "V4fV4fV4f", "ncV:128:", "sse")
 TARGET_BUILTIN(__builtin_ia32_minss, "V4fV4fV4f", "ncV:128:", "sse")
 TARGET_BUILTIN(__builtin_ia32_maxss, "V4fV4fV4f", "ncV:128:", "sse")
+TARGET_BUILTIN(__builtin_ia32_cmpps, "V4fV4fV4fIc", "ncV:128:", "sse")
+TARGET_BUILTIN(__builtin_ia32_cmpss, "V4fV4fV4fIc", "ncV:128:", "sse")
 
 TARGET_BUILTIN(__builtin_ia32_cmpeqpd, "V2dV2dV2d", "ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_cmpltpd, "V2dV2dV2d", "ncV:128:", "sse2")
@@ -243,6 +245,8 @@ TARGET_BUILTIN(__builtin_ia32_cmpneqsd, "V2dV2dV2d", 
"ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_cmpnltsd, "V2dV2dV2d", "ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_cmpnlesd, "V2dV2dV2d", "ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_cmpordsd, "V2dV2dV2d", "ncV:128:", "sse2")
+TARGET_BUILTIN(__builtin_ia32_cmpsd, "V2dV2dV2dIc", "ncV:128:", "sse2")
+TARGET_BUILTIN(__builtin_ia32_cmppd, "V2dV2dV2dIc", "ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_minpd, "V2dV2dV2d", "ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_maxpd, "V2dV2dV2d", "ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_minsd, "V2dV2dV2d", "ncV:128:", "sse2")
@@ -462,12 +466,8 @@ TARGET_BUILTIN(__builtin_ia32_blendvps256, "V8fV8fV8fV8f", 
"ncV:256:", "avx")
 TARGET_BUILTIN(__builtin_ia32_shufpd256, "V4dV4dV4dIi", "ncV:256:", "avx")
 TARGET_BUILTIN(__builtin_ia32_shufps256, "V8fV8fV8fIi", "ncV:256:", "avx")
 TARGET_BUILTIN(__builtin_ia32_dpps256, "V8fV8fV8fIc", "ncV:256:", "avx")
-TARGET_BUILTIN(__builtin_ia32_cmppd, "V2dV2dV2dIc", "ncV:128:", "avx")
 TARGET_BUILTIN(__builtin_ia32_cmppd256, "V4dV4dV4dIc", "ncV:256:", "avx")
-TARGET_BUILTIN(__builtin_ia32_cmpps, "V4fV4fV4fIc", "ncV:128:", "avx")
 TARGET_BUILTIN(__builtin_ia32_cmpps256, "V8fV8fV8fIc", "ncV:256:", "avx")
-TARGET_BUILTIN(__builtin_ia32_cmpsd, "V2dV2dV2dIc", "ncV:128:", "avx")
-TARGET_BUILTIN(__builtin_ia32_cmpss, "V4fV4fV4fIc", "ncV:128:", "avx")
 TARGET_BUILTIN(__builtin_ia32_vextractf128_pd256, "V2dV4dIi", "ncV:256:", 
"avx")
 TARGET_BUILTIN(__builtin_ia32_vextractf128_ps256, "V4fV8fIi", "ncV:256:", 
"avx")
 TARGET_BUILTIN(__builtin_ia32_vextractf128_si256, "V4iV8iIi", "ncV:256:", 
"avx")
diff --git a/clang/lib/Headers/avxintrin.h b/clang/lib/Headers/avxintrin.h
index f116d8bc3a94c7..d6192518ea24ba 100644
--- a/clang/lib/Headers/avxintrin.h
+++ b/clang/lib/Headers/avxintrin.h
@@ -1573,15 +1573,6 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c)
   ((__m256d)__builtin_ia32_shufpd256((__v4df)(__m256d)(a), \
  (__v4df)(__m256d)(b), (int)(mask)))
 
-/* Compare */
-#define _CMP_EQ_OQ0x00 /* Equal (ordered, non-signaling)  */
-#define _CMP_LT_OS0x01 /* Less-than (ordered, signaling)  */
-#define _CMP_LE_OS0x02 /* Less-than-or-equal (ordered, signaling)  */
-#define _CMP_UNORD_Q  0x03 /* Unordered (non-signaling)  */
-#define _CMP_NEQ_UQ   0x04 /* Not-equal (unordered, non-signaling)  */
-#define _CMP_NLT_US   0x05 /* Not-less-than (unordered, signaling)  */
-#define _CMP_NLE_US   0x06 /* Not-less-than-or-equal (unordered, signaling)  */
-#define _CMP_ORD_Q0x07 /* Ordered (non-signaling)   */
 #define _CMP_EQ_UQ0x08 /* Equal (unordered, non-signaling)  */
 #define _CMP_NGE_US   0x09 /* Not-greater-than-or-equal (unordered, signaling) 
 */
 #define _CMP_NGT_US   0x0a /* Not-greater-than (unordered, signaling)  */
@@ -1607,126 +1598,6 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c)
 #define _CMP_GT_OQ0x1e /* Greater-than (ordered, non-signaling)  */
 #define _CMP_TRUE_US  0x1f /* True (unordered, signaling)  */
 
-/// Compares each of the corresponding double-precision values of two
-///

[clang-tools-extra] [clang-tidy] Add bugprone-suspicious-stringview-data-usage check (PR #83716)

2024-03-08 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL updated 
https://github.com/llvm/llvm-project/pull/83716

>From d56e3336a8b4b3434c5f2d69b4ec50cafc01cd8f Mon Sep 17 00:00:00 2001
From: Piotr Zegar 
Date: Tue, 20 Feb 2024 18:15:56 +
Subject: [PATCH 1/4] [clang-tidy] Add
 bugprone-suspicious-stringview-data-usage check

This check identifies suspicious usages of std::string_view::data()
that could lead to reading out-of-bounds data due to inadequate or
incorrect string null termination.
---
 .../bugprone/BugproneTidyModule.cpp   |   3 +
 .../clang-tidy/bugprone/CMakeLists.txt|   1 +
 .../SuspiciousStringviewDataUsageCheck.cpp| 100 ++
 .../SuspiciousStringviewDataUsageCheck.h  |  38 +++
 clang-tools-extra/docs/ReleaseNotes.rst   |   7 ++
 .../suspicious-stringview-data-usage.rst  |  58 ++
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../clang-tidy/checkers/Inputs/Headers/string |   7 ++
 .../suspicious-stringview-data-usage.cpp  |  48 +
 9 files changed, 263 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/SuspiciousStringviewDataUsageCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/SuspiciousStringviewDataUsageCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/suspicious-stringview-data-usage.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/suspicious-stringview-data-usage.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index e518a64abc52eb..2931325d8b5798 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -73,6 +73,7 @@
 #include "SuspiciousReallocUsageCheck.h"
 #include "SuspiciousSemicolonCheck.h"
 #include "SuspiciousStringCompareCheck.h"
+#include "SuspiciousStringviewDataUsageCheck.h"
 #include "SwappedArgumentsCheck.h"
 #include "SwitchMissingDefaultCaseCheck.h"
 #include "TerminatingContinueCheck.h"
@@ -218,6 +219,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-suspicious-semicolon");
 CheckFactories.registerCheck(
 "bugprone-suspicious-string-compare");
+CheckFactories.registerCheck(
+"bugprone-suspicious-stringview-data-usage");
 CheckFactories.registerCheck(
 "bugprone-swapped-arguments");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 638fba03a43587..081ba67efe1538 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -26,6 +26,7 @@ add_clang_library(clangTidyBugproneModule
   ImplicitWideningOfMultiplicationResultCheck.cpp
   InaccurateEraseCheck.cpp
   IncorrectEnableIfCheck.cpp
+  SuspiciousStringviewDataUsageCheck.cpp
   SwitchMissingDefaultCaseCheck.cpp
   IncDecInConditionsCheck.cpp
   IncorrectRoundingsCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/SuspiciousStringviewDataUsageCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/SuspiciousStringviewDataUsageCheck.cpp
new file mode 100644
index 00..ffb31840c4c886
--- /dev/null
+++ 
b/clang-tools-extra/clang-tidy/bugprone/SuspiciousStringviewDataUsageCheck.cpp
@@ -0,0 +1,100 @@
+//===--- SuspiciousStringviewDataUsageCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "SuspiciousStringviewDataUsageCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+SuspiciousStringviewDataUsageCheck::SuspiciousStringviewDataUsageCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  StringViewTypes(utils::options::parseStringList(Options.get(
+  "StringViewTypes", "::std::basic_string_view;::llvm::StringRef"))),
+  AllowedCallees(
+  utils::options::parseStringList(Options.get("AllowedCallees", ""))) 
{}
+
+void SuspiciousStringviewDataUsageCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "StringViewTypes",
+utils::options::serializeStringList(StringViewTypes));
+  Options.store(Opts, "AllowedCallees",
+utils::options::serializeStringList(AllowedCallees));
+}
+
+bool SuspiciousStringviewDataUsageCheck::isLanguageVersionSupported(
+const LangOptions &LangOpts) const {
+  return LangOpts.CPlusPlus;
+}
+
+std::optional
+SuspiciousSt

[clang] [clang-format][NFC] Eliminate the IsCpp parameter in all functions (PR #84599)

2024-03-08 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/84599

>From 43238d58ff490073c13ff621faddceb89b05b22e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 8 Mar 2024 19:47:54 -0800
Subject: [PATCH] [clang-format][NFC] Eliminate the IsCpp parameter in all
 functions

---
 clang/include/clang/Format/Format.h  |  3 ++
 clang/lib/Format/ContinuationIndenter.cpp| 12 +++--
 clang/lib/Format/Format.cpp  |  2 +
 clang/lib/Format/FormatToken.cpp |  6 +--
 clang/lib/Format/FormatToken.h   |  6 +--
 clang/lib/Format/FormatTokenLexer.cpp|  5 +-
 clang/lib/Format/QualifierAlignmentFixer.cpp | 29 ++--
 clang/lib/Format/QualifierAlignmentFixer.h   |  5 +-
 clang/lib/Format/TokenAnnotator.cpp  | 48 ++--
 clang/lib/Format/TokenAnnotator.h|  6 +--
 clang/lib/Format/UnwrappedLineParser.cpp | 22 +
 clang/lib/Format/UnwrappedLineParser.h   |  1 -
 12 files changed, 74 insertions(+), 71 deletions(-)

diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 590297fd89a398..a72c1b171c3e18 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5228,6 +5228,9 @@ extern const char *DefaultFormatStyle;
 /// Different builds can modify the value to the preferred styles.
 extern const char *DefaultFallbackStyle;
 
+/// Whether the language is C/C++/Objective-C/Objective-C++.
+extern bool IsCpp;
+
 /// Construct a FormatStyle based on ``StyleName``.
 ///
 /// ``StyleName`` can take several forms:
diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index df44e6994c4784..506e21725ba9f7 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -241,7 +241,9 @@ ContinuationIndenter::ContinuationIndenter(const 
FormatStyle &Style,
 : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
   Whitespaces(Whitespaces), Encoding(Encoding),
   BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
-  CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
+  CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {
+  IsCpp = Style.isCpp();
+}
 
 LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
 unsigned FirstStartColumn,
@@ -406,7 +408,7 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   }
   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
(Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
-State.Line->First->isNot(TT_AttributeSquare) && Style.isCpp() &&
+State.Line->First->isNot(TT_AttributeSquare) && IsCpp &&
 // FIXME: This is a temporary workaround for the case where 
clang-format
 // sets BreakBeforeParameter to avoid bin packing and this creates a
 // completely unnecessary line break after a template type that isn't
@@ -677,8 +679,8 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   auto &CurrentState = State.Stack.back();
 
   bool DisallowLineBreaksOnThisLine =
-  Style.LambdaBodyIndentation == FormatStyle::LBI_Signature &&
-  Style.isCpp() && [&Current] {
+  Style.LambdaBodyIndentation == FormatStyle::LBI_Signature && IsCpp &&
+  [&Current] {
 // Deal with lambda arguments in C++. The aim here is to ensure that we
 // don't over-indent lambda function bodies when lambdas are passed as
 // arguments to function calls. We do this by ensuring that either all
@@ -1091,7 +1093,7 @@ unsigned 
ContinuationIndenter::addTokenOnNewLine(LineState &State,
   // Any break on this level means that the parent level has been broken
   // and we need to avoid bin packing there.
   bool NestedBlockSpecialCase =
-  (!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
+  (!IsCpp && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
   (Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&
State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index e64ba7eebc1ce8..00182f75560a2c 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3943,6 +3943,8 @@ const char *DefaultFormatStyle = "file";
 
 const char *DefaultFallbackStyle = "LLVM";
 
+bool IsCpp = false;
+
 llvm::ErrorOr>
 loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
FormatStyle *Style, bool AllowUnknownOptions) {
diff --git a/clang/lib/Format/FormatToken.cpp b/clang/lib/Format/FormatToken.cpp
index 4fb70ffac706d0..665b2e43259b21 100644
--- a/clang/lib/Format/FormatToken.cpp
+++ b/clang/lib/Format/FormatToken.cpp

[clang] [clang-format][NFC] Eliminate the IsCpp parameter in all functions (PR #84599)

2024-03-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes



---

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


12 Files Affected:

- (modified) clang/include/clang/Format/Format.h (+2) 
- (modified) clang/lib/Format/ContinuationIndenter.cpp (+7-5) 
- (modified) clang/lib/Format/Format.cpp (+2) 
- (modified) clang/lib/Format/FormatToken.cpp (+3-3) 
- (modified) clang/lib/Format/FormatToken.h (+3-3) 
- (modified) clang/lib/Format/FormatTokenLexer.cpp (+3-2) 
- (modified) clang/lib/Format/QualifierAlignmentFixer.cpp (+13-16) 
- (modified) clang/lib/Format/QualifierAlignmentFixer.h (+2-3) 
- (modified) clang/lib/Format/TokenAnnotator.cpp (+23-25) 
- (modified) clang/lib/Format/TokenAnnotator.h (+3-3) 
- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+12-10) 
- (modified) clang/lib/Format/UnwrappedLineParser.h (-1) 


``diff
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 590297fd89a398..ff96e2bdbbc1d8 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5228,6 +5228,8 @@ extern const char *DefaultFormatStyle;
 /// Different builds can modify the value to the preferred styles.
 extern const char *DefaultFallbackStyle;
 
+extern bool IsCpp;
+
 /// Construct a FormatStyle based on ``StyleName``.
 ///
 /// ``StyleName`` can take several forms:
diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index df44e6994c4784..506e21725ba9f7 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -241,7 +241,9 @@ ContinuationIndenter::ContinuationIndenter(const 
FormatStyle &Style,
 : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
   Whitespaces(Whitespaces), Encoding(Encoding),
   BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
-  CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
+  CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {
+  IsCpp = Style.isCpp();
+}
 
 LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
 unsigned FirstStartColumn,
@@ -406,7 +408,7 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   }
   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
(Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
-State.Line->First->isNot(TT_AttributeSquare) && Style.isCpp() &&
+State.Line->First->isNot(TT_AttributeSquare) && IsCpp &&
 // FIXME: This is a temporary workaround for the case where 
clang-format
 // sets BreakBeforeParameter to avoid bin packing and this creates a
 // completely unnecessary line break after a template type that isn't
@@ -677,8 +679,8 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   auto &CurrentState = State.Stack.back();
 
   bool DisallowLineBreaksOnThisLine =
-  Style.LambdaBodyIndentation == FormatStyle::LBI_Signature &&
-  Style.isCpp() && [&Current] {
+  Style.LambdaBodyIndentation == FormatStyle::LBI_Signature && IsCpp &&
+  [&Current] {
 // Deal with lambda arguments in C++. The aim here is to ensure that we
 // don't over-indent lambda function bodies when lambdas are passed as
 // arguments to function calls. We do this by ensuring that either all
@@ -1091,7 +1093,7 @@ unsigned 
ContinuationIndenter::addTokenOnNewLine(LineState &State,
   // Any break on this level means that the parent level has been broken
   // and we need to avoid bin packing there.
   bool NestedBlockSpecialCase =
-  (!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
+  (!IsCpp && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
   (Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&
State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index e64ba7eebc1ce8..00182f75560a2c 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3943,6 +3943,8 @@ const char *DefaultFormatStyle = "file";
 
 const char *DefaultFallbackStyle = "LLVM";
 
+bool IsCpp = false;
+
 llvm::ErrorOr>
 loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
FormatStyle *Style, bool AllowUnknownOptions) {
diff --git a/clang/lib/Format/FormatToken.cpp b/clang/lib/Format/FormatToken.cpp
index 4fb70ffac706d0..665b2e43259b21 100644
--- a/clang/lib/Format/FormatToken.cpp
+++ b/clang/lib/Format/FormatToken.cpp
@@ -78,15 +78,15 @@ static SmallVector CppNonKeywordTypes = {
 "uint32_t", "uint64_t",  "uint8_t", "uintptr_t",
 };
 
-bool FormatToken::isTypeNa

[clang] [clang-format][NFC] Eliminate the IsCpp parameter in all functions (PR #84599)

2024-03-08 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/84599

None

>From bd3e866189ad4c238ea0afbbc30fbe88e0406eb9 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 8 Mar 2024 19:47:54 -0800
Subject: [PATCH] [clang-format][NFC] Eliminate the IsCpp parameter in all
 functions

---
 clang/include/clang/Format/Format.h  |  2 +
 clang/lib/Format/ContinuationIndenter.cpp| 12 +++--
 clang/lib/Format/Format.cpp  |  2 +
 clang/lib/Format/FormatToken.cpp |  6 +--
 clang/lib/Format/FormatToken.h   |  6 +--
 clang/lib/Format/FormatTokenLexer.cpp|  5 +-
 clang/lib/Format/QualifierAlignmentFixer.cpp | 29 ++--
 clang/lib/Format/QualifierAlignmentFixer.h   |  5 +-
 clang/lib/Format/TokenAnnotator.cpp  | 48 ++--
 clang/lib/Format/TokenAnnotator.h|  6 +--
 clang/lib/Format/UnwrappedLineParser.cpp | 22 +
 clang/lib/Format/UnwrappedLineParser.h   |  1 -
 12 files changed, 73 insertions(+), 71 deletions(-)

diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 590297fd89a398..ff96e2bdbbc1d8 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5228,6 +5228,8 @@ extern const char *DefaultFormatStyle;
 /// Different builds can modify the value to the preferred styles.
 extern const char *DefaultFallbackStyle;
 
+extern bool IsCpp;
+
 /// Construct a FormatStyle based on ``StyleName``.
 ///
 /// ``StyleName`` can take several forms:
diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index df44e6994c4784..506e21725ba9f7 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -241,7 +241,9 @@ ContinuationIndenter::ContinuationIndenter(const 
FormatStyle &Style,
 : Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
   Whitespaces(Whitespaces), Encoding(Encoding),
   BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
-  CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
+  CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {
+  IsCpp = Style.isCpp();
+}
 
 LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
 unsigned FirstStartColumn,
@@ -406,7 +408,7 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   }
   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
(Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
-State.Line->First->isNot(TT_AttributeSquare) && Style.isCpp() &&
+State.Line->First->isNot(TT_AttributeSquare) && IsCpp &&
 // FIXME: This is a temporary workaround for the case where 
clang-format
 // sets BreakBeforeParameter to avoid bin packing and this creates a
 // completely unnecessary line break after a template type that isn't
@@ -677,8 +679,8 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   auto &CurrentState = State.Stack.back();
 
   bool DisallowLineBreaksOnThisLine =
-  Style.LambdaBodyIndentation == FormatStyle::LBI_Signature &&
-  Style.isCpp() && [&Current] {
+  Style.LambdaBodyIndentation == FormatStyle::LBI_Signature && IsCpp &&
+  [&Current] {
 // Deal with lambda arguments in C++. The aim here is to ensure that we
 // don't over-indent lambda function bodies when lambdas are passed as
 // arguments to function calls. We do this by ensuring that either all
@@ -1091,7 +1093,7 @@ unsigned 
ContinuationIndenter::addTokenOnNewLine(LineState &State,
   // Any break on this level means that the parent level has been broken
   // and we need to avoid bin packing there.
   bool NestedBlockSpecialCase =
-  (!Style.isCpp() && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
+  (!IsCpp && Current.is(tok::r_brace) && State.Stack.size() > 1 &&
State.Stack[State.Stack.size() - 2].NestedBlockInlined) ||
   (Style.Language == FormatStyle::LK_ObjC && Current.is(tok::r_brace) &&
State.Stack.size() > 1 && !Style.ObjCBreakBeforeNestedBlockParam);
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index e64ba7eebc1ce8..00182f75560a2c 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3943,6 +3943,8 @@ const char *DefaultFormatStyle = "file";
 
 const char *DefaultFallbackStyle = "LLVM";
 
+bool IsCpp = false;
+
 llvm::ErrorOr>
 loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
FormatStyle *Style, bool AllowUnknownOptions) {
diff --git a/clang/lib/Format/FormatToken.cpp b/clang/lib/Format/FormatToken.cpp
index 4fb70ffac706d0..665b2e43259b21 100644
--- a/clang/lib/Format/FormatToken.cpp
+++ b/clang/lib/Format/FormatToken.cpp
@@ -78,15 +78,15 @@ static SmallVector CppNonKeywordTypes

[clang] [clang-format] Handle common C++ non-keyword types as such (PR #83709)

2024-03-08 Thread Owen Pan via cfe-commits

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


[clang] 0baef3b - [clang-format] Handle common C++ non-keyword types as such (#83709)

2024-03-08 Thread via cfe-commits

Author: Owen Pan
Date: 2024-03-08T19:42:35-08:00
New Revision: 0baef3b18cdbbdcf9f07c10607407ad0fb541449

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

LOG: [clang-format] Handle common C++ non-keyword types as such (#83709)

Fixes #83400.

Added: 


Modified: 
clang/lib/Format/FormatToken.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/QualifierAlignmentFixer.cpp
clang/lib/Format/QualifierAlignmentFixer.h
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.cpp 
b/clang/lib/Format/FormatToken.cpp
index 56a7b2d6387765..4fb70ffac706d0 100644
--- a/clang/lib/Format/FormatToken.cpp
+++ b/clang/lib/Format/FormatToken.cpp
@@ -71,8 +71,22 @@ bool FormatToken::isSimpleTypeSpecifier() const {
   }
 }
 
-bool FormatToken::isTypeOrIdentifier() const {
-  return isSimpleTypeSpecifier() || Tok.isOneOf(tok::kw_auto, tok::identifier);
+// Sorted common C++ non-keyword types.
+static SmallVector CppNonKeywordTypes = {
+"clock_t",  "int16_t",   "int32_t", "int64_t",   "int8_t",
+"intptr_t", "ptr
diff _t", "size_t",  "time_t","uint16_t",
+"uint32_t", "uint64_t",  "uint8_t", "uintptr_t",
+};
+
+bool FormatToken::isTypeName(bool IsCpp) const {
+  return is(TT_TypeName) || isSimpleTypeSpecifier() ||
+ (IsCpp && is(tok::identifier) &&
+  std::binary_search(CppNonKeywordTypes.begin(),
+ CppNonKeywordTypes.end(), TokenText));
+}
+
+bool FormatToken::isTypeOrIdentifier(bool IsCpp) const {
+  return isTypeName(IsCpp) || isOneOf(tok::kw_auto, tok::identifier);
 }
 
 bool FormatToken::isBlockIndentedInitRBrace(const FormatStyle &Style) const {

diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 31245495041960..f4566e4a335138 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -676,7 +676,9 @@ struct FormatToken {
   /// Determine whether the token is a simple-type-specifier.
   [[nodiscard]] bool isSimpleTypeSpecifier() const;
 
-  [[nodiscard]] bool isTypeOrIdentifier() const;
+  [[nodiscard]] bool isTypeName(bool IsCpp) const;
+
+  [[nodiscard]] bool isTypeOrIdentifier(bool IsCpp) const;
 
   bool isObjCAccessSpecifier() const {
 return is(tok::at) && Next &&

diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index 0c63d330b5aed4..c263530456727c 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -268,11 +268,13 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeRight(
   if (isPossibleMacro(TypeToken))
 return Tok;
 
+  const bool IsCpp = Style.isCpp();
+
   // The case `const long long int volatile` -> `long long int const volatile`
   // The case `long const long int volatile` -> `long long int const volatile`
   // The case `long long volatile int const` -> `long long int const volatile`
   // The case `const long long volatile int` -> `long long int const volatile`
-  if (TypeToken->isSimpleTypeSpecifier()) {
+  if (TypeToken->isTypeName(IsCpp)) {
 // The case `const decltype(foo)` -> `const decltype(foo)`
 // The case `const typeof(foo)` -> `const typeof(foo)`
 // The case `const _Atomic(foo)` -> `const _Atomic(foo)`
@@ -280,8 +282,10 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeRight(
   return Tok;
 
 const FormatToken *LastSimpleTypeSpecifier = TypeToken;
-while (isQualifierOrType(LastSimpleTypeSpecifier->getNextNonComment()))
+while (isQualifierOrType(LastSimpleTypeSpecifier->getNextNonComment(),
+ IsCpp)) {
   LastSimpleTypeSpecifier = LastSimpleTypeSpecifier->getNextNonComment();
+}
 
 rotateTokens(SourceMgr, Fixes, Tok, LastSimpleTypeSpecifier,
  /*Left=*/false);
@@ -291,7 +295,7 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeRight(
   // The case  `unsigned short const` -> `unsigned short const`
   // The case:
   // `unsigned short volatile const` -> `unsigned short const volatile`
-  if (PreviousCheck && PreviousCheck->isSimpleTypeSpecifier()) {
+  if (PreviousCheck && PreviousCheck->isTypeName(IsCpp)) {
 if (LastQual != Tok)
   rotateTokens(SourceMgr, Fixes, Tok, LastQual, /*Left=*/false);
 return Tok;
@@ -408,11 +412,11 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeLeft(
   // The case `volatile long long const int` -> `const volatile long long int`
   // The case `const long long volatile int` -> `const volatile long long int`
   // The case `long volatile long int const` -> `const volatile long long int`
-  if (TypeToken->

[clang] [clang-format] Handle common C++ non-keyword types as such (PR #83709)

2024-03-08 Thread Owen Pan via cfe-commits

owenca wrote:

> Just thinking out loud and maybe not for this patch but for a more general 
> solution, what we seem to never do is collect information about types local 
> to the file as we go; For example what if a first pass identified types from 
> declarations and function argument declarations, return types, template 
> arguments and added them to a structure that would have some probability that 
> a given identifier was actually a type.

I'm kind of skeptical because we can't even correctly annotate the declarators 
all the time, but someone must actually try it to find out.

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


[clang] [clang-format] Handle common C++ non-keyword types as such (PR #83709)

2024-03-08 Thread Owen Pan via cfe-commits

owenca wrote:

> Can the TypeNames mechanism be prepopulated with this list of types instead?

I don't see how that would work. Please note that the TypeNames option is not 
specific to C/C++/Objective-C. Otherwise, I could simply change 
`isTypeName(bool IsCpp)` to `isCppTypeName()`.

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


[clang] [clang] Fix crash when declaring invalid lambda member (PR #74110)

2024-03-08 Thread Nico Weber via cfe-commits

nico wrote:

Also on the official waterfall, eg here: 
https://lab.llvm.org/buildbot/#/builders/188/builds/42935

Can you take a look, and revert for now if it takes a while to fix?

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


[clang] [clang] Fix crash when declaring invalid lambda member (PR #74110)

2024-03-08 Thread Nico Weber via cfe-commits

nico wrote:

Looks like the included test still makes clang crash: 
http://45.33.8.238/linux/132722/step_7.txt

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


[clang] [llvm] [RISCV] Support RISC-V Profiles in -march option (PR #76357)

2024-03-08 Thread Craig Topper via cfe-commits


@@ -0,0 +1,189 @@
+//===-- RISCVProfiles.td - RISC-V Profiles -*- tablegen 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+class RISCVProfile features>

topperc wrote:

> When adding new RISCVProcessorModel, we can just specify profile feature and 
> those implemented optional extensions.

This case can be handled with a named list in tablegen and a `listconcat` 
without exposing it as a subtarget feature.

> When disassembling some object files, we don't need a long -mattr if we know 
> it's compiled with a profile.

If objdump requires you to use `-mattr`, instead of `-march`, that's a bad 
interface design. Users of objdump shouldn't need to know if they to have pass 
`experimental-` before an extension name.

> When doing some end-to-end tests that we need to discard CPU specific 
> features (so we can't use -mcpu), we don't need a long -mattr.

This might be an argument for a `generic-` `mcpu`.

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


[clang-tools-extra] [clang-tidy]avoid bugprone-unused-return-value false positive for assignment operator overloading (PR #84489)

2024-03-08 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/84489

>From 265db5ee772772bef4099cc97b69995cfa67b3f2 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Fri, 8 Mar 2024 22:15:20 +0800
Subject: [PATCH 1/3] [clang-tidy]avoid bugprone-unused-return-value false
 positive for assignment operator overloading

Fixes: #84480
We assuem assignemnt at most of time, operator overloading means the value is 
assigned to the other variable, then clang-tidy should suppress warning even if 
this operator overloading match the regex.
---
 .../bugprone/UnusedReturnValueCheck.cpp   | 24 --
 clang-tools-extra/docs/ReleaseNotes.rst   |  4 +--
 .../unused-return-value-avoid-assignment.cpp  | 31 +++
 3 files changed, 47 insertions(+), 12 deletions(-)
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value-avoid-assignment.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
index 1252b2f23805a1..2167d381c42b03 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
@@ -11,6 +11,7 @@
 #include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 
 using namespace clang::ast_matchers;
 using namespace clang::ast_matchers::internal;
@@ -157,16 +158,19 @@ void 
UnusedReturnValueCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 }
 
 void UnusedReturnValueCheck::registerMatchers(MatchFinder *Finder) {
-  auto MatchedDirectCallExpr =
-  expr(callExpr(callee(functionDecl(
-// Don't match void overloads of checked functions.
-unless(returns(voidType())),
-
anyOf(isInstantiatedFrom(matchers::matchesAnyListedName(
-  CheckedFunctions)),
-  returns(hasCanonicalType(hasDeclaration(
-  namedDecl(matchers::matchesAnyListedName(
-  CheckedReturnTypes)
-   .bind("match"));
+  auto MatchedDirectCallExpr = expr(
+  callExpr(callee(functionDecl(
+   // Don't match void overloads of checked functions.
+   unless(returns(voidType())),
+   // Don't match copy or move assignment operator.
+   unless(cxxMethodDecl(anyOf(isCopyAssignmentOperator(),
+  isMoveAssignmentOperator(,
+   anyOf(isInstantiatedFrom(
+ matchers::matchesAnyListedName(CheckedFunctions)),
+ returns(hasCanonicalType(hasDeclaration(
+ namedDecl(matchers::matchesAnyListedName(
+ CheckedReturnTypes)
+  .bind("match"));
 
   auto CheckCastToVoid =
   AllowCastToVoid ? castExpr(unless(hasCastKind(CK_ToVoid))) : castExpr();
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index b5f025ce467a15..c7121fe07e0ad3 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -152,9 +152,9 @@ Changes in existing checks
 
 - Improved :doc:`bugprone-unused-return-value
   ` check by updating the
-  parameter `CheckedFunctions` to support regexp and avoiding false postive for
+  parameter `CheckedFunctions` to support regexp, avoiding false positive for
   function with the same prefix as the default argument, e.g. 
``std::unique_ptr``
-  and ``std::unique``.
+  and ``std::unique``, avoiding false positive for assignment operator 
overloading.
 
 - Improved :doc:`bugprone-use-after-move
   ` check to also handle
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value-avoid-assignment.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value-avoid-assignment.cpp
new file mode 100644
index 00..8bd3c30e71b51a
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value-avoid-assignment.cpp
@@ -0,0 +1,31 @@
+// RUN: %check_clang_tidy %s bugprone-unused-return-value %t \
+// RUN: -config='{CheckOptions: \
+// RUN:  {bugprone-unused-return-value.CheckedFunctions: "::*"}}' \
+// RUN: --
+
+struct S {
+  S(){};
+  S(S const &);
+  S(S &&);
+  S &operator=(S const &);
+  S &operator=(S &&);
+};
+
+S returnValue();
+S const &returnRef();
+
+void bar() {
+  returnValue();
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: the value returned by this 
function should not be disregarded; neglecting it may lead to errors
+
+  S a{};
+  a = returnValue();
+  // CHECK-NOT: [[@LINE-1]]:3: warning
+  a.operator=(returnValue());
+  // CHECK-NOT: [[@LINE-1]]:3: warning

[clang] [Clang][Sema]: Allow flexible arrays in unions and alone in structs (PR #84428)

2024-03-08 Thread Kees Cook via cfe-commits

kees wrote:

For historical reference, the first version of this PR is visible here now: 
https://github.com/kees/llvm-project/commit/ce31f1d75f060b32e5dbc5756fe41cc8eaac83a6

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


[clang] [Clang] Document some of the implementation-defined keywords (PR #84591)

2024-03-08 Thread Nikolas Klauser via cfe-commits

https://github.com/philnik777 updated 
https://github.com/llvm/llvm-project/pull/84591

>From 634b8e8285b23201d7ad852ae35044d9b89c3c63 Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Sat, 9 Mar 2024 02:14:36 +0100
Subject: [PATCH] [Clang] Document some of the implementation-defined keywords

---
 clang/docs/LanguageExtensions.rst | 122 +++---
 1 file changed, 111 insertions(+), 11 deletions(-)

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 06af93fd3c15ca..2530d657be5996 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -433,6 +433,117 @@ __datasizeof
 ``__datasizeof`` behaves like ``sizeof``, except that it returns the size of 
the
 type ignoring tail padding.
 
+_BitInt, _ExtInt
+
+
+Clang supports the C23 ``_BitInt(N)`` feature as an extension in older C modes
+and in C++. This type was previously implemented in Clang with the same
+semantics, but spelled ``_ExtInt(N)``. This spelling has been deprecated in
+favor of the standard type.
+
+Note: the ABI for ``_BitInt(N)`` is still in the process of being stabilized,
+so this type should not yet be used in interfaces that require ABI stability.
+
+C keywords supported in all language modes
+--
+
+Clang supports ``_Alignas``, ``_Alignof``, ``_Atomic``, ``_Complex``,
+``_Generic``, ``_Imaginary``, ``_Noreturn``, ``_Static_assert``,
+``_Thread_local``, ``_Float16``, ``_Decimal32``, ``_Decimal64`` and
+``_Decimal128`` in all language modes with the C semantics.
+
+__alignof, __alignof__
+--
+
+``__alignof`` and ``__alignof__`` return, in contrast to ``_Alignof`` and
+``alignof``, the preferred alignment of a type. This may be larger than the
+required alignment for improved performance.
+
+__extension__
+-
+
+``__extension__`` suppressed extension diagnostics in the statement it is
+prepended to.
+
+__auto_type
+---
+
+``__auto_type`` behaves the same as C++11s ``auto`` but is available in all
+language modes.
+
+__imag, __imag__
+
+
+``__imag`` and ``__imag__`` can be used to get the imaginary part of a complex
+value.
+
+__real, __real__
+
+
+``__real`` and ``__real__`` can be used to get the real part of a complex 
value.
+
+__asm, __asm__
+--
+
+``__asm`` and ``__asm__`` are alternate spellings for ``asm``, but available in
+all language modes.
+
+__complex, __complex__
+--
+
+``__complex`` and ``__complex__`` are alternate spellings for ``_Complex``.
+
+__const, __const__
+--
+
+``__const`` and ``__const__`` are alternate spellings for ``const``.
+
+__decltype
+--
+
+``__decltype`` is an alternate spelling for ``decltype``, but is also available
+in C++ modes before C++11.
+
+__inline, __inline__
+
+
+``__inline`` and ``__inline__`` are alternate spellings for ``inline``, but are
+available in all language modes.
+
+__nullptr
+-
+
+``__nullptr`` is an alternate spelling for ``nullptr``, but is also available 
in
+C++ modes before C++11.
+
+__restrict, __restrict__
+
+
+``__restrict`` and ``__restrict__`` are alternate spellings for ``restrict``,
+but are available in all language modes.
+
+__signed, __signed__
+
+
+``__signed`` and ``__signed__`` are alternate spellings for ``signed``.
+
+__typeof, __typeof__
+
+
+``__typeof`` and ``__typeof__`` are alternate spellings for ``typeof``, but are
+available in all langauge modes.
+
+__volatile, __volatile__
+
+
+``__volatile`` and ``__volatile__`` are alternate spellings for ``volatile``.
+
+__char16_t, __char32_t
+--
+
+``__char16_t`` and ``__char32_t`` are alternate spellings for ``char16_t`` and
+``char32_t`` respectively, but are also available in C++ modes before C++11.
+
 ..
   FIXME: This should list all the keyword extensions
 
@@ -5319,17 +5430,6 @@ Examples are:
# 60 "" 2 // return to "main.c"
# 1 "/usr/ancient/header.h" 1 4 // Enter an implicit extern "C" header
 
-Extended Integer Types
-==
-
-Clang supports the C23 ``_BitInt(N)`` feature as an extension in older C modes
-and in C++. This type was previously implemented in Clang with the same
-semantics, but spelled ``_ExtInt(N)``. This spelling has been deprecated in
-favor of the standard type.
-
-Note: the ABI for ``_BitInt(N)`` is still in the process of being stabilized,
-so this type should not yet be used in interfaces that require ABI stability.
-
 Intrinsics Support within Constant Expressions
 ==
 

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


[clang] [OBJC] Allow __attribute__((NSObject)) types be used as lightweight generic specifiers (PR #84593)

2024-03-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: dmaclach (dmaclach)


Changes

As per 
https://clang.llvm.org/docs/AutomaticReferenceCounting.html#retainable-object-pointers,
 types with `__attribute__((NSObject))` are retainable, and thus should be 
eligible to be used as lightweight generic specifiers.

Fix for #84592 84592

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


2 Files Affected:

- (modified) clang/lib/Sema/SemaType.cpp (+5) 
- (added) clang/test/SemaObjC/attr-objc-NSObject.m (+23) 


``diff
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 3148299f6467af..87173a52af8143 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -1018,6 +1018,11 @@ static QualType applyObjCTypeArgs(Sema &S, 
SourceLocation loc, QualType type,
   return type;
 }
 
+// Types that have __attribute__((NSObject)) are permitted.
+if (typeArg->isObjCNSObjectType()) {
+  continue;
+}
+
 // Dependent types will be checked at instantiation time.
 if (typeArg->isDependentType()) {
   continue;
diff --git a/clang/test/SemaObjC/attr-objc-NSObject.m 
b/clang/test/SemaObjC/attr-objc-NSObject.m
new file mode 100644
index 00..76a01dcef01637
--- /dev/null
+++ b/clang/test/SemaObjC/attr-objc-NSObject.m
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -verify -Wno-objc-root-class -fsyntax-only %s
+
+@interface NSArray<__covariant ObjectType>
+- (void)containsObject:(ObjectType)anObject; // expected-note {{passing 
argument to parameter 'anObject' here}}
+- (void)description;
+@end
+
+typedef __attribute__((NSObject)) struct Foo *FooRef;
+typedef struct Bar *BarRef;
+
+void good() {
+  FooRef object;
+  NSArray *array;
+  [array containsObject:object];
+  [object description];
+}
+
+void bad() {
+  BarRef object;
+  NSArray *array; // expected-error {{type argument 'BarRef' (aka 
'struct Bar *') is neither an Objective-C object nor a block type}}
+  [array containsObject:object]; // expected-warning {{incompatible pointer 
types sending 'BarRef' (aka 'struct Bar *') to parameter of type 'id'}}
+  [object description]; // expected-warning {{receiver type 'BarRef' (aka 
'struct Bar *') is not 'id' or interface pointer, consider casting it to 'id'}}
+}

``




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


[clang] [OBJC] Allow __attribute__((NSObject)) types be used as lightweight generic specifiers (PR #84593)

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


[clang] [OBJC] Allow __attribute__((NSObject)) types be used as lightweight generic specifiers (PR #84593)

2024-03-08 Thread via cfe-commits

https://github.com/dmaclach created 
https://github.com/llvm/llvm-project/pull/84593

As per 
https://clang.llvm.org/docs/AutomaticReferenceCounting.html#retainable-object-pointers,
 types with `__attribute__((NSObject))` are retainable, and thus should be 
eligible to be used as lightweight generic specifiers.

Fix for #84592 84592

>From fe3ac2146f6fb969975848a9137b38eb2eb1d918 Mon Sep 17 00:00:00 2001
From: Dave MacLachlan 
Date: Fri, 8 Mar 2024 15:14:56 -0800
Subject: [PATCH] Allow __attribute__((NSObject)) types be used as lightweight
 generic specifiers

As per 
https://clang.llvm.org/docs/AutomaticReferenceCounting.html#retainable-object-pointers,
types with `__attribute__((NSObject))` are retainable, and thus should be 
eligible to be
used as lightweight generic specifiers.
---
 clang/lib/Sema/SemaType.cpp  |  5 +
 clang/test/SemaObjC/attr-objc-NSObject.m | 23 +++
 2 files changed, 28 insertions(+)
 create mode 100644 clang/test/SemaObjC/attr-objc-NSObject.m

diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 3148299f6467af..87173a52af8143 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -1018,6 +1018,11 @@ static QualType applyObjCTypeArgs(Sema &S, 
SourceLocation loc, QualType type,
   return type;
 }
 
+// Types that have __attribute__((NSObject)) are permitted.
+if (typeArg->isObjCNSObjectType()) {
+  continue;
+}
+
 // Dependent types will be checked at instantiation time.
 if (typeArg->isDependentType()) {
   continue;
diff --git a/clang/test/SemaObjC/attr-objc-NSObject.m 
b/clang/test/SemaObjC/attr-objc-NSObject.m
new file mode 100644
index 00..76a01dcef01637
--- /dev/null
+++ b/clang/test/SemaObjC/attr-objc-NSObject.m
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -verify -Wno-objc-root-class -fsyntax-only %s
+
+@interface NSArray<__covariant ObjectType>
+- (void)containsObject:(ObjectType)anObject; // expected-note {{passing 
argument to parameter 'anObject' here}}
+- (void)description;
+@end
+
+typedef __attribute__((NSObject)) struct Foo *FooRef;
+typedef struct Bar *BarRef;
+
+void good() {
+  FooRef object;
+  NSArray *array;
+  [array containsObject:object];
+  [object description];
+}
+
+void bad() {
+  BarRef object;
+  NSArray *array; // expected-error {{type argument 'BarRef' (aka 
'struct Bar *') is neither an Objective-C object nor a block type}}
+  [array containsObject:object]; // expected-warning {{incompatible pointer 
types sending 'BarRef' (aka 'struct Bar *') to parameter of type 'id'}}
+  [object description]; // expected-warning {{receiver type 'BarRef' (aka 
'struct Bar *') is not 'id' or interface pointer, consider casting it to 'id'}}
+}

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


[clang] [Clang] Document some of the implementation-defined keywords (PR #84591)

2024-03-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Nikolas Klauser (philnik777)


Changes



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


1 Files Affected:

- (modified) clang/docs/LanguageExtensions.rst (+112-11) 


``diff
diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 06af93fd3c15ca..9c6c91c1cf4ba3 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -433,6 +433,118 @@ __datasizeof
 ``__datasizeof`` behaves like ``sizeof``, except that it returns the size of 
the
 type ignoring tail padding.
 
+_BitInt, _ExtInt
+
+
+Clang supports the C23 ``_BitInt(N)`` feature as an extension in older C modes
+and in C++. This type was previously implemented in Clang with the same
+semantics, but spelled ``_ExtInt(N)``. This spelling has been deprecated in
+favor of the standard type.
+
+Note: the ABI for ``_BitInt(N)`` is still in the process of being stabilized,
+so this type should not yet be used in interfaces that require ABI stability.
+
+C keywords supported in all language modes
+--
+
+Clang supports ``_Alignas``, ``_Alignof``, ``_Atomic``, ``_Complex``,
+``_Generic``, ``_Imaginary``, ``_Noreturn``, ``_Static_assert``,
+``_Thread_local``, ``_Float16``, ``_Decimal32``, ``_Decimal64`` and
+``_Decimal128`` in all language modes with the C semantics.
+
+__alignof, __alignof__
+-
+
+``__alignof`` and ``__alignof__`` return, in contrast to ``_Alignof`` and
+``alignof``, the preferred alignment of a type. This may be larger than the
+required alignment for improved performance.
+
+__extension__
+-
+
+``__extension__`` suppressed extension diagnostics in the statement it is
+prepended to.
+
+__auto_type
+---
+
+``__auto_type`` behaves the same as C++11s ``auto`` but is available in all
+language modes.
+
+__imag, __imag__
+
+
+``__imag`` and ``__imag__`` can be used to get the imaginary part of a complex
+value.
+
+__real, __real__
+
+
+``__real`` and ``__real__`` can be used to get the real part of a complex 
value.
+
+__asm, __asm__
+--
+
+``__asm`` and ``__asm__`` are alternate spellings for ``asm``, but available in
+all language modes.
+
+__complex, __complex__
+--
+
+``__complex`` and ``__complex__`` are alternate spellings for ``_Complex``.
+These are available for compatibility with old code.
+
+__const, __const__
+--
+
+``__const`` and ``__const__`` are alternate spellings for ``const``.
+
+__decltype
+--
+
+``__decltype`` is an alternate spelling for ``decltype``, but is also available
+in C++ modes before C++11.
+
+__inline, __inline__
+
+
+``__inline`` and ``__inline__`` are alternate spellings for ``inline``, but are
+available in all language modes.
+
+__nullptr
+-
+
+``__nullptr`` is an alternate spelling for ``nullptr``, but is also available 
in
+C++ modes before C++11.
+
+__restrict, __restrict__
+
+
+``__restrict`` and ``__restrict__`` are alternate spellings for ``restrict``,
+but are available in all language modes.
+
+__signed, __signed__
+
+
+``__signed`` and ``__signed__`` are alternate spellings for ``signed``.
+
+__typeof, __typeof__
+
+
+``__typeof`` and ``__typeof__`` are alternate spellings for ``typeof``, but are
+available in all langauge modes.
+
+__volatile, __volatile__
+
+
+``__volatile`` and ``__volatile__`` are alternate spellings for ``volatile``.
+
+__char16_t, __char32_t
+--
+
+``__char16_t`` and ``__char32_t`` are alternate spellings for ``char16_t`` and
+``char32_t`` respectively, but are also available in C++ modes before C++11.
+
 ..
   FIXME: This should list all the keyword extensions
 
@@ -5319,17 +5431,6 @@ Examples are:
# 60 "" 2 // return to "main.c"
# 1 "/usr/ancient/header.h" 1 4 // Enter an implicit extern "C" header
 
-Extended Integer Types
-==
-
-Clang supports the C23 ``_BitInt(N)`` feature as an extension in older C modes
-and in C++. This type was previously implemented in Clang with the same
-semantics, but spelled ``_ExtInt(N)``. This spelling has been deprecated in
-favor of the standard type.
-
-Note: the ABI for ``_BitInt(N)`` is still in the process of being stabilized,
-so this type should not yet be used in interfaces that require ABI stability.
-
 Intrinsics Support within Constant Expressions
 ==
 

``




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


[clang] [Clang] Document some of the implementation-defined keywords (PR #84591)

2024-03-08 Thread Nikolas Klauser via cfe-commits

https://github.com/philnik777 created 
https://github.com/llvm/llvm-project/pull/84591

None

>From 479b0dec7feb17beaccbdc029799f2333d979ce4 Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Sat, 9 Mar 2024 02:14:36 +0100
Subject: [PATCH] [Clang] Document some of the implementation-defined keywords

---
 clang/docs/LanguageExtensions.rst | 123 +++---
 1 file changed, 112 insertions(+), 11 deletions(-)

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 06af93fd3c15ca..9c6c91c1cf4ba3 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -433,6 +433,118 @@ __datasizeof
 ``__datasizeof`` behaves like ``sizeof``, except that it returns the size of 
the
 type ignoring tail padding.
 
+_BitInt, _ExtInt
+
+
+Clang supports the C23 ``_BitInt(N)`` feature as an extension in older C modes
+and in C++. This type was previously implemented in Clang with the same
+semantics, but spelled ``_ExtInt(N)``. This spelling has been deprecated in
+favor of the standard type.
+
+Note: the ABI for ``_BitInt(N)`` is still in the process of being stabilized,
+so this type should not yet be used in interfaces that require ABI stability.
+
+C keywords supported in all language modes
+--
+
+Clang supports ``_Alignas``, ``_Alignof``, ``_Atomic``, ``_Complex``,
+``_Generic``, ``_Imaginary``, ``_Noreturn``, ``_Static_assert``,
+``_Thread_local``, ``_Float16``, ``_Decimal32``, ``_Decimal64`` and
+``_Decimal128`` in all language modes with the C semantics.
+
+__alignof, __alignof__
+-
+
+``__alignof`` and ``__alignof__`` return, in contrast to ``_Alignof`` and
+``alignof``, the preferred alignment of a type. This may be larger than the
+required alignment for improved performance.
+
+__extension__
+-
+
+``__extension__`` suppressed extension diagnostics in the statement it is
+prepended to.
+
+__auto_type
+---
+
+``__auto_type`` behaves the same as C++11s ``auto`` but is available in all
+language modes.
+
+__imag, __imag__
+
+
+``__imag`` and ``__imag__`` can be used to get the imaginary part of a complex
+value.
+
+__real, __real__
+
+
+``__real`` and ``__real__`` can be used to get the real part of a complex 
value.
+
+__asm, __asm__
+--
+
+``__asm`` and ``__asm__`` are alternate spellings for ``asm``, but available in
+all language modes.
+
+__complex, __complex__
+--
+
+``__complex`` and ``__complex__`` are alternate spellings for ``_Complex``.
+These are available for compatibility with old code.
+
+__const, __const__
+--
+
+``__const`` and ``__const__`` are alternate spellings for ``const``.
+
+__decltype
+--
+
+``__decltype`` is an alternate spelling for ``decltype``, but is also available
+in C++ modes before C++11.
+
+__inline, __inline__
+
+
+``__inline`` and ``__inline__`` are alternate spellings for ``inline``, but are
+available in all language modes.
+
+__nullptr
+-
+
+``__nullptr`` is an alternate spelling for ``nullptr``, but is also available 
in
+C++ modes before C++11.
+
+__restrict, __restrict__
+
+
+``__restrict`` and ``__restrict__`` are alternate spellings for ``restrict``,
+but are available in all language modes.
+
+__signed, __signed__
+
+
+``__signed`` and ``__signed__`` are alternate spellings for ``signed``.
+
+__typeof, __typeof__
+
+
+``__typeof`` and ``__typeof__`` are alternate spellings for ``typeof``, but are
+available in all langauge modes.
+
+__volatile, __volatile__
+
+
+``__volatile`` and ``__volatile__`` are alternate spellings for ``volatile``.
+
+__char16_t, __char32_t
+--
+
+``__char16_t`` and ``__char32_t`` are alternate spellings for ``char16_t`` and
+``char32_t`` respectively, but are also available in C++ modes before C++11.
+
 ..
   FIXME: This should list all the keyword extensions
 
@@ -5319,17 +5431,6 @@ Examples are:
# 60 "" 2 // return to "main.c"
# 1 "/usr/ancient/header.h" 1 4 // Enter an implicit extern "C" header
 
-Extended Integer Types
-==
-
-Clang supports the C23 ``_BitInt(N)`` feature as an extension in older C modes
-and in C++. This type was previously implemented in Clang with the same
-semantics, but spelled ``_ExtInt(N)``. This spelling has been deprecated in
-favor of the standard type.
-
-Note: the ABI for ``_BitInt(N)`` is still in the process of being stabilized,
-so this type should not yet be used in interfaces that require ABI stability.
-
 Intrinsics Support within Constant Expressions
 ==
 

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


[clang] [clang][Sema] Refine unused-member-function diagnostic message for constructors (PR #84515)

2024-03-08 Thread Shafik Yaghmour via cfe-commits

shafik wrote:

Looks like the build failed b/c you did not run `git clang-format`

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


[clang] [Clang][Sema] Fix type of enumerators in incomplete enumerations (PR #84068)

2024-03-08 Thread via cfe-commits

Kupa-Martin wrote:

@shafik We dont have a dedicated cpp test for this. I can add one if you want, 
but clang/test/Sema/warn-compare-enum-types-mismatch.c runs clang both on C and 
C++ mode, so I didnt think it necessary.

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


[clang] [C++20][Coroutines] lambda-coroutine with promise_type ctor. (PR #84519)

2024-03-08 Thread Shafik Yaghmour via cfe-commits


@@ -596,8 +596,21 @@ VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
 
   // Add implicit object parameter.
   if (auto *MD = dyn_cast(FD)) {
-if (MD->isImplicitObjectMemberFunction() && !isLambdaCallOperator(MD)) {
-  ExprResult ThisExpr = ActOnCXXThis(Loc);
+if (MD->isImplicitObjectMemberFunction()) {
+  ExprResult ThisExpr{};
+
+  if (isLambdaCallOperator(MD) && !MD->isStatic()) {
+Qualifiers ThisQuals = MD->getMethodQualifiers();
+CXXRecordDecl *Record = MD->getParent();
+
+Sema::CXXThisScopeRAII ThisScope(*this, Record, ThisQuals,
+ Record != nullptr);

shafik wrote:

```suggestion
 /*Enabled=*/Record != nullptr);
```

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


[clang] [C++20][Coroutines] lambda-coroutine with promise_type ctor. (PR #84519)

2024-03-08 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik commented:

nitpick

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


[clang] [C++20][Coroutines] lambda-coroutine with promise_type ctor. (PR #84519)

2024-03-08 Thread Shafik Yaghmour via cfe-commits

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


[clang] [clang-tools-extra] [llvm] [llvm][Support] Add and use errnoAsErrorCode (PR #84423)

2024-03-08 Thread David Blaikie via cfe-commits

dwblaikie wrote:

Cool cool - thanks for the extra context!

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


[clang] [Clang] Update missing varargs arg extension warnings (PR #84520)

2024-03-08 Thread Shafik Yaghmour via cfe-commits

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


[clang] [Clang] Update missing varargs arg extension warnings (PR #84520)

2024-03-08 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik commented:

Just a nit here.

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


[clang] [Clang] Update missing varargs arg extension warnings (PR #84520)

2024-03-08 Thread Shafik Yaghmour via cfe-commits


@@ -993,11 +993,18 @@ MacroArgs *Preprocessor::ReadMacroCallArgumentList(Token 
&MacroName,
   // If the macro contains the comma pasting extension, the diagnostic
   // is suppressed; we know we'll get another diagnostic later.
   if (!MI->hasCommaPasting()) {
-// C++20 allows this construct, but standards before C++20 and all C
-// standards do not allow the construct (we allow it as an extension).
-Diag(Tok, getLangOpts().CPlusPlus20
-  ? diag::warn_cxx17_compat_missing_varargs_arg
-  : diag::ext_missing_varargs_arg);
+// C++20 and C23 allow this construct, but standards before that
+// do not (we allow it as an extension).

shafik wrote:

CC @AaronBallman should we add a standard quote like we normally do for C++? It 
looks like it should be 6.10.5 p12. It took me a but to remember in C they are 
referred to as *variable arguments* and not variadic like in C++. 

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


[clang] [Clang][Sema] Fix type of enumerators in incomplete enumerations (PR #84068)

2024-03-08 Thread Shafik Yaghmour via cfe-commits


@@ -6,7 +6,9 @@ typedef enum EnumA {
 } EnumA;
 
 enum EnumB {
-  B
+  B,

shafik wrote:

I think what I was asking, was do we have an equivalent C++ test that verifies 
in a `.cpp` file that we also do not obtain a diagnostic for this.

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


[clang] [Clang][Sema] Fix type of enumerators in incomplete enumerations (PR #84068)

2024-03-08 Thread Shafik Yaghmour via cfe-commits

shafik wrote:

> So I believe:
> 
> ```
> typedef enum EnumA {
>   A
> } EnumA;
> 
> enum EnumB {
>   B,
>   B1 = 1,
>   B2 = A == B1
> };
> ```
> 
> is not an enum compare warning in C++ because `B1` doesn't have an 
> enumeration type due to the enumeration not being fully-defined, and is not 
> an enum compare warning in C because `A` has type `int` (due to p15) and `B1` 
> has type `int` (due to p12).

Right, so do we have a test for C++ that verifies that.

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


[clang] [llvm] BPF address space insn (PR #84410)

2024-03-08 Thread Yingchi Long via cfe-commits

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


[clang] [llvm] BPF address space insn (PR #84410)

2024-03-08 Thread Yingchi Long via cfe-commits


@@ -0,0 +1,52 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --version 4
+; RUN: opt --bpf-check-and-opt-ir -S -mtriple=bpf-pc-linux < %s | FileCheck %s
+
+; Generated from the following C code:
+;
+;   extern int __uptr *magic1();
+;   extern int __uptr *magic2();
+;
+;   void test(long i) {
+; int __uptr *a;
+;
+; if (i > 42)
+;   a = magic1();
+; else
+;   a = magic2();
+; a[5] = 7;
+;   }
+;
+; Using the following command:
+;
+;   clang --target=bpf -O2 -S -emit-llvm -o t.ll t.c
+
+; Function Attrs: nounwind

inclyc wrote:

No, it do has 'nounwind' attr because it is attributed with `#0`, however, in 
our testing ir I see `#0` is omitted

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


[clang-tools-extra] [clang-tidy]avoid bugprone-unused-return-value false positive for assignment operator overloading (PR #84489)

2024-03-08 Thread Julian Schmidt via cfe-commits

5chmidti wrote:

*(Approval after fixes)

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


[clang-tools-extra] [clang-tidy]avoid bugprone-unused-return-value false positive for assignment operator overloading (PR #84489)

2024-03-08 Thread Julian Schmidt via cfe-commits


@@ -5,6 +5,8 @@ bugprone-unused-return-value
 
 Warns on unused function return values. The checked functions can be 
configured.
 
+Operator overloading with assignment semantics are ignored。

5chmidti wrote:

The dot at the end of this line is some character that is not the normal dot.

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


[clang-tools-extra] [clang-tidy]avoid bugprone-unused-return-value false positive for assignment operator overloading (PR #84489)

2024-03-08 Thread Julian Schmidt via cfe-commits


@@ -28,6 +30,11 @@ AST_MATCHER_P(FunctionDecl, isInstantiatedFrom, 
Matcher,
   return InnerMatcher.matches(InstantiatedFrom ? *InstantiatedFrom : Node,
   Finder, Builder);
 }
+
+AST_MATCHER_P(CXXMethodDecl, isOperatorOverloading,
+  llvm::SmallVector, kinds) {

5chmidti wrote:

`Kinds`

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


[clang-tools-extra] [clang-tidy]avoid bugprone-unused-return-value false positive for assignment operator overloading (PR #84489)

2024-03-08 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti approved this pull request.


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


[clang-tools-extra] [clang-tidy]avoid bugprone-unused-return-value false positive for assignment operator overloading (PR #84489)

2024-03-08 Thread Julian Schmidt via cfe-commits

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


[clang] [clang] Accept lambdas in C++03 as an extensions (PR #73376)

2024-03-08 Thread Nikolas Klauser via cfe-commits

https://github.com/philnik777 updated 
https://github.com/llvm/llvm-project/pull/73376

>From db504f5031b11ff7e28a346db829463fd6883d98 Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Sat, 25 Nov 2023 04:00:57 +0100
Subject: [PATCH] [clang] Accept lambdas in C++03 as an extensions

This is a fairly simple extension, but makes the life for people who
have to support C++03 a lot easier. As a nice bonus, this also improves
diagnostics, since lambdas are now properly recognized when parsing
C++03 code.
---
 clang/docs/LanguageExtensions.rst |  73 ++-
 .../clang/Basic/DiagnosticParseKinds.td   |   1 +
 clang/include/clang/Basic/Features.def|   1 +
 clang/lib/Parse/ParseExpr.cpp |   2 +-
 clang/lib/Parse/ParseExprCXX.cpp  |   9 +-
 clang/lib/Parse/ParseInit.cpp |   2 +-
 clang/lib/Sema/SemaDecl.cpp   |   2 +-
 clang/lib/Sema/SemaDeclCXX.cpp|   3 +-
 clang/test/Lexer/has_extension_cxx.cpp|   5 +
 .../OpenMP/declare_reduction_messages.cpp |  14 +--
 clang/test/OpenMP/openmp_check.cpp|   2 +-
 clang/test/Parser/cxx03-lambda-extension.cpp  |   5 +
 .../test/Parser/cxx0x-lambda-expressions.cpp  | 116 +++---
 clang/test/Parser/cxx2b-lambdas.cpp   |  43 +--
 .../Parser/objcxx-lambda-expressions-neg.mm   |   9 +-
 clang/test/ParserHLSL/group_shared.hlsl   |   4 +-
 clang/test/SemaCXX/cxx2a-template-lambdas.cpp |  26 ++--
 clang/test/SemaCXX/lambda-expressions.cpp |  63 ++
 .../SemaCXX/lambda-implicit-this-capture.cpp  |   1 +
 clang/test/SemaCXX/lambda-invalid-capture.cpp |   1 +
 clang/test/SemaCXX/new-delete.cpp |   7 +-
 21 files changed, 208 insertions(+), 181 deletions(-)
 create mode 100644 clang/test/Parser/cxx03-lambda-extension.cpp

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 06af93fd3c15ca8..1d7bbcc161b1844 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -1458,40 +1458,45 @@ More information could be found `here 

 Language Extensions Back-ported to Previous Standards
 =
 
-==  
= =
-FeatureFeature Test Macro   
Introduced In Backported To
-==  
= =
-variadic templates __cpp_variadic_templates C++11  
   C++03
-Alias templates__cpp_alias_templatesC++11  
   C++03
-Non-static data member initializers__cpp_nsdmi  C++11  
   C++03
-Range-based ``for`` loop   __cpp_range_based_forC++11  
   C++03
-RValue references  __cpp_rvalue_references  C++11  
   C++03
-Attributes __cpp_attributes C++11  
   C++03
-variable templates __cpp_variable_templates C++14  
   C++03
-Binary literals__cpp_binary_literalsC++14  
   C++03
-Relaxed constexpr  __cpp_constexpr  C++14  
   C++11
-``if constexpr``   __cpp_if_constexpr   C++17  
   C++11
-fold expressions   __cpp_fold_expressions   C++17  
   C++03
-Lambda capture of \*this by value  __cpp_capture_star_this  C++17  
   C++11
-Attributes on enums__cpp_enumerator_attributes  C++17  
   C++03
-Guaranteed copy elision__cpp_guaranteed_copy_elisionC++17  
   C++03
-Hexadecimal floating literals  __cpp_hex_float  C++17  
   C++03
-``inline`` variables   __cpp_inline_variables   C++17  
   C++03
-Attributes on namespaces   __cpp_namespace_attributes   C++17  
   C++11
-Structured bindings__cpp_structured_bindingsC++17  
   C++03
-template template arguments__cpp_template_template_args C++17  
   C++03
-``static operator[]``  __cpp_multidimensional_subscript C++20  
   C++03
-Designated initializers__cpp_designated_initializersC++20  
   C++03
-Conditional ``explicit``   __cpp_conditional_explicit   C++20  
   C++03
-``using enum`` __cpp_using_enum C++20  
   C++03
-``if consteval``   __cpp_if_consteval   C++23  
   C++20
-``static operator()``  __cpp_static_call_operator   C++23  
   C++03
-Attributes on Lambda-Expressions

[clang] [clang] Accept lambdas in C++03 as an extensions (PR #73376)

2024-03-08 Thread Nikolas Klauser via cfe-commits

https://github.com/philnik777 updated 
https://github.com/llvm/llvm-project/pull/73376

>From 73135ec6395a6d3a29725e58b30ecb42249695fe Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Sat, 25 Nov 2023 04:00:57 +0100
Subject: [PATCH] [clang] Accept lambdas in C++03 as an extensions

This is a fairly simple extension, but makes the life for people who
have to support C++03 a lot easier. As a nice bonus, this also improves
diagnostics, since lambdas are now properly recognized when parsing
C++03 code.
---
 clang/docs/LanguageExtensions.rst |  74 ++-
 .../clang/Basic/DiagnosticParseKinds.td   |   1 +
 clang/include/clang/Basic/Features.def|   1 +
 clang/lib/Parse/ParseExpr.cpp |   2 +-
 clang/lib/Parse/ParseExprCXX.cpp  |   9 +-
 clang/lib/Parse/ParseInit.cpp |   2 +-
 clang/lib/Sema/SemaDecl.cpp   |   2 +-
 clang/lib/Sema/SemaDeclCXX.cpp|   3 +-
 clang/test/Lexer/has_extension_cxx.cpp|   5 +
 .../OpenMP/declare_reduction_messages.cpp |  14 +--
 clang/test/OpenMP/openmp_check.cpp|   2 +-
 clang/test/Parser/cxx03-lambda-extension.cpp  |   5 +
 .../test/Parser/cxx0x-lambda-expressions.cpp  | 116 +++---
 clang/test/Parser/cxx2b-lambdas.cpp   |  43 +--
 .../Parser/objcxx-lambda-expressions-neg.mm   |   9 +-
 clang/test/ParserHLSL/group_shared.hlsl   |   4 +-
 clang/test/SemaCXX/cxx2a-template-lambdas.cpp |  26 ++--
 clang/test/SemaCXX/lambda-expressions.cpp |  63 ++
 .../SemaCXX/lambda-implicit-this-capture.cpp  |   1 +
 clang/test/SemaCXX/lambda-invalid-capture.cpp |   1 +
 clang/test/SemaCXX/new-delete.cpp |   7 +-
 21 files changed, 209 insertions(+), 181 deletions(-)
 create mode 100644 clang/test/Parser/cxx03-lambda-extension.cpp

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 06af93fd3c15ca8..c9fc01f9b074bd6 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -1458,40 +1458,46 @@ More information could be found `here 

 Language Extensions Back-ported to Previous Standards
 =
 
-==  
= =
-FeatureFeature Test Macro   
Introduced In Backported To
-==  
= =
-variadic templates __cpp_variadic_templates C++11  
   C++03
-Alias templates__cpp_alias_templatesC++11  
   C++03
-Non-static data member initializers__cpp_nsdmi  C++11  
   C++03
-Range-based ``for`` loop   __cpp_range_based_forC++11  
   C++03
-RValue references  __cpp_rvalue_references  C++11  
   C++03
-Attributes __cpp_attributes C++11  
   C++03
-variable templates __cpp_variable_templates C++14  
   C++03
-Binary literals__cpp_binary_literalsC++14  
   C++03
-Relaxed constexpr  __cpp_constexpr  C++14  
   C++11
-``if constexpr``   __cpp_if_constexpr   C++17  
   C++11
-fold expressions   __cpp_fold_expressions   C++17  
   C++03
-Lambda capture of \*this by value  __cpp_capture_star_this  C++17  
   C++11
-Attributes on enums__cpp_enumerator_attributes  C++17  
   C++03
-Guaranteed copy elision__cpp_guaranteed_copy_elisionC++17  
   C++03
-Hexadecimal floating literals  __cpp_hex_float  C++17  
   C++03
-``inline`` variables   __cpp_inline_variables   C++17  
   C++03
-Attributes on namespaces   __cpp_namespace_attributes   C++17  
   C++11
-Structured bindings__cpp_structured_bindingsC++17  
   C++03
-template template arguments__cpp_template_template_args C++17  
   C++03
-``static operator[]``  __cpp_multidimensional_subscript C++20  
   C++03
-Designated initializers__cpp_designated_initializersC++20  
   C++03
-Conditional ``explicit``   __cpp_conditional_explicit   C++20  
   C++03
-``using enum`` __cpp_using_enum C++20  
   C++03
-``if consteval``   __cpp_if_consteval   C++23  
   C++20
-``static operator()``  __cpp_static_call_operator   C++23  
   C++03
-Attributes on Lambda-Expressions

[clang] [clang] Accept lambdas in C++03 as an extensions (PR #73376)

2024-03-08 Thread Nikolas Klauser via cfe-commits

https://github.com/philnik777 updated 
https://github.com/llvm/llvm-project/pull/73376

>From 305599596dd5914747687af23a105d2968546ca1 Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Sat, 25 Nov 2023 04:00:57 +0100
Subject: [PATCH] [clang] Accept lambdas in C++03 as an extensions

This is a fairly simple extension, but makes the life for people who
have to support C++03 a lot easier. As a nice bonus, this also improves
diagnostics, since lambdas are now properly recognized when parsing
C++03 code.
---
 clang/docs/LanguageExtensions.rst |  62 +-
 .../clang/Basic/DiagnosticParseKinds.td   |   1 +
 clang/include/clang/Basic/Features.def|   1 +
 clang/lib/Parse/ParseExpr.cpp |   2 +-
 clang/lib/Parse/ParseExprCXX.cpp  |   9 +-
 clang/lib/Parse/ParseInit.cpp |   2 +-
 clang/lib/Sema/SemaDecl.cpp   |   2 +-
 clang/lib/Sema/SemaDeclCXX.cpp|   3 +-
 clang/test/Lexer/has_extension_cxx.cpp|   5 +
 .../OpenMP/declare_reduction_messages.cpp |  14 +--
 clang/test/OpenMP/openmp_check.cpp|   2 +-
 clang/test/Parser/cxx03-lambda-extension.cpp  |   5 +
 .../test/Parser/cxx0x-lambda-expressions.cpp  | 116 +++---
 clang/test/Parser/cxx2b-lambdas.cpp   |  43 +--
 .../Parser/objcxx-lambda-expressions-neg.mm   |   9 +-
 clang/test/ParserHLSL/group_shared.hlsl   |   4 +-
 clang/test/SemaCXX/cxx2a-template-lambdas.cpp |  26 ++--
 clang/test/SemaCXX/lambda-expressions.cpp |  63 ++
 .../SemaCXX/lambda-implicit-this-capture.cpp  |   1 +
 clang/test/SemaCXX/lambda-invalid-capture.cpp |   1 +
 clang/test/SemaCXX/new-delete.cpp |   7 +-
 21 files changed, 203 insertions(+), 175 deletions(-)
 create mode 100644 clang/test/Parser/cxx03-lambda-extension.cpp

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 06af93fd3c15ca8..b809b544434d540 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -1458,34 +1458,39 @@ More information could be found `here 

 Language Extensions Back-ported to Previous Standards
 =
 
-==  
= =
-FeatureFeature Test Macro   
Introduced In Backported To
-==  
= =
-variadic templates __cpp_variadic_templates C++11  
   C++03
-Alias templates__cpp_alias_templatesC++11  
   C++03
-Non-static data member initializers__cpp_nsdmi  C++11  
   C++03
-Range-based ``for`` loop   __cpp_range_based_forC++11  
   C++03
-RValue references  __cpp_rvalue_references  C++11  
   C++03
-Attributes __cpp_attributes C++11  
   C++03
-variable templates __cpp_variable_templates C++14  
   C++03
-Binary literals__cpp_binary_literalsC++14  
   C++03
-Relaxed constexpr  __cpp_constexpr  C++14  
   C++11
-``if constexpr``   __cpp_if_constexpr   C++17  
   C++11
-fold expressions   __cpp_fold_expressions   C++17  
   C++03
-Lambda capture of \*this by value  __cpp_capture_star_this  C++17  
   C++11
-Attributes on enums__cpp_enumerator_attributes  C++17  
   C++03
-Guaranteed copy elision__cpp_guaranteed_copy_elisionC++17  
   C++03
-Hexadecimal floating literals  __cpp_hex_float  C++17  
   C++03
-``inline`` variables   __cpp_inline_variables   C++17  
   C++03
-Attributes on namespaces   __cpp_namespace_attributes   C++17  
   C++11
-Structured bindings__cpp_structured_bindingsC++17  
   C++03
-template template arguments__cpp_template_template_args C++17  
   C++03
-``static operator[]``  __cpp_multidimensional_subscript C++20  
   C++03
-Designated initializers__cpp_designated_initializersC++20  
   C++03
-Conditional ``explicit``   __cpp_conditional_explicit   C++20  
   C++03
-``using enum`` __cpp_using_enum C++20  
   C++03
-``if consteval``   __cpp_if_consteval   C++23  
   C++20
-``static operator()``  __cpp_static_call_operator   C++23  
   C++03
+ 

[clang] [clang] Fix crash when declaring invalid lambda member (PR #74110)

2024-03-08 Thread Nikolas Klauser via cfe-commits

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


[clang] dc567a2 - [clang] Fix crash when declaring invalid lambda member (#74110)

2024-03-08 Thread via cfe-commits

Author: Nikolas Klauser
Date: 2024-03-09T01:18:17+01:00
New Revision: dc567a2ec61d07e89902f73c1bdd4106dc071f3f

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

LOG: [clang] Fix crash when declaring invalid lambda member (#74110)

In valid code, there should only be a very specific set of members in a
lambda definition. If the user tries to define something inside the
lambda class, this assumption is violated and causes an assertion error.
This can be fixed by checking whether the members are valid, and if not,
ignore that the class members are potentially unexpected.

I've come across this while working on implementing lambdas in C++03.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/AST/DeclCXX.cpp
clang/test/SemaCXX/lambda-expressions.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 690fc7ed271a3d..8935a610722a31 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -258,6 +258,9 @@ Bug Fixes in This Version
   operator.
   Fixes (#GH83267).
 
+- Fixes an assertion failure on invalid code when trying to define member
+  functions in lambdas.
+
 Bug Fixes to Compiler Builtins
 ^^
 
@@ -408,7 +411,7 @@ RISC-V Support
 CUDA/HIP Language Changes
 ^
 
-- PTX is no longer included by default when compiling for CUDA. Using 
+- PTX is no longer included by default when compiling for CUDA. Using
   ``--cuda-include-ptx=all`` will return the old behavior.
 
 CUDA Support

diff  --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index 1c3dcf63465c68..645ec2f7563bca 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -1567,10 +1567,9 @@ bool CXXRecordDecl::isGenericLambda() const {
 
 #ifndef NDEBUG
 static bool allLookupResultsAreTheSame(const DeclContext::lookup_result &R) {
-  for (auto *D : R)
-if (!declaresSameEntity(D, R.front()))
-  return false;
-  return true;
+  return llvm::all_of(R, [&](NamedDecl *D) {
+return D->isInvalidDecl() || declaresSameEntity(D, R.front());
+  });
 }
 #endif
 

diff  --git a/clang/test/SemaCXX/lambda-expressions.cpp 
b/clang/test/SemaCXX/lambda-expressions.cpp
index 0516a5da31ae9a..8907b08e1830e0 100644
--- a/clang/test/SemaCXX/lambda-expressions.cpp
+++ b/clang/test/SemaCXX/lambda-expressions.cpp
@@ -1,3 +1,4 @@
+// RUN: %clang_cc1 -std=c++11 -Wno-unused-value -fsyntax-only 
-verify=expected,expected-cxx14,cxx11 -fblocks %s
 // RUN: %clang_cc1 -std=c++14 -Wno-unused-value -fsyntax-only -verify 
-verify=expected-cxx14 -fblocks %s
 // RUN: %clang_cc1 -std=c++17 -Wno-unused-value -verify -ast-dump -fblocks %s 
| FileCheck %s
 
@@ -558,8 +559,8 @@ struct B {
   int x;
   A a = [&] { int y = x; };
   A b = [&] { [&] { [&] { int y = x; }; }; };
-  A d = [&](auto param) { int y = x; };
-  A e = [&](auto param) { [&] { [&](auto param2) { int y = x; }; }; };
+  A d = [&](auto param) { int y = x; }; // cxx11-error {{'auto' not allowed in 
lambda parameter}}
+  A e = [&](auto param) { [&] { [&](auto param2) { int y = x; }; }; }; // 
cxx11-error 2 {{'auto' not allowed in lambda parameter}}
 };
 
 B b;
@@ -589,6 +590,7 @@ struct S1 {
 void foo1() {
   auto s0 = S1{[name=]() {}}; // expected-error 2 {{expected expression}}
   auto s1 = S1{[name=name]() {}}; // expected-error {{use of undeclared 
identifier 'name'; did you mean 'name1'?}}
+  // cxx11-warning@-1 {{initialized lambda 
captures are a C++14 extension}}
 }
 }
 
@@ -604,7 +606,7 @@ namespace PR25627_dont_odr_use_local_consts {
 
 namespace ConversionOperatorDoesNotHaveDeducedReturnType {
   auto x = [](int){};
-  auto y = [](auto &v) -> void { v.n = 0; };
+  auto y = [](auto &v) -> void { v.n = 0; }; // cxx11-error {{'auto' not 
allowed in lambda parameter}} cxx11-note {{candidate function not viable}} 
cxx11-note {{conversion candidate}}
   using T = decltype(x);
   using U = decltype(y);
   using ExpectedTypeT = void (*)(int);
@@ -624,22 +626,22 @@ namespace ConversionOperatorDoesNotHaveDeducedReturnType {
 template
   friend constexpr U::operator ExpectedTypeU() const noexcept;
 #else
-friend auto T::operator()(int) const;
+friend auto T::operator()(int) const; // cxx11-error {{'auto' return 
without trailing return type; deduced return types are a C++14 extension}}
 friend T::operator ExpectedTypeT() const;
 
 template
-  friend void U::operator()(T&) const;
+  friend void U::operator()(T&) const; // cxx11-error {{friend declaration 
of 'operator()' does not match any declaration}}
 // FIXME: This should not match, as above.
 template
-  friend U::operator ExpectedTypeU() const;
+  friend U::operator ExpectedTypeU() const; // cxx11-err

[clang] [clang] Fix crash when declaring invalid lambda member (PR #74110)

2024-03-08 Thread Nikolas Klauser via cfe-commits

https://github.com/philnik777 updated 
https://github.com/llvm/llvm-project/pull/74110

>From 563f86bddc0ec59b63c6aeffee2342f027c09119 Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Fri, 1 Dec 2023 18:16:36 +0100
Subject: [PATCH 1/2] [clang] Fix crash when declaring invalid lambda member

---
 clang/lib/AST/DeclCXX.cpp |  7 +++
 clang/test/SemaCXX/lambda-expressions.cpp | 16 +---
 2 files changed, 12 insertions(+), 11 deletions(-)

diff --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index c944862fcefeee..e9e62fea9fb376 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -1526,10 +1526,9 @@ bool CXXRecordDecl::isGenericLambda() const {
 
 #ifndef NDEBUG
 static bool allLookupResultsAreTheSame(const DeclContext::lookup_result &R) {
-  for (auto *D : R)
-if (!declaresSameEntity(D, R.front()))
-  return false;
-  return true;
+  return llvm::all_of(R, [&](NamedDecl *D) {
+return D->isInvalidDecl() || declaresSameEntity(D, R.front());
+  });
 }
 #endif
 
diff --git a/clang/test/SemaCXX/lambda-expressions.cpp 
b/clang/test/SemaCXX/lambda-expressions.cpp
index 1797eef320b865..1921d02b1a9cf8 100644
--- a/clang/test/SemaCXX/lambda-expressions.cpp
+++ b/clang/test/SemaCXX/lambda-expressions.cpp
@@ -1,3 +1,4 @@
+// RUN: %clang_cc1 -std=c++11 -Wno-unused-value -fsyntax-only 
-verify=expected,expected-cxx14,cxx11 -fblocks %s
 // RUN: %clang_cc1 -std=c++14 -Wno-unused-value -fsyntax-only -verify 
-verify=expected-cxx14 -fblocks %s
 // RUN: %clang_cc1 -std=c++17 -Wno-unused-value -verify -ast-dump -fblocks %s 
| FileCheck %s
 
@@ -558,8 +559,8 @@ struct B {
   int x;
   A a = [&] { int y = x; };
   A b = [&] { [&] { [&] { int y = x; }; }; };
-  A d = [&](auto param) { int y = x; };
-  A e = [&](auto param) { [&] { [&](auto param2) { int y = x; }; }; };
+  A d = [&](auto param) { int y = x; }; // cxx11-error {{'auto' not allowed in 
lambda parameter}}
+  A e = [&](auto param) { [&] { [&](auto param2) { int y = x; }; }; }; // 
cxx11-error 2 {{'auto' not allowed in lambda parameter}}
 };
 
 B b;
@@ -589,6 +590,7 @@ struct S1 {
 void foo1() {
   auto s0 = S1{[name=]() {}}; // expected-error 2 {{expected expression}}
   auto s1 = S1{[name=name]() {}}; // expected-error {{use of undeclared 
identifier 'name'; did you mean 'name1'?}}
+  // cxx11-warning@-1 {{initialized lambda 
captures are a C++14 extension}}
 }
 }
 
@@ -604,7 +606,7 @@ namespace PR25627_dont_odr_use_local_consts {
 
 namespace ConversionOperatorDoesNotHaveDeducedReturnType {
   auto x = [](int){};
-  auto y = [](auto &v) -> void { v.n = 0; };
+  auto y = [](auto &v) -> void { v.n = 0; }; // cxx11-error {{'auto' not 
allowed in lambda parameter}} cxx11-note {{candidate function not viable}} 
cxx11-note {{conversion candidate}}
   using T = decltype(x);
   using U = decltype(y);
   using ExpectedTypeT = void (*)(int);
@@ -624,14 +626,14 @@ namespace ConversionOperatorDoesNotHaveDeducedReturnType {
 template
   friend constexpr U::operator ExpectedTypeU() const noexcept;
 #else
-friend auto T::operator()(int) const;
+friend auto T::operator()(int) const; // cxx11-error {{'auto' return 
without trailing return type; deduced return types are a C++14 extension}}
 friend T::operator ExpectedTypeT() const;
 
 template
-  friend void U::operator()(T&) const;
+  friend void U::operator()(T&) const; // cxx11-error {{friend declaration 
of 'operator()' does not match any declaration}}
 // FIXME: This should not match, as above.
 template
-  friend U::operator ExpectedTypeU() const;
+  friend U::operator ExpectedTypeU() const; // cxx11-error {{friend 
declaration of 'operator void (*)(type-parameter-0-0 &)' does not match any 
declaration}}
 #endif
 
   private:
@@ -639,7 +641,7 @@ namespace ConversionOperatorDoesNotHaveDeducedReturnType {
   };
 
   // Should be OK: lambda's call operator is a friend.
-  void use(X &x) { y(x); }
+  void use(X &x) { y(x); } // cxx11-error {{no matching function for call to 
object}}
 
   // This used to crash in return type deduction for the conversion opreator.
   struct A { int n; void f() { +[](decltype(n)) {}; } };

>From 5412ff972af6fdc6c83d9f0b835ff989252ff591 Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Thu, 7 Mar 2024 12:47:55 +0100
Subject: [PATCH 2/2] Address comments

---
 clang/docs/ReleaseNotes.rst   | 2 ++
 clang/test/SemaCXX/lambda-expressions.cpp | 2 +-
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0ce15169d49bcc..db4dcc3ce029fb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -617,6 +617,8 @@ Bug Fixes in This Version
 - Fix crash during code generation of C++ coroutine initial suspend when the 
return
   type of await_resume is not trivially destructible.
   Fixes (`#63803 `_)

[clang] [Clang] [Parser] Support [[omp::assume]] (PR #84582)

2024-03-08 Thread via cfe-commits

https://github.com/Sirraide updated 
https://github.com/llvm/llvm-project/pull/84582

>From d436f7fefb967f050220a8ede6d05c8e26f363b3 Mon Sep 17 00:00:00 2001
From: Sirraide 
Date: Fri, 8 Mar 2024 23:54:14 +0100
Subject: [PATCH 1/2] [Clang] [Parser] Support [[omp::assume]]

---
 clang/include/clang/Basic/Attr.td |  2 +-
 clang/lib/Basic/Attributes.cpp|  8 ++--
 clang/lib/Parse/ParseDeclCXX.cpp  |  4 +++-
 clang/test/Sema/attr-assume.c | 17 +
 4 files changed, 27 insertions(+), 4 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index fa191c7378dba4..c6877b61fa7f1e 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4144,7 +4144,7 @@ def OMPDeclareVariant : InheritableAttr {
 }
 
 def Assumption : InheritableAttr {
-  let Spellings = [Clang<"assume">];
+  let Spellings = [Clang<"assume">, CXX11<"omp", "assume">];
   let Subjects = SubjectList<[Function, ObjCMethod]>;
   let InheritEvenIfAlreadyPresent = 1;
   let Documentation = [AssumptionDocs];
diff --git a/clang/lib/Basic/Attributes.cpp b/clang/lib/Basic/Attributes.cpp
index 44a4f1890d39e1..867d241a2cf847 100644
--- a/clang/lib/Basic/Attributes.cpp
+++ b/clang/lib/Basic/Attributes.cpp
@@ -47,8 +47,12 @@ int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
   // attributes. We support those, but not through the typical attribute
   // machinery that goes through TableGen. We support this in all OpenMP modes
   // so long as double square brackets are enabled.
-  if (LangOpts.OpenMP && ScopeName == "omp")
-return (Name == "directive" || Name == "sequence") ? 1 : 0;
+  //
+  // Other OpenMP attributes (e.g. [[omp::assume]]) are handled via the
+  // regular attribute parsing machinery.
+  if (LangOpts.OpenMP && ScopeName == "omp" &&
+  (Name == "directive" || Name == "sequence"))
+return 1;
 
   int res = hasAttributeImpl(Syntax, Name, ScopeName, Target, LangOpts);
   if (res)
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 62632b2d79792e..64129d7eaface5 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -4579,7 +4579,9 @@ bool Parser::ParseCXX11AttributeArgs(
 return true;
   }
 
-  if (ScopeName && ScopeName->isStr("omp")) {
+  // [[omp::directive]] and [[omp::sequence]] need special handling.
+  if (ScopeName && ScopeName->isStr("omp") &&
+  (AttrName->isStr("directive") || AttrName->isStr("sequence"))) {
 Diag(AttrNameLoc, getLangOpts().OpenMP >= 51
   ? diag::warn_omp51_compat_attributes
   : diag::ext_omp_attributes);
diff --git a/clang/test/Sema/attr-assume.c b/clang/test/Sema/attr-assume.c
index 98deffa3a74609..3b7721647dee60 100644
--- a/clang/test/Sema/attr-assume.c
+++ b/clang/test/Sema/attr-assume.c
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -triple i386-apple-darwin9 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -fopenmp -DCXX -verify %s
 
+#ifndef CXX
 void f1(void) __attribute__((assume(3))); // expected-error {{expected string 
literal as argument of 'assume' attribute}}
 void f2(void) __attribute__((assume(int))); // expected-error {{expected 
string literal as argument of 'assume' attribute}}
 void f3(void) __attribute__((assume(for))); // expected-error {{expected 
string literal as argument of 'assume' attribute}}
@@ -12,3 +14,18 @@ void f9(void) __attribute__((assume("omp_no_openmp", 
"omp_no_openmp"))); // expe
 
 int g1 __attribute__((assume(0))); // expected-error {{expected string literal 
as argument of 'assume' attribute}}
 int g2 __attribute__((assume("omp_no_openmp"))); // expected-warning 
{{'assume' attribute only applies to functions and Objective-C methods}}
+
+#else
+[[omp::assume(3)]] void f1(); // expected-error {{expected string literal as 
argument of 'assume' attribute}}
+[[omp::assume(int)]] void f2(); // expected-error {{expected string literal as 
argument of 'assume' attribute}}
+[[omp::assume(for)]] void f3(); // expected-error {{expected string literal as 
argument of 'assume' attribute}}
+[[omp::assume("")]] void f4(); // expected-warning {{unknown assumption 
string ''; attribute is potentially ignored}}
+[[omp::assume("omp_no_openmp")]] void f5();
+[[omp::assume("omp_noopenmp")]] void f6(); // expected-warning {{unknown 
assumption string 'omp_noopenmp' may be misspelled; attribute is potentially 
ignored, did you mean 'omp_no_openmp'?}}
+[[omp::assume("omp_no_openmp_routine")]] void f7(); // expected-warning 
{{unknown assumption string 'omp_no_openmp_routine' may be misspelled; 
attribute is potentially ignored, did you mean 'omp_no_openmp_routines'?}}
+[[omp::assume("omp_no_openmp1")]] void f8(); // expected-warning {{unknown 
assumption string 'omp_no_openmp1' may be misspelled; attribute is potentially 
ignored, did you mean 'omp_no_openmp'?}}
+[[omp::assume("omp_no_openmp", "omp_no_openmp")]] void f9(); // expected-err

[clang] [Clang] [Parser] Support [[omp::assume]] (PR #84582)

2024-03-08 Thread via cfe-commits

Sirraide wrote:

Ok yeah, good, looks like that’s the right attribute to map `[[omp::assume]]` 
to.

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


[clang] [WebAssembly] Change the default linker for `wasm32-wasip2` (PR #84569)

2024-03-08 Thread Alex Crichton via cfe-commits

alexcrichton wrote:

> So the core module + metadata is kind of isomorphic with that 
> single-core-module-component?

Sort of and sort of not. At a high level you're correct, but at a technical 
level this isn't correct. The subtle differences are:

* Most wasm binaries today using WASI probably use `wasi_snapshot_preview1` 
imports. That means they need an "adapter" to switch to to WASIp2-based 
imports. That adapter is a core wasm which is currently baked into 
`wasm-component-ld` (see the adapters in [this 
folder](https://github.com/alexcrichton/wasm-component-ld/tree/main/src))
* Due to the way components and lifting and lowering works many imports need a 
"shim". For example in the component model when you "lower" a function from a 
component function to a core function you need to specify a linear memory. A 
linear memory isn't available until you instantiate the core module, but the 
core module needs the lowered imports to be instantiated. To break this cycle 
we introduce a shim wasm module which uses `call_indirect` through a table for 
its exports, so that's used to pass in as imports when instantiating the main 
module, and then after the main module is instantiated we instantiate another 
shim module that fills in the table.

Going from core module + metadata into a component is a pretty nontrivial 
operation, so the raw output of `wasm-ld` (module + metadata) isn't suitable as 
an intermediate artifact for components. 

> I was more asking about whether the file types is accepts are anything more 
> than object files and libraries. i.e. can you pass other core modules and 
> have wasm-component-ld build a component that contains more than one core 
> module?


Ah sory I misunderstood! Currently wasm-component-ld takes no other inputs and 
it assumes everything goes into `wasm-ld`. In the future for the dynamic 
linking case above it may start taking in `*.wasm` binaries compiled as shared 
libraries to bundle and/or refer to in the output component, but that's in the 
future. That means that at this time wasm-component-ld will always build a 
component with a single "main module", e.g. the one from `wasm-ld`.

> Also, can you say more about the metadata that is being using to drive 
> wasm-componenet-ld? If the core module is all based on canonical ABI what 
> extra metdata is needed/planned?

Certainly! The canonical ABI gives the ability to say that for any component 
model function type it corresponds to a particular core wasm function type. 
That operation is not reversible, though, you can't go from core wasm back to 
the component model function type. Thus the metadata carries along this 
information. That way the componentization process draws a mapping from 
component model import/export to core wasm import/export and then can 
synthesize the right type in the component binary format.

The short answer to your question, though, is `wasm-tools component wit 
./my-wit-files --wasm`. That output blob, which is itself a component but only 
with type information, is embedded in core wasm. Put another way we start with 
WIT files, then those are converted into their binary format as a component 
with only types, that gets fed through LLVM/wasm-ld, then on the other end we 
deserialize the component-with-type-information, turn it back into WIT, and 
then make the real component.

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


[clang] [Clang] [Parser] Support [[omp::assume]] (PR #84582)

2024-03-08 Thread Alexey Bataev via cfe-commits

alexey-bataev wrote:

> One more thing: this is just a different spelling for what was previously 
> already exposed as `__attribute__((assume))`; I’m not sure if/how familiar 
> you are with that one, but I hope its semantics align with what 
> `[[omp::assume]]` is supposed to do. I’m asking because I’m not terribly 
> familiar with OpenMP myself.

Some details about assume directive

https://www.openmp.org/wp-content/uploads/OpenMP-assume_Doerfert.pdf

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


[clang] [Clang] [Parser] Support [[omp::assume]] (PR #84582)

2024-03-08 Thread via cfe-commits

Sirraide wrote:

> Currently only for C++11 and higher

Ok, good; that’ll make this easier.

> https://www.openmp.org/wp-content/uploads/OpenMP-API-Specification-5-2.pdf, 
> pages 49-50

Thanks. At a glance, it looks like there are more things that also still need 
to be implemented in the frontend, but adding `[[omp::assume]]` will allow us 
to deprecate/remove the `__attribute__((assume))` spelling that’s causing 
problems for us at the moment, so that’s a more pressing concern right now.

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


[clang] [Clang] [Parser] Support [[omp::assume]] (PR #84582)

2024-03-08 Thread Alexey Bataev via cfe-commits

alexey-bataev wrote:

> @alexey-bataev I have a few more questions about `[[omp::assume]]`:
> 
> - Is this supported in C? Because the `[[]]` spelling is only officially 
> available in C23 and later (we *do* support it in earlier language modes, but 
> users will get a warning if `-pedantic` is passed)
> 
> - Is there any place where I can find some more documentation about this 
> attribute? I tried to search for it online, but I couldn’t find anything 
> about it.

https://www.openmp.org/wp-content/uploads/OpenMP-API-Specification-5-2.pdf, 
pages 49-50

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


[clang] [Clang] [Parser] Support [[omp::assume]] (PR #84582)

2024-03-08 Thread Alexey Bataev via cfe-commits

alexey-bataev wrote:

> @alexey-bataev I have a few more questions about `[[omp::assume]]`:
> 
> - Is this supported in C? Because the `[[]]` spelling is only officially 
> available in C23 and later (we *do* support it in earlier language modes, but 
> users will get a warning if `-pedantic` is passed)
> 
> - Is there any place where I can find some more documentation about this 
> attribute? I tried to search for it online, but I couldn’t find anything 
> about it.

Currently only for C++11 and higher

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


[clang] [Clang] [Parser] Support [[omp::assume]] (PR #84582)

2024-03-08 Thread via cfe-commits

Sirraide wrote:

One more thing: this is just a different spelling for what was previously 
already exposed as `__attribute__((assume))`; I’m not sure if/how familiar you 
are with that one, but I hope its semantics align with what `[[omp::assume]]` 
is supposed to do. I’m asking because I’m not terribly familiar with OpenMP 
myself.

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


[clang] [HLSL] Add diagnostic for enabling 16 bit types (PR #84537)

2024-03-08 Thread Joshua Batista via cfe-commits

https://github.com/bob80905 updated 
https://github.com/llvm/llvm-project/pull/84537

>From 55395c5c8a5b92e200aa2f1bf06774d20ac4afd9 Mon Sep 17 00:00:00 2001
From: Joshua Batista 
Date: Fri, 8 Mar 2024 11:03:37 -0800
Subject: [PATCH 1/3] add check for enable 16 bit types

---
 clang/include/clang/Basic/DiagnosticDriverKinds.td |  3 ++-
 clang/lib/Driver/ToolChains/HLSL.cpp   | 14 ++
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 1bc9885849d54bf..23009117af0f378 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -750,7 +750,8 @@ def err_drv_hlsl_unsupported_target : Error<
   "HLSL code generation is unsupported for target '%0'">;
 def err_drv_hlsl_bad_shader_required_in_target : Error<
   "%select{shader model|Vulkan environment|shader stage}0 is required as 
%select{OS|environment}1 in target '%2' for HLSL code generation">;
-
+def err_drv_hlsl_enable_16bit_types : Error<
+  "enable_16bit_types cannot be applied when shader model is <= 6.2 and hlsl 
version <= 2018. (SM: %0, HV: %1)">;
 def err_drv_hlsl_bad_shader_unsupported : Error<
   "%select{shader model|Vulkan environment|shader stage}0 '%1' in target '%2' 
is invalid for HLSL code generation">;
 def warn_drv_dxc_missing_dxv : Warning<"dxv not found. "
diff --git a/clang/lib/Driver/ToolChains/HLSL.cpp 
b/clang/lib/Driver/ToolChains/HLSL.cpp
index c6ad862b229420b..e30ae78ca6553cf 100644
--- a/clang/lib/Driver/ToolChains/HLSL.cpp
+++ b/clang/lib/Driver/ToolChains/HLSL.cpp
@@ -243,6 +243,20 @@ HLSLToolChain::TranslateArgs(const DerivedArgList &Args, 
StringRef BoundArch,
   // FIXME: add validation for enable_16bit_types should be after HLSL 2018 and
   // shader model 6.2.
   // See: https://github.com/llvm/llvm-project/issues/57876
+  if (DAL->hasArg(options::OPT_enable_16bit_types)) {
+llvm::opt::Arg *hvArg = DAL->getLastArg(options::OPT_dxc_hlsl_version);
+llvm::VersionTuple versionTuple = getTriple().getOSVersion();
+unsigned int major = versionTuple.getMajor();
+auto minor = versionTuple.getMinor();
+
+if (major < 6 || (major == 6 && minor.value() <= 2) ||
+strcmp(hvArg->getValue(), "2016") == 0 ||
+strcmp(hvArg->getValue(), "2017") == 0 ||
+strcmp(hvArg->getValue(), "2018") == 0) {
+  getDriver().Diag(diag::err_drv_hlsl_enable_16bit_types)
+  << versionTuple.getAsString() << hvArg->getValue();
+}
+  }
   return DAL;
 }
 

>From 8205c6894a4c1deeeb28c2520d16a56c3fcf21ea Mon Sep 17 00:00:00 2001
From: Joshua Batista 
Date: Fri, 8 Mar 2024 11:03:37 -0800
Subject: [PATCH 2/3] add check for enable 16 bit types

---
 clang/include/clang/Basic/DiagnosticDriverKinds.td |  3 ++-
 clang/lib/Driver/ToolChains/HLSL.cpp   | 14 ++
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 1bc9885849d54bf..23009117af0f378 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -750,7 +750,8 @@ def err_drv_hlsl_unsupported_target : Error<
   "HLSL code generation is unsupported for target '%0'">;
 def err_drv_hlsl_bad_shader_required_in_target : Error<
   "%select{shader model|Vulkan environment|shader stage}0 is required as 
%select{OS|environment}1 in target '%2' for HLSL code generation">;
-
+def err_drv_hlsl_enable_16bit_types : Error<
+  "enable_16bit_types cannot be applied when shader model is <= 6.2 and hlsl 
version <= 2018. (SM: %0, HV: %1)">;
 def err_drv_hlsl_bad_shader_unsupported : Error<
   "%select{shader model|Vulkan environment|shader stage}0 '%1' in target '%2' 
is invalid for HLSL code generation">;
 def warn_drv_dxc_missing_dxv : Warning<"dxv not found. "
diff --git a/clang/lib/Driver/ToolChains/HLSL.cpp 
b/clang/lib/Driver/ToolChains/HLSL.cpp
index c6ad862b229420b..e30ae78ca6553cf 100644
--- a/clang/lib/Driver/ToolChains/HLSL.cpp
+++ b/clang/lib/Driver/ToolChains/HLSL.cpp
@@ -243,6 +243,20 @@ HLSLToolChain::TranslateArgs(const DerivedArgList &Args, 
StringRef BoundArch,
   // FIXME: add validation for enable_16bit_types should be after HLSL 2018 and
   // shader model 6.2.
   // See: https://github.com/llvm/llvm-project/issues/57876
+  if (DAL->hasArg(options::OPT_enable_16bit_types)) {
+llvm::opt::Arg *hvArg = DAL->getLastArg(options::OPT_dxc_hlsl_version);
+llvm::VersionTuple versionTuple = getTriple().getOSVersion();
+unsigned int major = versionTuple.getMajor();
+auto minor = versionTuple.getMinor();
+
+if (major < 6 || (major == 6 && minor.value() <= 2) ||
+strcmp(hvArg->getValue(), "2016") == 0 ||
+strcmp(hvArg->getValue(), "2017") == 0 ||
+strcmp(hvArg->getValue(), "2018") == 0) {
+  getDriver().Diag(d

[clang] [clang-tools-extra] [llvm] [llvm][Support] Add and use errnoAsErrorCode (PR #84423)

2024-03-08 Thread Michael Spencer via cfe-commits

Bigcheese wrote:

The other cases of `std::system_category` were in `LLVM_ON_UNIX` (or similar) 
blocks that would only be used on systems where it's mostly fine to use either 
one, as most of the time you'll get an error that's in `std::errc`, and then 
there's no difference (or they just are never compared in general). The initial 
desire to do this came from spending 30m looking into which one to use on UNIX 
systems in general and wanting to avoid that in the future. The 
`JSONTransport.cpp` case was just more indication to me that the existing way 
was error prone.

In auditing all uses of `errno` I did find a few other places where the code 
isn't quite wrong, but it's not really using `llvm::Error` correctly. There's 
quite a few places where people use `llvm::inconvertibleErrorCode()` where they 
really shouldn't be. For example `llvm-exegesis` has a bunch of places where 
they call `strerror(errno)` to construct an `llvm::Error` that implicitly uses 
`llvm::inconvertibleErrorCode()` as the `std::error_code` value. Our existing 
documentation here is pretty nice for `Error` and `Expected` 
(https://llvm.org/docs/ProgrammersManual.html#error-handling), but it would be 
nice to better cover how `std::error_code` is supposed to be propagated, as it 
currently kind of implies they are going away, but they are always needed for 
OS errors. I'll try to get to this when I can find time.

As for test coverage, some of these have existing error tests, but for a lot of 
the rest it's either incredibly difficult or just not possible (without using 
`LD_PRELOAD` or something similar) to test. Given that, it's good to make 
handling them as easy to get correct as practicable.



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


[clang] [Clang] [Parser] Support [[omp::assume]] (PR #84582)

2024-03-08 Thread via cfe-commits

Sirraide wrote:

@alexey-bataev I have a few more questions about `[[omp::assume]]`:
- Is this supported in C? Because the `[[]]` spelling is only officially 
available in C23 and later (we *do* support it in earlier language modes, but 
users will get a warning if `-pedantic` is passed)
- Is there any place where I can find some more documentation about this 
attribute? I tried to search for it online, but I couldn’t find anything about 
it.

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


[clang] [Clang] [Parser] Support [[omp::assume]] (PR #84582)

2024-03-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-openmp

Author: None (Sirraide)


Changes

This pr implements the `[[omp::assume]]` spelling for the 
`__attribute__((assume))` attribute. It does not change anything about how that 
attribute is handled by the rest of Clang.

This pr is only *not* meant for figuring out what to do w/ the latter—I’ll be 
opening a separate pr that will update the documentation etc. to use 
`[[omp::assume]]`; we should have that discussion there; this pr is mostly 
meant to be self-contained (and also does not depend on or conflict with #81014).

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


4 Files Affected:

- (modified) clang/include/clang/Basic/Attr.td (+1-1) 
- (modified) clang/lib/Basic/Attributes.cpp (+6-2) 
- (modified) clang/lib/Parse/ParseDeclCXX.cpp (+3-1) 
- (modified) clang/test/Sema/attr-assume.c (+17) 


``diff
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index fa191c7378dba4..c6877b61fa7f1e 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4144,7 +4144,7 @@ def OMPDeclareVariant : InheritableAttr {
 }
 
 def Assumption : InheritableAttr {
-  let Spellings = [Clang<"assume">];
+  let Spellings = [Clang<"assume">, CXX11<"omp", "assume">];
   let Subjects = SubjectList<[Function, ObjCMethod]>;
   let InheritEvenIfAlreadyPresent = 1;
   let Documentation = [AssumptionDocs];
diff --git a/clang/lib/Basic/Attributes.cpp b/clang/lib/Basic/Attributes.cpp
index 44a4f1890d39e1..867d241a2cf847 100644
--- a/clang/lib/Basic/Attributes.cpp
+++ b/clang/lib/Basic/Attributes.cpp
@@ -47,8 +47,12 @@ int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
   // attributes. We support those, but not through the typical attribute
   // machinery that goes through TableGen. We support this in all OpenMP modes
   // so long as double square brackets are enabled.
-  if (LangOpts.OpenMP && ScopeName == "omp")
-return (Name == "directive" || Name == "sequence") ? 1 : 0;
+  //
+  // Other OpenMP attributes (e.g. [[omp::assume]]) are handled via the
+  // regular attribute parsing machinery.
+  if (LangOpts.OpenMP && ScopeName == "omp" &&
+  (Name == "directive" || Name == "sequence"))
+return 1;
 
   int res = hasAttributeImpl(Syntax, Name, ScopeName, Target, LangOpts);
   if (res)
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 62632b2d79792e..64129d7eaface5 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -4579,7 +4579,9 @@ bool Parser::ParseCXX11AttributeArgs(
 return true;
   }
 
-  if (ScopeName && ScopeName->isStr("omp")) {
+  // [[omp::directive]] and [[omp::sequence]] need special handling.
+  if (ScopeName && ScopeName->isStr("omp") &&
+  (AttrName->isStr("directive") || AttrName->isStr("sequence"))) {
 Diag(AttrNameLoc, getLangOpts().OpenMP >= 51
   ? diag::warn_omp51_compat_attributes
   : diag::ext_omp_attributes);
diff --git a/clang/test/Sema/attr-assume.c b/clang/test/Sema/attr-assume.c
index 98deffa3a74609..3b7721647dee60 100644
--- a/clang/test/Sema/attr-assume.c
+++ b/clang/test/Sema/attr-assume.c
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -triple i386-apple-darwin9 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -fopenmp -DCXX -verify %s
 
+#ifndef CXX
 void f1(void) __attribute__((assume(3))); // expected-error {{expected string 
literal as argument of 'assume' attribute}}
 void f2(void) __attribute__((assume(int))); // expected-error {{expected 
string literal as argument of 'assume' attribute}}
 void f3(void) __attribute__((assume(for))); // expected-error {{expected 
string literal as argument of 'assume' attribute}}
@@ -12,3 +14,18 @@ void f9(void) __attribute__((assume("omp_no_openmp", 
"omp_no_openmp"))); // expe
 
 int g1 __attribute__((assume(0))); // expected-error {{expected string literal 
as argument of 'assume' attribute}}
 int g2 __attribute__((assume("omp_no_openmp"))); // expected-warning 
{{'assume' attribute only applies to functions and Objective-C methods}}
+
+#else
+[[omp::assume(3)]] void f1(); // expected-error {{expected string literal as 
argument of 'assume' attribute}}
+[[omp::assume(int)]] void f2(); // expected-error {{expected string literal as 
argument of 'assume' attribute}}
+[[omp::assume(for)]] void f3(); // expected-error {{expected string literal as 
argument of 'assume' attribute}}
+[[omp::assume("")]] void f4(); // expected-warning {{unknown assumption 
string ''; attribute is potentially ignored}}
+[[omp::assume("omp_no_openmp")]] void f5();
+[[omp::assume("omp_noopenmp")]] void f6(); // expected-warning {{unknown 
assumption string 'omp_noopenmp' may be misspelled; attribute is potentially 
ignored, did you mean 'omp_no_openmp'?}}
+[[omp::assume("omp_no_openmp_routine")]] void f7(); // expected-warning 
{{unknown assumption string 'omp_no_openmp_routine' may

[clang] [Clang] [Parser] Support [[omp::assume]] (PR #84582)

2024-03-08 Thread via cfe-commits

https://github.com/Sirraide created 
https://github.com/llvm/llvm-project/pull/84582

This pr implements the `[[omp::assume]]` spelling for the 
`__attribute__((assume))` attribute. It does not change anything about how that 
attribute is handled by the rest of Clang.

This pr is only *not* meant for figuring out what to do w/ the latter—I’ll be 
opening a separate pr that will update the documentation etc. to use 
`[[omp::assume]]`; we should have that discussion there; this pr is mostly 
meant to be self-contained (and also does not depend on or conflict with 
#81014).

>From d436f7fefb967f050220a8ede6d05c8e26f363b3 Mon Sep 17 00:00:00 2001
From: Sirraide 
Date: Fri, 8 Mar 2024 23:54:14 +0100
Subject: [PATCH] [Clang] [Parser] Support [[omp::assume]]

---
 clang/include/clang/Basic/Attr.td |  2 +-
 clang/lib/Basic/Attributes.cpp|  8 ++--
 clang/lib/Parse/ParseDeclCXX.cpp  |  4 +++-
 clang/test/Sema/attr-assume.c | 17 +
 4 files changed, 27 insertions(+), 4 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index fa191c7378dba4..c6877b61fa7f1e 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4144,7 +4144,7 @@ def OMPDeclareVariant : InheritableAttr {
 }
 
 def Assumption : InheritableAttr {
-  let Spellings = [Clang<"assume">];
+  let Spellings = [Clang<"assume">, CXX11<"omp", "assume">];
   let Subjects = SubjectList<[Function, ObjCMethod]>;
   let InheritEvenIfAlreadyPresent = 1;
   let Documentation = [AssumptionDocs];
diff --git a/clang/lib/Basic/Attributes.cpp b/clang/lib/Basic/Attributes.cpp
index 44a4f1890d39e1..867d241a2cf847 100644
--- a/clang/lib/Basic/Attributes.cpp
+++ b/clang/lib/Basic/Attributes.cpp
@@ -47,8 +47,12 @@ int clang::hasAttribute(AttributeCommonInfo::Syntax Syntax,
   // attributes. We support those, but not through the typical attribute
   // machinery that goes through TableGen. We support this in all OpenMP modes
   // so long as double square brackets are enabled.
-  if (LangOpts.OpenMP && ScopeName == "omp")
-return (Name == "directive" || Name == "sequence") ? 1 : 0;
+  //
+  // Other OpenMP attributes (e.g. [[omp::assume]]) are handled via the
+  // regular attribute parsing machinery.
+  if (LangOpts.OpenMP && ScopeName == "omp" &&
+  (Name == "directive" || Name == "sequence"))
+return 1;
 
   int res = hasAttributeImpl(Syntax, Name, ScopeName, Target, LangOpts);
   if (res)
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 62632b2d79792e..64129d7eaface5 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -4579,7 +4579,9 @@ bool Parser::ParseCXX11AttributeArgs(
 return true;
   }
 
-  if (ScopeName && ScopeName->isStr("omp")) {
+  // [[omp::directive]] and [[omp::sequence]] need special handling.
+  if (ScopeName && ScopeName->isStr("omp") &&
+  (AttrName->isStr("directive") || AttrName->isStr("sequence"))) {
 Diag(AttrNameLoc, getLangOpts().OpenMP >= 51
   ? diag::warn_omp51_compat_attributes
   : diag::ext_omp_attributes);
diff --git a/clang/test/Sema/attr-assume.c b/clang/test/Sema/attr-assume.c
index 98deffa3a74609..3b7721647dee60 100644
--- a/clang/test/Sema/attr-assume.c
+++ b/clang/test/Sema/attr-assume.c
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -triple i386-apple-darwin9 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -fopenmp -DCXX -verify %s
 
+#ifndef CXX
 void f1(void) __attribute__((assume(3))); // expected-error {{expected string 
literal as argument of 'assume' attribute}}
 void f2(void) __attribute__((assume(int))); // expected-error {{expected 
string literal as argument of 'assume' attribute}}
 void f3(void) __attribute__((assume(for))); // expected-error {{expected 
string literal as argument of 'assume' attribute}}
@@ -12,3 +14,18 @@ void f9(void) __attribute__((assume("omp_no_openmp", 
"omp_no_openmp"))); // expe
 
 int g1 __attribute__((assume(0))); // expected-error {{expected string literal 
as argument of 'assume' attribute}}
 int g2 __attribute__((assume("omp_no_openmp"))); // expected-warning 
{{'assume' attribute only applies to functions and Objective-C methods}}
+
+#else
+[[omp::assume(3)]] void f1(); // expected-error {{expected string literal as 
argument of 'assume' attribute}}
+[[omp::assume(int)]] void f2(); // expected-error {{expected string literal as 
argument of 'assume' attribute}}
+[[omp::assume(for)]] void f3(); // expected-error {{expected string literal as 
argument of 'assume' attribute}}
+[[omp::assume("")]] void f4(); // expected-warning {{unknown assumption 
string ''; attribute is potentially ignored}}
+[[omp::assume("omp_no_openmp")]] void f5();
+[[omp::assume("omp_noopenmp")]] void f6(); // expected-warning {{unknown 
assumption string 'omp_noopenmp' may be misspelled; attribute is potentially 
ignored, did you mean 'omp_no_openmp'?}}
+[[omp:

[clang] [WebAssembly] Change the default linker for `wasm32-wasip2` (PR #84569)

2024-03-08 Thread Sam Clegg via cfe-commits

sbc100 wrote:

> Currently it accepts no extra inputs, but in the future I'd expect that it'll 
> grow an option or two of its own

I was more asking about whether the file types is accepts are anything more 
than object files and libraries.  i.e. can you pass other core modules and have 
wasm-component-ld build a component that contains more than one core module?

Also, can you say more about the metadata that is being using to drive 
wasm-componenet-ld?If the core module is all based on canonical ABI what 
extra metdata is needed/planned?

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


[clang] [HLSL] Add diagnostic for enabling 16 bit types (PR #84537)

2024-03-08 Thread Joshua Batista via cfe-commits


@@ -243,6 +243,20 @@ HLSLToolChain::TranslateArgs(const DerivedArgList &Args, 
StringRef BoundArch,
   // FIXME: add validation for enable_16bit_types should be after HLSL 2018 and

bob80905 wrote:

Yes, I'll remove the comment.

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


[clang] [WebAssembly] Change the default linker for `wasm32-wasip2` (PR #84569)

2024-03-08 Thread Sam Clegg via cfe-commits

sbc100 wrote:

I see, so `wasm-ld` builds "core module + metadata" and then 
`wasm-component-ld` takes that metadata and uses it to wrap the core module 
into a component (with exactly that one core module inside of it). 

So the core module + metadata is kind of isomorphic with that 
single-core-module-component?





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


[clang] [HLSL] Add diagnostic for enabling 16 bit types (PR #84537)

2024-03-08 Thread Damyan Pepper via cfe-commits


@@ -243,6 +243,20 @@ HLSLToolChain::TranslateArgs(const DerivedArgList &Args, 
StringRef BoundArch,
   // FIXME: add validation for enable_16bit_types should be after HLSL 2018 and

damyanp wrote:

Is this FIXME comment outdated by this PR?

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


[clang] [WebAssembly] Change the default linker for `wasm32-wasip2` (PR #84569)

2024-03-08 Thread Alex Crichton via cfe-commits

alexcrichton wrote:

Currently it accepts no extra inputs, but in the future I'd expect that it'll 
grow an option or two of its own. Currently it [hand-codes the list of options 
to forward to 
`wasm-ld`](https://github.com/alexcrichton/wasm-component-ld/blob/2f6106e395e2db99a8bb0524088d08bb6964997a/src/main.rs#L23-L53)
 which I'm sure will need updates over time, but that should be ok. And yes, 
the purpose of `wasm-component-ld` is twofold:

1. First it invokes `wasm-ld` internally, producing the core wasm that's 
expected today.
2. Next it invokes the "componentization process" which activates some Rust 
crates that converts this output core wasm module into a component.

In step (2) it's using component type information smuggled through LLVM/wasm-ld 
through custom sections to create the final output component.

> Do we expect clang users to be building compound components using a single 
> clang command?

If by compound you mean linking multiple components internally, then no. The 
intention is that `wasm32-wasip2` outputs a component but internally it's 
"just" a core wasm module. The next phase of composing components together 
we've got other tooling for, and that's intended to be outside the scope of 
individual language toolchains. (e.g. in theory composition works the same 
regardless of source language)

> Would it make more sense to have clang default to building core modules and 
> have the component creation be a higher level thing built on top clang 
> outputs?

That's actually what we currently have to day with converting `wasm32-wasip1` 
outputs into components. The purpose of `wasm32-wasip2`, however, is that core 
wasms are not natively usable as-is because WASI APIs are defined at the level 
of the component model, not core wasm. There is of course definitions for core 
wasm using the canonical ABI, but that's not the focus of WASI nowdays.

I do plan on having a flag (also answering the question about 
wasm-component-ld-specific-flags) to not emit a component and instead skip the 
componentization step. This step could also be done by using `-fuse-ld=wasm-ld` 
(or the equivalent thereof) to just switch the default linker back to `wasm-ld`.

> Regarding WebAssembly/wasi-sdk and WebAssembly/wasi-libc, is there any reason 
> why simple programs wouldn't be core modules? Won't most C/C++ programs still 
> be build-able as just core modules?

Yep, they'll all still be buildable as core modules (as that's the internals of 
a component anyway, a big thing produced by LLVM). With the p2 target though 
the thinking is that components are the default output, not core wasm modules.

---

Another future feature on the theoretical roadmap for wasm-component-ld is that 
Joel has componentize-py built on "dynamic linking" of a sort which gets 
`dlopen` working enough for Python to open its native extensions. This is all 
built on the Emscripten dynamic linking model and a component packages that all 
up into a single component where the dynamic libraries are statically known at 
build time. This is all wrapped up in `wasm-tools component link` and is 
something I'd like to also automatically bake in to `wasm-component-ld` so 
building that style of component is much easier.

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


[clang] [WebAssembly] Change the default linker for `wasm32-wasip2` (PR #84569)

2024-03-08 Thread Sam Clegg via cfe-commits

sbc100 wrote:

Regarding WebAssembly/wasi-sdk and WebAssembly/wasi-libc, is there any reason 
why simple programs wouldn't be core modules?   Won't most C/C++ programs still 
be build-able as just core modules?  

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


[clang] [WebAssembly] Change the default linker for `wasm32-wasip2` (PR #84569)

2024-03-08 Thread Sam Clegg via cfe-commits

https://github.com/sbc100 commented:

Does wasm-component-ld accept any other input types other than the ones that 
wasm-ld accepts?

Does wasm-component-ld call wasm-ld internally?

Do we expect clang users to be building compound components using a single 
clang command?  i.e. will they be somehow supplying input files that describe 
how the componend links?   Would it make more sense to have clang default to 
building core modules and have the component creation be a higher level thing 
built on top clang outputs?

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


[clang] [Clang][Sema] Fix type of enumerators in incomplete enumerations (PR #84068)

2024-03-08 Thread via cfe-commits


@@ -6,7 +6,9 @@ typedef enum EnumA {
 } EnumA;
 
 enum EnumB {
-  B
+  B,

Kupa-Martin wrote:

done

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


[clang] [Clang][Sema] Fix type of enumerators in incomplete enumerations (PR #84068)

2024-03-08 Thread via cfe-commits


@@ -264,11 +264,14 @@ namespace {
 }
 
 QualType Expr::getEnumCoercedType(const ASTContext &Ctx) const {
-  if (isa(this->getType()))
-return this->getType();
-  else if (const auto *ECD = this->getEnumConstantDecl())
-return Ctx.getTypeDeclType(cast(ECD->getDeclContext()));
-  return this->getType();
+  if (isa(getType())) {
+return getType();
+  } else if (const auto *ECD = getEnumConstantDecl()) {
+const auto *ED = cast(ECD->getDeclContext());
+if (ED->isCompleteDefinition())
+  return Ctx.getTypeDeclType(ED);
+  }

Kupa-Martin wrote:

done

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


[clang] [Clang][Sema] Fix type of enumerators in incomplete enumerations (PR #84068)

2024-03-08 Thread via cfe-commits

https://github.com/Kupa-Martin updated 
https://github.com/llvm/llvm-project/pull/84068

>From 4bbd5cf7eb1eeeaba8eed2ac4aba76cdbbcc671f Mon Sep 17 00:00:00 2001
From: 44-2-Kupa-Martin 
Date: Tue, 5 Mar 2024 17:21:02 -0300
Subject: [PATCH] [Clang][Sema] Fix type of enumerators in incomplete
 enumerations Enumerators dont have the type of their enumeration before the
 closing brace. In these cases Expr::getEnumCoercedType() incorrectly returned
 the enumeration type.

Introduced in PR #81418
---
 clang/lib/AST/Expr.cpp | 13 -
 clang/test/Sema/warn-compare-enum-types-mismatch.c |  9 -
 2 files changed, 16 insertions(+), 6 deletions(-)

diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index b4de2155adcebd..f5ad402e3bd73e 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -264,11 +264,14 @@ namespace {
 }
 
 QualType Expr::getEnumCoercedType(const ASTContext &Ctx) const {
-  if (isa(this->getType()))
-return this->getType();
-  else if (const auto *ECD = this->getEnumConstantDecl())
-return Ctx.getTypeDeclType(cast(ECD->getDeclContext()));
-  return this->getType();
+  if (isa(getType()))
+return getType();
+  if (const auto *ECD = getEnumConstantDecl()) {
+const auto *ED = cast(ECD->getDeclContext());
+if (ED->isCompleteDefinition())
+  return Ctx.getTypeDeclType(ED);
+  }
+  return getType();
 }
 
 SourceLocation Expr::getExprLoc() const {
diff --git a/clang/test/Sema/warn-compare-enum-types-mismatch.c 
b/clang/test/Sema/warn-compare-enum-types-mismatch.c
index 2b72aae16b977a..85d218e3213b2d 100644
--- a/clang/test/Sema/warn-compare-enum-types-mismatch.c
+++ b/clang/test/Sema/warn-compare-enum-types-mismatch.c
@@ -1,12 +1,19 @@
 // RUN: %clang_cc1 -x c -fsyntax-only -verify -Wenum-compare 
-Wno-unused-comparison %s
 // RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wenum-compare 
-Wno-unused-comparison %s
 
+// In C enumerators (i.e enumeration constants) have type int (until C23). In 
order to support diagnostics such as 
+// -Wenum-compare we pretend they have the type of their enumeration.
+
 typedef enum EnumA {
   A
 } EnumA;
 
 enum EnumB {
-  B
+  B,
+  B1 = 1,
+  // In C++ this comparison doesnt warn as enumerators dont have the type of 
their enumeration before the closing 
+  // brace. We mantain the same behavior in C.
+  B2 = A == B1
 };
 
 enum {

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


[clang] [Clang][Sema] Fix type of enumerators in incomplete enumerations (PR #84068)

2024-03-08 Thread via cfe-commits

Kupa-Martin wrote:

> not an enum compare warning in C++ because `B1` doesn't have an enumeration 
> type due to the enumeration not being fully-defined, and is not an enum 
> compare warning in C because `A` has type `int` (due to p15) and `B1` has 
> type `int` (due to p12).

Yes, you are correct.

> I think we play a bit fast-and-loose with the way we treat enum constants in 
> C in Clang, but that's outside of the scope of this patch.

There are enough differences between the C23 and C++ standards to produce 
different diagnostics. I've made a godbolt 
[snippet](https://godbolt.org/z/741W1356r) that tries to keep track of the type 
of different enumerators in C23 and C++; we warn when we shouldnt and we dont 
warn when we should. In any case, this patch didnt intend to cover C23.

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


[clang] [compiler-rt] [clang][UBSan] Add implicit conversion check for bitfields (PR #75481)

2024-03-08 Thread Richard Smith via cfe-commits

zygoloid wrote:

> I'm not opposed to the changes, though I do find it somewhat strange to add 
> them to UBSan given that they're not undefined behavior (even though there's 
> precedent).

This is adding checks to `-fsanitize=implicit-conversion`, which is not part of 
`-fsanitize=undefined`. It's sort of ambiguous whether UBSan means 
`-fsanitize=undefined` (that is, checks for UB that can be done without a big 
runtime), or whether it means any of the checks that the UBSan infrastructure 
and runtime power, but the established precedent is we also use the UBSan 
infrastructure to do non-UB data-loss checks like this, and this patch seems 
like a logical extension of the existing behavior.

I'd be happier if we drew a brighter distinction between the UB checks and the 
non-UB checks that our sanitizers perform. For example, perhaps the non-UB 
sanitizers shouldn't be listed in 
https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html but in a different 
page, or perhaps at least in a different section from the other checks. But I 
think that's independent of this PR, and in the context of this PR, I don't 
think we should be re-litigating whether this kind of 
data-loss-through-conversion check is in scope.

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


  1   2   3   4   5   >