[clang] [llvm] Conditionalize use of POSIX features missing on WASI/WebAssembly (PR #92677)

2024-05-18 Thread via cfe-commits

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


[clang] HLSL availability diagnostics design doc (PR #92207)

2024-05-18 Thread Helena Kotas via cfe-commits

https://github.com/hekota updated 
https://github.com/llvm/llvm-project/pull/92207

>From 3df0ba0fd2171a0115427bc6ba5e3f8e84831747 Mon Sep 17 00:00:00 2001
From: Helena Kotas 
Date: Tue, 14 May 2024 19:06:59 -0700
Subject: [PATCH 1/9] HLSL Availability Diagnostics Design Document - initial
 commit

---
 clang/docs/HLSL/AvailabilityDiagnostics.rst | 50 +
 clang/docs/HLSL/HLSLDocs.rst|  1 +
 2 files changed, 51 insertions(+)
 create mode 100644 clang/docs/HLSL/AvailabilityDiagnostics.rst

diff --git a/clang/docs/HLSL/AvailabilityDiagnostics.rst 
b/clang/docs/HLSL/AvailabilityDiagnostics.rst
new file mode 100644
index 0..218047495e6b9
--- /dev/null
+++ b/clang/docs/HLSL/AvailabilityDiagnostics.rst
@@ -0,0 +1,50 @@
+=
+HLSL Availability Diagnostics
+=
+
+.. contents::
+   :local:
+
+Introduction
+
+
+HLSL availability diagnostics emits errors or warning when unavailable shader 
APIs are used. Unavailable shader APIs are APIs that are exposed in HLSL code 
but are not available in the target shader stage or shader model version.
+
+There are three modes of HLSL availability diagnostic:
+1. **Default mode** - compiler emits an error when an unavailable shader API 
is found in a code that is reachable from the shader entry point function or 
from an exported library function (when compiling a shader library)
+2. **Relaxed mode** - same as default mode except the compiler emits a 
warning. This mode is enabled by ``-Wno-error=hlsl-availability``.
+3. **Strict mode** - compiler emits an error when when an unavailable API is 
found in parsed code regardless of whether it can be reached from the shader 
entry point or exported functions, or not. This mode is enabled by 
``-fhlsl-strict-diagnostics``.
+
+Implementation Details
+==
+
+Environment Parameter
+-
+
+In order to encode API availability based on the shader model version and 
shader model stage a new ``environment`` parameter was added to the existing 
Clang ``availability`` attribute. 
+
+The values allowed for this parameter are a subset of values allowed as the 
``llvm::Triple`` environment component. If the environment parameters is 
present, the declared availability attribute applies only to targets with the 
same platform and environment.
+
+Default and Relaxed Diagnostic Modes
+
+
+This mode is implemeted in ``DiagnoseHLSLAvailability`` class in 
``SemaHLSL.cpp`` and it is invoked after the whole translation unit is parsed 
(from ``Sema::ActOnEndOfTranslationUnit``). The implementation iterates over 
all shader entry points and exported library functions in the translation unit 
and performs an AST traversal of each function body.
+
+When a reference to another function is found and it has a body, the AST of 
the referenced function is also scanned. This chain of AST traversals will 
reach all of the code that is reachable from the initial shader entry point or 
exported library function.
+
+All shader APIs have an availability attribute that specifies the shader model 
version (and environment, if applicable) when this API was first 
introduced.When a reference to a function without a definition is found and it 
has an availability attribute, the version of the attribute is checked against 
the target shader model version and shader stage (if shader stage context is 
known), and an appropriate diagnostic is generated as needed.
+
+All shader entry functions have ``HLSLShaderAttr`` attribute that specifies 
what type of shader this function represents. However, for exported library 
functions the target shader stage is unknown, so in this case the HLSL API 
availability will be only checked against the shader model version.
+
+A list of functions that were already scanned is kept in order to avoid 
duplicate scans and diagnostics (see 
``DiagnoseHLSLAvailability::ScannedDecls``). It might happen that a shader 
library has multiple shader entry points for different shader stages that all 
call into the same shared function. It is therefore important to record not 
just that a function has been scanned, but also in which shader stage context. 
This is done by using ``llvm::DenseMap`` that maps ``FunctionDecl *`` to a 
``unsigned`` bitmap that represents a set of shader stages (or environments) 
the function has been scanned for. The ``N``'th bit in the set is set if the 
function has been scanned in shader environment whose 
``HLSLShaderAttr::ShaderType`` integer value equals ``N``.
+
+The emitted diagnostic messages belong to ``hlsl-availability`` diagnostic 
group and are reported as errors by default. With 
``-Wno-error=hlsl-availability`` flang they become warning, making it relaxed 
HLSL diagnostics mode.
+
+Strict Diagnostic Mode
+--
+
+When strict HLSL availability diagnostic mode is enabled the compiler must 
report all HLSL API availab

[clang] [llvm] Conditionalize use of POSIX features missing on WASI/WebAssembly (PR #92677)

2024-05-18 Thread via cfe-commits

https://github.com/whitequark updated 
https://github.com/llvm/llvm-project/pull/92677

>From 0a86da8896ccc32c82e045828e28d2f39de991f9 Mon Sep 17 00:00:00 2001
From: Catherine 
Date: Sun, 19 May 2024 04:41:27 +
Subject: [PATCH] Conditionalize use of POSIX features missing on
 WASI/WebAssembly.

This patch is the first in a series that makes it possible to build
LLVM, Clang, and LLD for WASI/WebAssembly. This patch does not introduce
conditionals of the form `defined(__wasi__)` or `defined(__wasm__)`;
instead it detects these APIs like any other platform features. While
some features are never present in WASI and the feature check is
functionally identical to a platform check, some may be conditionally
present if emulation is turned on, e.g. `getpid`.

The complete list of feature tests introduced is:
* `HAVE_ALARM`: WebAssembly does not support delivery of asynchronous
  signals.
* `HAVE_GETHOSTNAME`: WASI does not provide `gethostname`.
* `HAVE_GETPID`: WASI does not have process IDs. However, it ships
  with a polyfill (`-D_WASI_EMULATED_GETPID`). The final behavior is
  the same either way.
* `HAVE_FCHOWN`: WASI likely will never support UNIX ownership model.
* `HAVE_FLOCK`: WASI likely will never support POSIX advisory locking.
* `HAVE_PWD_H`: WASI likely will never support UNIX password databases.
* `HAVE_RAISE`: WASI does not support delivery of asynchronous signals.
  However, it ships with a polyfill (`-D_WASI_EMULATED_SIGNAL`).
  This polyfill implements `raise` but not `sigaction` (only `signal`)
  and as a result it is not currently useful for LLVM. If `sigaction`
  is implemented in wasi-libc then `raise(SIGABRT);` would be able to
  invoke the handler.
* `HAVE_SETJMP`: WebAssembly implements SjLj using exception handling.
  Exception handling has not been stabilized in Wasm yet. In addition,
  it significantly increases deployment complexity. Building with
  `-mllvm -wasm-enable-sjlj` enables the use of SjLj.
* `HAVE_SOCKET`: WASIp1 does not provide the Berkeley socket API.
  WASIp2 does provide it. It will likely remain desirable to target
  WASIp1 for a long time.
* `HAVE_SYS_WAIT_H`: WASI does not have subprocess management.
* `HAVE_UMASK`: WASI likely will never support UNIX permission model,
  but `umask` might eventually be added in a polyfill.

Of these, only `HAVE_FLOCK` requires a custom compile test:

#include 
struct flock lk;
int main(void) { return 0; }
---
 clang/lib/Driver/Driver.cpp   |  6 ++--
 llvm/cmake/config-ix.cmake| 16 +
 llvm/include/llvm/Config/config.h.cmake   | 33 +++
 .../Interpreter/ExternalFunctions.cpp |  6 
 llvm/lib/Support/CrashRecoveryContext.cpp | 15 -
 llvm/lib/Support/LockFileManager.cpp  |  2 +-
 llvm/lib/Support/Unix/Path.inc| 30 +
 llvm/lib/Support/Unix/Process.inc |  4 +++
 llvm/lib/Support/Unix/Unix.h  |  3 ++
 llvm/lib/Support/Unix/Watchdog.inc|  4 +--
 llvm/lib/Support/raw_socket_stream.cpp|  4 +++
 11 files changed, 116 insertions(+), 7 deletions(-)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 2868b4f2b02e9..f8b7c76e6439d 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -99,8 +99,8 @@
 #include 
 #include 
 #include 
-#if LLVM_ON_UNIX
-#include  // getpid
+#if HAVE_GETPID
+#include 
 #endif
 
 using namespace clang::driver;
@@ -1577,7 +1577,7 @@ bool Driver::getCrashDiagnosticFile(StringRef 
ReproCrashFilename,
 CrashDiagDir = "/";
   path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
   int PID =
-#if LLVM_ON_UNIX
+#if HAVE_GETPID
   getpid();
 #else
   0;
diff --git a/llvm/cmake/config-ix.cmake b/llvm/cmake/config-ix.cmake
index bf1b110245bb2..81209d664bf11 100644
--- a/llvm/cmake/config-ix.cmake
+++ b/llvm/cmake/config-ix.cmake
@@ -49,6 +49,7 @@ check_include_file(malloc/malloc.h HAVE_MALLOC_MALLOC_H)
 if( NOT PURE_WINDOWS )
   check_include_file(pthread.h HAVE_PTHREAD_H)
 endif()
+check_include_file(pwd.h HAVE_PWD_H)
 check_include_file(signal.h HAVE_SIGNAL_H)
 check_include_file(sys/ioctl.h HAVE_SYS_IOCTL_H)
 check_include_file(sys/mman.h HAVE_SYS_MMAN_H)
@@ -57,6 +58,7 @@ check_include_file(sys/resource.h HAVE_SYS_RESOURCE_H)
 check_include_file(sys/stat.h HAVE_SYS_STAT_H)
 check_include_file(sys/time.h HAVE_SYS_TIME_H)
 check_include_file(sys/types.h HAVE_SYS_TYPES_H)
+check_include_file(sys/wait.h HAVE_SYS_WAIT_H)
 check_include_file(sysexits.h HAVE_SYSEXITS_H)
 check_include_file(termios.h HAVE_TERMIOS_H)
 check_include_file(unistd.h HAVE_UNISTD_H)
@@ -276,11 +278,15 @@ check_symbol_exists(__deregister_frame 
"${CMAKE_CURRENT_LIST_DIR}/unwind.h" HAVE
 check_symbol_exists(__unw_add_dynamic_fde "${CMAKE_CURRENT_LIST_DIR}/unwind.h" 
HAVE_UNW_ADD_DYNAMIC_FDE)
 
 check_symbol_exists(_Unwind_Backtrace "unwind.h" HAVE__UNWIND_BACKTRACE)
+check_symbol_exists(alarm unistd.h H

[clang] [llvm] Conditionalize use of POSIX features missing on WASI/WebAssembly (PR #92677)

2024-05-18 Thread via cfe-commits

https://github.com/whitequark updated 
https://github.com/llvm/llvm-project/pull/92677

>From 4110cfe39bde72f0a0c1ed3187811db5548ecd99 Mon Sep 17 00:00:00 2001
From: Catherine 
Date: Sun, 19 May 2024 04:41:27 +
Subject: [PATCH] Conditionalize use of POSIX features missing on
 WASI/WebAssembly.

This patch is the first in a series that makes it possible to build
LLVM, Clang, and LLD for WASI/WebAssembly. This patch does not introduce
conditionals of the form `defined(__wasi__)` or `defined(__wasm__)`;
instead it detects these APIs like any other platform features. While
some features are never present in WASI and the feature check is
functionally identical to a platform check, some may be conditionally
present if emulation is turned on, e.g. `getpid`.

The complete list of feature tests introduced is:
* `HAVE_ALARM`: WebAssembly does not support delivery of asynchronous
  signals.
* `HAVE_GETHOSTNAME`: WASI does not provide `gethostname`.
* `HAVE_GETPID`: WASI does not have process IDs. However, it ships
  with a polyfill (`-D_WASI_EMULATED_GETPID`). The final behavior is
  the same either way.
* `HAVE_FCHOWN`: WASI likely will never support UNIX ownership model.
* `HAVE_FLOCK`: WASI likely will never support POSIX advisory locking.
* `HAVE_PWD_H`: WASI likely will never support UNIX password databases.
* `HAVE_RAISE`: WASI does not support delivery of asynchronous signals.
  However, it ships with a polyfill (`-D_WASI_EMULATED_SIGNAL`).
  This polyfill implements `raise` but not `sigaction` (only `signal`)
  and as a result it is not currently useful for LLVM. If `sigaction`
  is implemented in wasi-libc then `raise(SIGABRT);` would be able to
  invoke the handler.
* `HAVE_SETJMP`: WebAssembly implements SjLj using exception handling.
  Exception handling has not been stabilized in Wasm yet. In addition,
  it significantly increases deployment complexity. Building with
  `-mllvm -wasm-enable-sjlj` enables the use of SjLj.
* `HAVE_SOCKET`: WASIp1 does not provide the Berkeley socket API.
  WASIp2 does provide it. It will likely remain desirable to target
  WASIp1 for a long time.
* `HAVE_SYS_WAIT_H`: WASI does not have subprocess management.
* `HAVE_UMASK`: WASI likely will never support UNIX permission model,
  but `umask` might eventually be added in a polyfill.

Of these, only `HAVE_FLOCK` requires a custom compile test:

#include 
struct flock lk;
int main(void) { return 0; }
---
 clang/lib/Driver/Driver.cpp   |  6 ++--
 llvm/cmake/config-ix.cmake| 16 +
 llvm/include/llvm/Config/config.h.cmake   | 33 +++
 .../Interpreter/ExternalFunctions.cpp |  6 
 llvm/lib/Support/CrashRecoveryContext.cpp | 15 -
 llvm/lib/Support/LockFileManager.cpp  |  2 +-
 llvm/lib/Support/Unix/Path.inc| 30 +
 llvm/lib/Support/Unix/Process.inc |  4 +++
 llvm/lib/Support/Unix/Unix.h  |  5 ++-
 llvm/lib/Support/Unix/Watchdog.inc|  4 +--
 llvm/lib/Support/raw_socket_stream.cpp|  4 +++
 11 files changed, 117 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 2868b4f2b02e9..f8b7c76e6439d 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -99,8 +99,8 @@
 #include 
 #include 
 #include 
-#if LLVM_ON_UNIX
-#include  // getpid
+#if HAVE_GETPID
+#include 
 #endif
 
 using namespace clang::driver;
@@ -1577,7 +1577,7 @@ bool Driver::getCrashDiagnosticFile(StringRef 
ReproCrashFilename,
 CrashDiagDir = "/";
   path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
   int PID =
-#if LLVM_ON_UNIX
+#if HAVE_GETPID
   getpid();
 #else
   0;
diff --git a/llvm/cmake/config-ix.cmake b/llvm/cmake/config-ix.cmake
index bf1b110245bb2..81209d664bf11 100644
--- a/llvm/cmake/config-ix.cmake
+++ b/llvm/cmake/config-ix.cmake
@@ -49,6 +49,7 @@ check_include_file(malloc/malloc.h HAVE_MALLOC_MALLOC_H)
 if( NOT PURE_WINDOWS )
   check_include_file(pthread.h HAVE_PTHREAD_H)
 endif()
+check_include_file(pwd.h HAVE_PWD_H)
 check_include_file(signal.h HAVE_SIGNAL_H)
 check_include_file(sys/ioctl.h HAVE_SYS_IOCTL_H)
 check_include_file(sys/mman.h HAVE_SYS_MMAN_H)
@@ -57,6 +58,7 @@ check_include_file(sys/resource.h HAVE_SYS_RESOURCE_H)
 check_include_file(sys/stat.h HAVE_SYS_STAT_H)
 check_include_file(sys/time.h HAVE_SYS_TIME_H)
 check_include_file(sys/types.h HAVE_SYS_TYPES_H)
+check_include_file(sys/wait.h HAVE_SYS_WAIT_H)
 check_include_file(sysexits.h HAVE_SYSEXITS_H)
 check_include_file(termios.h HAVE_TERMIOS_H)
 check_include_file(unistd.h HAVE_UNISTD_H)
@@ -276,11 +278,15 @@ check_symbol_exists(__deregister_frame 
"${CMAKE_CURRENT_LIST_DIR}/unwind.h" HAVE
 check_symbol_exists(__unw_add_dynamic_fde "${CMAKE_CURRENT_LIST_DIR}/unwind.h" 
HAVE_UNW_ADD_DYNAMIC_FDE)
 
 check_symbol_exists(_Unwind_Backtrace "unwind.h" HAVE__UNWIND_BACKTRACE)
+check_symbol_exists(alarm unistd.h 

[clang] [llvm] Conditionalize use of POSIX features missing on WASI/WebAssembly (PR #92677)

2024-05-18 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 577785c5ca78a9714584b5c99ec085f8aea0a5c0 
289750cd78979e4811d6fd943c0a6c3b5bd3b5dd -- clang/lib/Driver/Driver.cpp 
llvm/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp 
llvm/lib/Support/CrashRecoveryContext.cpp llvm/lib/Support/LockFileManager.cpp 
llvm/lib/Support/Unix/Path.inc llvm/lib/Support/Unix/Process.inc 
llvm/lib/Support/Unix/Unix.h llvm/lib/Support/Unix/Watchdog.inc 
llvm/lib/Support/raw_socket_stream.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/lib/Support/Unix/Unix.h b/llvm/lib/Support/Unix/Unix.h
index b6988b3483..d96096d102 100644
--- a/llvm/lib/Support/Unix/Unix.h
+++ b/llvm/lib/Support/Unix/Unix.h
@@ -32,7 +32,7 @@
 #include 
 
 #ifdef HAVE_SYS_WAIT_H
-# include 
+#include 
 #endif
 
 #ifdef HAVE_UNISTD_H

``




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


[clang] [llvm] Conditionalize use of POSIX features missing on WASI/WebAssembly (PR #92677)

2024-05-18 Thread via cfe-commits

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


[clang] [llvm] Conditionalize use of POSIX features missing on WASI/WebAssembly (PR #92677)

2024-05-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Catherine (whitequark)


Changes

This patch is the first in a series that makes it possible to build LLVM, 
Clang, and LLD for WASI/WebAssembly. This patch does not introduce conditionals 
of the form `defined(__wasi__)` or `defined(__wasm__)`; instead it detects 
these APIs like any other platform features. While some features are never 
present in WASI and the feature check is functionally identical to a platform 
check, some may be conditionally present if emulation is turned on, e.g. 
`getpid`.

The complete list of feature tests introduced is:
* `HAVE_ALARM`: WebAssembly does not support delivery of asynchronous signals.
* `HAVE_GETHOSTNAME`: WASI does not provide `gethostname`.
* `HAVE_GETPID`: WASI does not have process IDs. However, it ships with a 
polyfill (`-D_WASI_EMULATED_GETPID`). The final behavior is the same either way.
* `HAVE_FCHOWN`: WASI likely will never support UNIX ownership model.
* `HAVE_PWD_H`: WASI likely will never support UNIX password databases.
* `HAVE_RAISE`: WASI does not support delivey of asynchronous signals. However, 
it ships with a polyfill (`-D_WASI_EMULATED_SIGNAL`). This polyfill implements 
`raise` but not `sigaction` (only `signal`) and as a result it is not currently 
useful for LLVM. If `sigaction` is implemented in wasi-libc then 
`raise(SIGABRT);` would be able to invoke the handler.
* `HAVE_SETJMP`: WebAssembly implements SjLj using exception handling. 
Exception handling has not been stabilized in Wasm yet. In addition, it 
significantly increases deployment complexity. Building with `-mllvm 
-wasm-enable-sjlj` enables the use of SjLj.
* `HAVE_SOCKET`: WASIp1 does not provide the Berkeley socket API. WASIp2 does 
provide it. It will likely remain desirable to target WASIp1 for a long time.
* `HAVE_SYS_WAIT_H`: WASI does not have subprocess management.
* `HAVE_UMASK`: WASI likely will never support UNIX permission model, but 
`umask` might eventually be added in a polyfill.

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


11 Files Affected:

- (modified) clang/lib/Driver/Driver.cpp (+3-3) 
- (modified) llvm/cmake/config-ix.cmake (+15) 
- (modified) llvm/include/llvm/Config/config.h.cmake (+33) 
- (modified) llvm/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp (+6) 
- (modified) llvm/lib/Support/CrashRecoveryContext.cpp (+14-1) 
- (modified) llvm/lib/Support/LockFileManager.cpp (+1-1) 
- (modified) llvm/lib/Support/Unix/Path.inc (+30) 
- (modified) llvm/lib/Support/Unix/Process.inc (+4) 
- (modified) llvm/lib/Support/Unix/Unix.h (+4-1) 
- (modified) llvm/lib/Support/Unix/Watchdog.inc (+2-2) 
- (modified) llvm/lib/Support/raw_socket_stream.cpp (+4) 


``diff
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 2868b4f2b02e9..f8b7c76e6439d 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -99,8 +99,8 @@
 #include 
 #include 
 #include 
-#if LLVM_ON_UNIX
-#include  // getpid
+#if HAVE_GETPID
+#include 
 #endif
 
 using namespace clang::driver;
@@ -1577,7 +1577,7 @@ bool Driver::getCrashDiagnosticFile(StringRef 
ReproCrashFilename,
 CrashDiagDir = "/";
   path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
   int PID =
-#if LLVM_ON_UNIX
+#if HAVE_GETPID
   getpid();
 #else
   0;
diff --git a/llvm/cmake/config-ix.cmake b/llvm/cmake/config-ix.cmake
index bf1b110245bb2..a1a76bb6241db 100644
--- a/llvm/cmake/config-ix.cmake
+++ b/llvm/cmake/config-ix.cmake
@@ -49,6 +49,7 @@ check_include_file(malloc/malloc.h HAVE_MALLOC_MALLOC_H)
 if( NOT PURE_WINDOWS )
   check_include_file(pthread.h HAVE_PTHREAD_H)
 endif()
+check_include_file(pwd.h HAVE_PWD_H)
 check_include_file(signal.h HAVE_SIGNAL_H)
 check_include_file(sys/ioctl.h HAVE_SYS_IOCTL_H)
 check_include_file(sys/mman.h HAVE_SYS_MMAN_H)
@@ -57,6 +58,7 @@ check_include_file(sys/resource.h HAVE_SYS_RESOURCE_H)
 check_include_file(sys/stat.h HAVE_SYS_STAT_H)
 check_include_file(sys/time.h HAVE_SYS_TIME_H)
 check_include_file(sys/types.h HAVE_SYS_TYPES_H)
+check_include_file(sys/wait.h HAVE_SYS_WAIT_H)
 check_include_file(sysexits.h HAVE_SYSEXITS_H)
 check_include_file(termios.h HAVE_TERMIOS_H)
 check_include_file(unistd.h HAVE_UNISTD_H)
@@ -276,11 +278,15 @@ check_symbol_exists(__deregister_frame 
"${CMAKE_CURRENT_LIST_DIR}/unwind.h" HAVE
 check_symbol_exists(__unw_add_dynamic_fde "${CMAKE_CURRENT_LIST_DIR}/unwind.h" 
HAVE_UNW_ADD_DYNAMIC_FDE)
 
 check_symbol_exists(_Unwind_Backtrace "unwind.h" HAVE__UNWIND_BACKTRACE)
+check_symbol_exists(alarm unistd.h HAVE_ALARM)
+check_symbol_exists(gethostname unistd.h HAVE_GETHOSTNAME)
 check_symbol_exists(getpagesize unistd.h HAVE_GETPAGESIZE)
+check_symbol_exists(getpid unistd.h HAVE_GETPID)
 check_symbol_exists(sysconf unistd.h HAVE_SYSCONF)
 check_symbol_exists(getrusage sys/resource.h HAVE_GETRUSAGE)
 check_symbol_exists(setrlimit sys/resource.h HAVE_SETRLIMIT)
 check_symbol_exists(isatty unistd.h HAVE_ISATTY)
+c

[clang] [llvm] Conditionalize use of POSIX features missing on WASI/WebAssembly (PR #92677)

2024-05-18 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-llvm-support

@llvm/pr-subscribers-clang-driver

Author: Catherine (whitequark)


Changes

This patch is the first in a series that makes it possible to build LLVM, 
Clang, and LLD for WASI/WebAssembly. This patch does not introduce conditionals 
of the form `defined(__wasi__)` or `defined(__wasm__)`; instead it detects 
these APIs like any other platform features. While some features are never 
present in WASI and the feature check is functionally identical to a platform 
check, some may be conditionally present if emulation is turned on, e.g. 
`getpid`.

The complete list of feature tests introduced is:
* `HAVE_ALARM`: WebAssembly does not support delivery of asynchronous signals.
* `HAVE_GETHOSTNAME`: WASI does not provide `gethostname`.
* `HAVE_GETPID`: WASI does not have process IDs. However, it ships with a 
polyfill (`-D_WASI_EMULATED_GETPID`). The final behavior is the same either way.
* `HAVE_FCHOWN`: WASI likely will never support UNIX ownership model.
* `HAVE_PWD_H`: WASI likely will never support UNIX password databases.
* `HAVE_RAISE`: WASI does not support delivey of asynchronous signals. However, 
it ships with a polyfill (`-D_WASI_EMULATED_SIGNAL`). This polyfill implements 
`raise` but not `sigaction` (only `signal`) and as a result it is not currently 
useful for LLVM. If `sigaction` is implemented in wasi-libc then 
`raise(SIGABRT);` would be able to invoke the handler.
* `HAVE_SETJMP`: WebAssembly implements SjLj using exception handling. 
Exception handling has not been stabilized in Wasm yet. In addition, it 
significantly increases deployment complexity. Building with `-mllvm 
-wasm-enable-sjlj` enables the use of SjLj.
* `HAVE_SOCKET`: WASIp1 does not provide the Berkeley socket API. WASIp2 does 
provide it. It will likely remain desirable to target WASIp1 for a long time.
* `HAVE_SYS_WAIT_H`: WASI does not have subprocess management.
* `HAVE_UMASK`: WASI likely will never support UNIX permission model, but 
`umask` might eventually be added in a polyfill.

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


11 Files Affected:

- (modified) clang/lib/Driver/Driver.cpp (+3-3) 
- (modified) llvm/cmake/config-ix.cmake (+15) 
- (modified) llvm/include/llvm/Config/config.h.cmake (+33) 
- (modified) llvm/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp (+6) 
- (modified) llvm/lib/Support/CrashRecoveryContext.cpp (+14-1) 
- (modified) llvm/lib/Support/LockFileManager.cpp (+1-1) 
- (modified) llvm/lib/Support/Unix/Path.inc (+30) 
- (modified) llvm/lib/Support/Unix/Process.inc (+4) 
- (modified) llvm/lib/Support/Unix/Unix.h (+4-1) 
- (modified) llvm/lib/Support/Unix/Watchdog.inc (+2-2) 
- (modified) llvm/lib/Support/raw_socket_stream.cpp (+4) 


``diff
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 2868b4f2b02e9..f8b7c76e6439d 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -99,8 +99,8 @@
 #include 
 #include 
 #include 
-#if LLVM_ON_UNIX
-#include  // getpid
+#if HAVE_GETPID
+#include 
 #endif
 
 using namespace clang::driver;
@@ -1577,7 +1577,7 @@ bool Driver::getCrashDiagnosticFile(StringRef 
ReproCrashFilename,
 CrashDiagDir = "/";
   path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
   int PID =
-#if LLVM_ON_UNIX
+#if HAVE_GETPID
   getpid();
 #else
   0;
diff --git a/llvm/cmake/config-ix.cmake b/llvm/cmake/config-ix.cmake
index bf1b110245bb2..a1a76bb6241db 100644
--- a/llvm/cmake/config-ix.cmake
+++ b/llvm/cmake/config-ix.cmake
@@ -49,6 +49,7 @@ check_include_file(malloc/malloc.h HAVE_MALLOC_MALLOC_H)
 if( NOT PURE_WINDOWS )
   check_include_file(pthread.h HAVE_PTHREAD_H)
 endif()
+check_include_file(pwd.h HAVE_PWD_H)
 check_include_file(signal.h HAVE_SIGNAL_H)
 check_include_file(sys/ioctl.h HAVE_SYS_IOCTL_H)
 check_include_file(sys/mman.h HAVE_SYS_MMAN_H)
@@ -57,6 +58,7 @@ check_include_file(sys/resource.h HAVE_SYS_RESOURCE_H)
 check_include_file(sys/stat.h HAVE_SYS_STAT_H)
 check_include_file(sys/time.h HAVE_SYS_TIME_H)
 check_include_file(sys/types.h HAVE_SYS_TYPES_H)
+check_include_file(sys/wait.h HAVE_SYS_WAIT_H)
 check_include_file(sysexits.h HAVE_SYSEXITS_H)
 check_include_file(termios.h HAVE_TERMIOS_H)
 check_include_file(unistd.h HAVE_UNISTD_H)
@@ -276,11 +278,15 @@ check_symbol_exists(__deregister_frame 
"${CMAKE_CURRENT_LIST_DIR}/unwind.h" HAVE
 check_symbol_exists(__unw_add_dynamic_fde "${CMAKE_CURRENT_LIST_DIR}/unwind.h" 
HAVE_UNW_ADD_DYNAMIC_FDE)
 
 check_symbol_exists(_Unwind_Backtrace "unwind.h" HAVE__UNWIND_BACKTRACE)
+check_symbol_exists(alarm unistd.h HAVE_ALARM)
+check_symbol_exists(gethostname unistd.h HAVE_GETHOSTNAME)
 check_symbol_exists(getpagesize unistd.h HAVE_GETPAGESIZE)
+check_symbol_exists(getpid unistd.h HAVE_GETPID)
 check_symbol_exists(sysconf unistd.h HAVE_SYSCONF)
 check_symbol_exists(getrusage sys/resource.h HAVE_GETRUSAGE)
 check_symbol_exists(setrlimit sys/resource.h HAVE_SETRLIMIT)
 check_symb

[clang] [llvm] Conditionalize use of POSIX features missing on WASI/WebAssembly (PR #92677)

2024-05-18 Thread via cfe-commits

https://github.com/whitequark created 
https://github.com/llvm/llvm-project/pull/92677

This patch is the first in a series that makes it possible to build LLVM, 
Clang, and LLD for WASI/WebAssembly. This patch does not introduce conditionals 
of the form `defined(__wasi__)` or `defined(__wasm__)`; instead it detects 
these APIs like any other platform features. While some features are never 
present in WASI and the feature check is functionally identical to a platform 
check, some may be conditionally present if emulation is turned on, e.g. 
`getpid`.

The complete list of feature tests introduced is:
* `HAVE_ALARM`: WebAssembly does not support delivery of asynchronous signals.
* `HAVE_GETHOSTNAME`: WASI does not provide `gethostname`.
* `HAVE_GETPID`: WASI does not have process IDs. However, it ships with a 
polyfill (`-D_WASI_EMULATED_GETPID`). The final behavior is the same either way.
* `HAVE_FCHOWN`: WASI likely will never support UNIX ownership model.
* `HAVE_PWD_H`: WASI likely will never support UNIX password databases.
* `HAVE_RAISE`: WASI does not support delivey of asynchronous signals. However, 
it ships with a polyfill (`-D_WASI_EMULATED_SIGNAL`). This polyfill implements 
`raise` but not `sigaction` (only `signal`) and as a result it is not currently 
useful for LLVM. If `sigaction` is implemented in wasi-libc then 
`raise(SIGABRT);` would be able to invoke the handler.
* `HAVE_SETJMP`: WebAssembly implements SjLj using exception handling. 
Exception handling has not been stabilized in Wasm yet. In addition, it 
significantly increases deployment complexity. Building with `-mllvm 
-wasm-enable-sjlj` enables the use of SjLj.
* `HAVE_SOCKET`: WASIp1 does not provide the Berkeley socket API. WASIp2 does 
provide it. It will likely remain desirable to target WASIp1 for a long time.
* `HAVE_SYS_WAIT_H`: WASI does not have subprocess management.
* `HAVE_UMASK`: WASI likely will never support UNIX permission model, but 
`umask` might eventually be added in a polyfill.

>From 289750cd78979e4811d6fd943c0a6c3b5bd3b5dd Mon Sep 17 00:00:00 2001
From: Catherine 
Date: Sun, 19 May 2024 04:41:27 +
Subject: [PATCH] Conditionalize use of POSIX features missing on
 WASI/WebAssembly.

This patch is the first in a series that makes it possible to build
LLVM, Clang, and LLD for WASI/WebAssembly. This patch does not introduce
conditionals of the form `defined(__wasi__)` or `defined(__wasm__)`;
instead it detects these APIs like any other platform features. While
some features are never present in WASI and the feature check is
functionally identical to a platform check, some may be conditionally
present if emulation is turned on, e.g. `getpid`.

The complete list of feature tests introduced is:
* `HAVE_ALARM`: WebAssembly does not support delivery of asynchronous
  signals.
* `HAVE_GETHOSTNAME`: WASI does not provide `gethostname`.
* `HAVE_GETPID`: WASI does not have process IDs. However, it ships
  with a polyfill (`-D_WASI_EMULATED_GETPID`). The final behavior is
  the same either way.
* `HAVE_FCHOWN`: WASI likely will never support UNIX ownership model.
* `HAVE_PWD_H`: WASI likely will never support UNIX password databases.
* `HAVE_RAISE`: WASI does not support delivey of asynchronous signals.
  However, it ships with a polyfill (`-D_WASI_EMULATED_SIGNAL`).
  This polyfill implements `raise` but not `sigaction` (only `signal`)
  and as a result it is not currently useful for LLVM. If `sigaction`
  is implemented in wasi-libc then `raise(SIGABRT);` would be able to
  invoke the handler.
* `HAVE_SETJMP`: WebAssembly implements SjLj using exception handling.
  Exception handling has not been stabilized in Wasm yet. In addition,
  it significantly increases deployment complexity. Building with
  `-mllvm -wasm-enable-sjlj` enables the use of SjLj.
* `HAVE_SOCKET`: WASIp1 does not provide the Berkeley socket API.
  WASIp2 does provide it. It will likely remain desirable to target
  WASIp1 for a long time.
* `HAVE_SYS_WAIT_H`: WASI does not have subprocess management.
* `HAVE_UMASK`: WASI likely will never support UNIX permission model,
  but `umask` might eventually be added in a polyfill.
---
 clang/lib/Driver/Driver.cpp   |  6 ++--
 llvm/cmake/config-ix.cmake| 15 +
 llvm/include/llvm/Config/config.h.cmake   | 33 +++
 .../Interpreter/ExternalFunctions.cpp |  6 
 llvm/lib/Support/CrashRecoveryContext.cpp | 15 -
 llvm/lib/Support/LockFileManager.cpp  |  2 +-
 llvm/lib/Support/Unix/Path.inc| 30 +
 llvm/lib/Support/Unix/Process.inc |  4 +++
 llvm/lib/Support/Unix/Unix.h  |  5 ++-
 llvm/lib/Support/Unix/Watchdog.inc|  4 +--
 llvm/lib/Support/raw_socket_stream.cpp|  4 +++
 11 files changed, 116 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 2868b4f2b02e9..f8b7c76e6439d 100644
--- a/c

[clang] [llvm] [C++23] [CLANG] Adding C++23 constexpr math functions: fmin, fmax and frexp. (PR #88978)

2024-05-18 Thread Hubert Tong via cfe-commits


@@ -3452,9 +3452,10 @@ def Fmod : FPMathTemplate, LibBuiltin<"math.h"> {
 
 def Frexp : FPMathTemplate, LibBuiltin<"math.h"> {
   let Spellings = ["frexp"];
-  let Attributes = [NoThrow];
+  let Attributes = [NoThrow, Constexpr];

hubert-reinterpretcast wrote:

The `Constexpr` here makes the non-`__builtin_`-prefixed version of the 
function `constexpr` under all language levels.
I checked the code: The `OnlyBuiltinPrefixedAliasIsConstexpr` flag can _add_ 
`constexpr`-ness; it does not _restrict_ it.

For reference:
https://github.com/llvm/llvm-project/blob/702198fc9ac5dba392f9d9ba7c56467996343c0a/clang/utils/TableGen/ClangBuiltinsEmitter.cpp#L225-L226

We may need a new builtin attribute that expresses `constexpr` for the 
non-prefixed functions only for C++23 and up (but we might end up with 
C++26-and-up, etc. in the future). However, it seems making the non-prefixed 
functions actually non-`constexpr` (as opposed to simply failing to evaluate) 
is only a QoI concern (see 
https://github.com/llvm/llvm-project/pull/88978#issuecomment-2119080104 for 
more context).

@philnik777, thoughts?

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


[clang] [llvm] [C++23] [CLANG] Adding C++23 constexpr math functions: fmin, fmax and frexp. (PR #88978)

2024-05-18 Thread Hubert Tong via cfe-commits

hubert-reinterpretcast wrote:

> Some more thought is needed on how to handle the non-`__builtin_`-prefixed 
> cases under non-C++23-or-higher language modes. The specific implications of 
> those functions being non-`constexpr` under said modes (as required, for C++, 
> by https://wg21.link/constexpr.functions) may determine the solution to apply 
> in this PR.

It seems that Clang _does_ care whether or not a function is `constexpr` 
(outside of an actual attempt to evaluate it during constant evaluation) when 
it is trying to diagnose the pre-C++23 IFNDR situation of a `constexpr` 
function that never produces a constant expression: 
https://godbolt.org/z/hnfqrrrdM

```cpp
extern "C" double fmin(double, double); // expected-note {{declared here}}
constexpr double contrived() { return fmin(0., 0.); }
// expected-error@-1 {{constexpr function never produces a constant expression}}
// expected-note@-2 {{non-constexpr function 'fmin' cannot be used in a 
constant expression}}
```

Aside: Clang checks the arguments before the function declaration.


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


[clang] [llvm] [DebugInfo][BPF] Add 'btf:type_tag' annotation in DWARF (PR #91423)

2024-05-18 Thread via cfe-commits

https://github.com/yonghong-song approved this pull request.


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


[clang] [llvm] [DebugInfo][BPF] Add 'btf:type_tag' annotation in DWARF (PR #91423)

2024-05-18 Thread via cfe-commits

yonghong-song wrote:

> Test "buildkite/github-pull-requests " failed and I don't know what is the 
> reason. I think it is worthwhile to rerun the test to ensure all tests passed.
> CI failure seems to be a fluke as it is reported for DataFlowSanitizer-x86_64 
> :: release_shadow_space.c which is completely unrelated, also CI for 91424 
> passed (91424 adds one commit to the bpf backend on top of this revision).
> […](#)

Right, I am aware of this. I just want to have test status 'green' :-)

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


[clang] [llvm] [BPF] Fix linking issues in static map initializers (PR #91310)

2024-05-18 Thread via cfe-commits


@@ -1950,8 +1950,22 @@ ConstantLValueEmitter::tryEmitBase(const 
APValue::LValueBase &base) {
 if (D->hasAttr())
   return CGM.GetWeakRefReference(D).getPointer();
 
-if (auto FD = dyn_cast(D))
-  return CGM.GetAddrOfFunction(FD);
+if (auto FD = dyn_cast(D)) {
+  auto *C = CGM.GetAddrOfFunction(FD);
+
+  // we don't normally emit debug info for extern fns referenced via
+  // variable initialisers; BPF needs it since it generates BTF from
+  // debug info and bpftool demands BTF for every symbol linked
+  if (CGM.getTarget().getTriple().isBPF() && FD->getStorageClass() == 
SC_Extern) {

yonghong-song wrote:

Thanks @mejedi I think we do not need to worry about cases where external 
functions are in the code but removed by optimizer later as this should not 
that frequent. Your patch looks good to me, which follows what we did for 
VarDecl so adding FunctionDecl is a natural addition. BPF side of the change 
looks good to me too. @efriedma-quic could you take a look as well?

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


[clang] [OpenCL] Fix an infinite loop in builidng AddrSpaceQualType (PR #92612)

2024-05-18 Thread Changpeng Fang via cfe-commits


@@ -0,0 +1,25 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 4
+//RUN: %clang_cc1 %s -emit-llvm -O1 -o - | FileCheck %s

changpeng wrote:

add "triple spir", same as other tests in the same directory

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


[clang] [OpenCL] Fix an infinite loop in builidng AddrSpaceQualType (PR #92612)

2024-05-18 Thread Changpeng Fang via cfe-commits

https://github.com/changpeng updated 
https://github.com/llvm/llvm-project/pull/92612

>From 2468a85a47499d90a99610846c632332eb7307b8 Mon Sep 17 00:00:00 2001
From: Changpeng Fang 
Date: Fri, 17 May 2024 15:13:07 -0700
Subject: [PATCH 1/3] [OpenCL] Fix an infinite loop in builidng
 AddrSpaceQualType

 In building AddrSpaceQualType 
(https://github.com/llvm/llvm-project/pull/90048),
there is a bug in removeAddrSpaceQualType() for arrays. Arrays are weird because
qualifiers on the element type also count as qualifiers on the type, so
getSingleStepDesugaredType() can't remove the sugar on arrays. This results
in an infinite loop in removeAddrSpaceQualType. To fix the issue,
we use ASTContext::getUnqualifiedArrayType, which strips the qualifier off
the element type, then reconstruct the array type.
---
 clang/lib/CodeGen/CGExprAgg.cpp   |  3 ++-
 .../array-type-infinite-loop.clcpp| 25 +++
 2 files changed, 27 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGenOpenCLCXX/array-type-infinite-loop.clcpp

diff --git a/clang/lib/CodeGen/CGExprAgg.cpp b/clang/lib/CodeGen/CGExprAgg.cpp
index 6172eb9cdc1bb..53ce133e8cbc6 100644
--- a/clang/lib/CodeGen/CGExprAgg.cpp
+++ b/clang/lib/CodeGen/CGExprAgg.cpp
@@ -537,8 +537,9 @@ void AggExprEmitter::EmitArrayInit(Address DestPtr, 
llvm::ArrayType *AType,
   elementType.isTriviallyCopyableType(CGF.getContext())) {
 CodeGen::CodeGenModule &CGM = CGF.CGM;
 ConstantEmitter Emitter(CGF);
+Qualifiers Quals;
 QualType GVArrayQTy = CGM.getContext().getAddrSpaceQualType(
-CGM.getContext().removeAddrSpaceQualType(ArrayQTy),
+CGM.getContext().getUnqualifiedArrayType(ArrayQTy, Quals),
 CGM.GetGlobalConstantAddressSpace());
 LangAS AS = GVArrayQTy.getAddressSpace();
 if (llvm::Constant *C =
diff --git a/clang/test/CodeGenOpenCLCXX/array-type-infinite-loop.clcpp 
b/clang/test/CodeGenOpenCLCXX/array-type-infinite-loop.clcpp
new file mode 100644
index 0..5a5b104e892f7
--- /dev/null
+++ b/clang/test/CodeGenOpenCLCXX/array-type-infinite-loop.clcpp
@@ -0,0 +1,25 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 4
+//RUN: %clang_cc1 %s -emit-llvm -O1 -o - | FileCheck %s
+
+// CHECK-LABEL: define dso_local spir_kernel void @test(
+// CHECK-SAME: ptr nocapture noundef readonly align 8 [[IN:%.*]], ptr 
nocapture noundef writeonly align 8 [[OUT:%.*]]) local_unnamed_addr 
#[[ATTR0:[0-9]+]] !kernel_arg_addr_space [[META3:![0-9]+]] 
!kernel_arg_access_qual [[META4:![0-9]+]] !kernel_arg_type [[META5:![0-9]+]] 
!kernel_arg_base_type [[META5]] !kernel_arg_type_qual [[META6:![0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[ARRAYIDX1:%.*]] = getelementptr inbounds i8, ptr [[IN]], 
i64 8
+// CHECK-NEXT:[[TMP0:%.*]] = load i64, ptr [[ARRAYIDX1]], align 8, !tbaa 
[[TBAA7:![0-9]+]]
+// CHECK-NEXT:store i64 [[TMP0]], ptr [[OUT]], align 8, !tbaa [[TBAA7]]
+// CHECK-NEXT:ret void
+//
+__kernel void test(__global long *In, __global long *Out) {
+   long m[4] = {  In[0], In[1], 0, 0 };
+   *Out = m[1];
+}
+//.
+// CHECK: [[META3]] = !{i32 1, i32 1}
+// CHECK: [[META4]] = !{!"none", !"none"}
+// CHECK: [[META5]] = !{!"long*", !"long*"}
+// CHECK: [[META6]] = !{!"", !""}
+// CHECK: [[TBAA7]] = !{[[META8:![0-9]+]], [[META8]], i64 0}
+// CHECK: [[META8]] = !{!"long", [[META9:![0-9]+]], i64 0}
+// CHECK: [[META9]] = !{!"omnipotent char", [[META10:![0-9]+]], i64 0}
+// CHECK: [[META10]] = !{!"Simple C++ TBAA"}
+//.

>From 17ac766cdcbf22af685b89b9a054a22afb42f46e Mon Sep 17 00:00:00 2001
From: Changpeng Fang 
Date: Fri, 17 May 2024 18:20:06 -0700
Subject: [PATCH 2/3] [OpenCL] Fix an infinite loop in builidng
 AddrSpaceQualType

  Fix ASTContext::removeAddrSpaceQualType()
---
 clang/include/clang/AST/ASTContext.h | 2 +-
 clang/lib/AST/ASTContext.cpp | 9 -
 clang/lib/CodeGen/CGExprAgg.cpp  | 3 +--
 3 files changed, 10 insertions(+), 4 deletions(-)

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index e03b112194786..2ce2b810d3636 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2611,7 +2611,7 @@ class ASTContext : public RefCountedBase {
   ///
   /// \returns if this is an array type, the completely unqualified array type
   /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
-  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
+  QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const;
 
   /// Determine whether the given types are equivalent after
   /// cvr-qualifiers have been removed.
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 8fc2bb8c401c2..388233c554d46 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -3054,6 +3054,13 @@ QualType ASTContext::removeAddrSpaceQualType(QualType T) 
const {
   if (!T.hasAddressS

[clang] [OpenCL] Fix an infinite loop in builidng AddrSpaceQualType (PR #92612)

2024-05-18 Thread Changpeng Fang via cfe-commits

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


[clang] [OpenCL] Fix an infinite loop in builidng AddrSpaceQualType (PR #92612)

2024-05-18 Thread Changpeng Fang via cfe-commits


@@ -3054,6 +3054,13 @@ QualType ASTContext::removeAddrSpaceQualType(QualType T) 
const {
   if (!T.hasAddressSpace())
 return T;
 
+  // For arrays, strip the qualifier off the element type, then reconstruct the
+  // array type
+  if (T.getTypePtr()->isArrayType()) {
+Qualifiers Qualfs;
+return getUnqualifiedArrayType(T, Qualfs);

changpeng wrote:

Thanks.  Can I do as the following?
Note that I am passing QualifierCollector to getUnqualifiedArrayType, which has 
Qualifiers as the second argument.
 Also,  TypeNode = T.getTypePtr(); after I is unqualified.

 QualifierCollector Quals;
  const Type *TypeNode;
  if (T.getTypePtr()->isArrayType()) {
T = getUnqualifiedArrayType(T, Quals);
TypeNode = T.getTypePtr();
  } else {
  while (T.hasAddressSpace()) {
  

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


[clang] [clang] Introduce `SemaAccess` (PR #92674)

2024-05-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Vlad Serebrennikov (Endilll)


Changes

This patch moves `Sema` functions that handle access checking into the new 
`SemaAccess` class. This continues previous efforts to split Sema up. 
Additional context can be found in 
https://github.com/llvm/llvm-project/pull/84184.

As usual, formatting changes are split into a separate commit.

---

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


20 Files Affected:

- (modified) clang/include/clang/Sema/Lookup.h (+2-1) 
- (modified) clang/include/clang/Sema/Sema.h (+38-119) 
- (added) clang/include/clang/Sema/SemaAccess.h (+112) 
- (modified) clang/lib/Sema/Sema.cpp (+2) 
- (modified) clang/lib/Sema/SemaAccess.cpp (+160-148) 
- (modified) clang/lib/Sema/SemaCast.cpp (+15-16) 
- (modified) clang/lib/Sema/SemaCodeComplete.cpp (+4-2) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+2-1) 
- (modified) clang/lib/Sema/SemaDeclAttr.cpp (+2-1) 
- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+28-26) 
- (modified) clang/lib/Sema/SemaDeclObjC.cpp (+2-1) 
- (modified) clang/lib/Sema/SemaExceptionSpec.cpp (+13-10) 
- (modified) clang/lib/Sema/SemaExprCXX.cpp (+26-19) 
- (modified) clang/lib/Sema/SemaExprMember.cpp (+1) 
- (modified) clang/lib/Sema/SemaInit.cpp (+20-15) 
- (modified) clang/lib/Sema/SemaLookup.cpp (+5-4) 
- (modified) clang/lib/Sema/SemaOpenMP.cpp (+5-4) 
- (modified) clang/lib/Sema/SemaOverload.cpp (+23-16) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+2-1) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+4-3) 


``diff
diff --git a/clang/include/clang/Sema/Lookup.h 
b/clang/include/clang/Sema/Lookup.h
index b0a08a05ac6a0..1d2a7de941698 100644
--- a/clang/include/clang/Sema/Lookup.h
+++ b/clang/include/clang/Sema/Lookup.h
@@ -25,6 +25,7 @@
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/Specifiers.h"
 #include "clang/Sema/Sema.h"
+#include "clang/Sema/SemaAccess.h"
 #include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Casting.h"
@@ -761,7 +762,7 @@ class LookupResult {
   void diagnoseAccess() {
 if (!isAmbiguous() && isClassLookup() &&
 getSema().getLangOpts().AccessControl)
-  getSema().CheckLookupAccess(*this);
+  getSema().Access().CheckLookupAccess(*this);
   }
 
   void diagnoseAmbiguous() {
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d4d4a82525a02..4b0cac3b15331 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -167,6 +167,7 @@ class Preprocessor;
 class PseudoDestructorTypeStorage;
 class PseudoObjectExpr;
 class QualType;
+class SemaAccess;
 class SemaCodeCompletion;
 class SemaCUDA;
 class SemaHLSL;
@@ -451,39 +452,38 @@ class Sema final : public SemaBase {
   // Table of Contents
   // -
   // 1. Semantic Analysis (Sema.cpp)
-  // 2. C++ Access Control (SemaAccess.cpp)
-  // 3. Attributes (SemaAttr.cpp)
-  // 4. Availability Attribute Handling (SemaAvailability.cpp)
-  // 5. Casts (SemaCast.cpp)
-  // 6. Extra Semantic Checking (SemaChecking.cpp)
-  // 7. C++ Coroutines (SemaCoroutine.cpp)
-  // 8. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
-  // 9. Declarations (SemaDecl.cpp)
-  // 10. Declaration Attribute Handling (SemaDeclAttr.cpp)
-  // 11. C++ Declarations (SemaDeclCXX.cpp)
-  // 12. C++ Exception Specifications (SemaExceptionSpec.cpp)
-  // 13. Expressions (SemaExpr.cpp)
-  // 14. C++ Expressions (SemaExprCXX.cpp)
-  // 15. Member Access Expressions (SemaExprMember.cpp)
-  // 16. Initializers (SemaInit.cpp)
-  // 17. C++ Lambda Expressions (SemaLambda.cpp)
-  // 18. Name Lookup (SemaLookup.cpp)
-  // 19. Modules (SemaModule.cpp)
-  // 20. C++ Overloading (SemaOverload.cpp)
-  // 21. Pseudo-Object (SemaPseudoObject.cpp)
-  // 22. Statements (SemaStmt.cpp)
-  // 23. `inline asm` Statement (SemaStmtAsm.cpp)
-  // 24. Statement Attribute Handling (SemaStmtAttr.cpp)
-  // 25. C++ Templates (SemaTemplate.cpp)
-  // 26. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
-  // 27. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
-  // 28. C++ Template Declaration Instantiation
+  // 2. Attributes (SemaAttr.cpp)
+  // 3. Availability Attribute Handling (SemaAvailability.cpp)
+  // 4. Casts (SemaCast.cpp)
+  // 5. Extra Semantic Checking (SemaChecking.cpp)
+  // 6. C++ Coroutines (SemaCoroutine.cpp)
+  // 7. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
+  // 8. Declarations (SemaDecl.cpp)
+  // 9. Declaration Attribute Handling (SemaDeclAttr.cpp)
+  // 10. C++ Declarations (SemaDeclCXX.cpp)
+  // 11. C++ Exception Specifications (SemaExceptionSpec.cpp)
+  // 12. Expressions (SemaExpr.cpp)
+  // 13. C++ Expressions (SemaExprCXX.cpp)
+  // 14. Member Access Expressions (SemaExprMember.cpp)
+  // 15. Initializers (SemaInit.cpp)
+  // 16. C++ Lambda Expressions (SemaLambda.cpp)
+  // 17. Name Lookup (SemaLookup.cpp)
+  // 18. Modules (Sem

[clang] [clang-format] Fix bad spacing of macro after lambda introducer (PR #92673)

2024-05-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Matthew Olsson (mattco98)


Changes

Fixes  #92661.

Also fixes the same problem applied to function-style macros, which I didn't 
consider when creating that issue.

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


2 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (+24) 
- (modified) clang/unittests/Format/FormatTest.cpp (+9) 


``diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 7c4c76a91f2c5..5f0040ec22d8b 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -76,6 +76,13 @@ static bool isLambdaParameterList(const FormatToken *Left) {
  Left->Previous->MatchingParen->is(TT_LambdaLSquare);
 }
 
+/// Returns \c true if the token is the right square bracket of a lambda
+/// introducer.
+static bool isLambdaRightIntroducerBracket(const FormatToken &Tok) {
+  return Tok.is(tok::r_square) && Tok.MatchingParen &&
+Tok.MatchingParen->is(TT_LambdaLSquare);
+}
+
 /// Returns \c true if the token is followed by a boolean condition, \c false
 /// otherwise.
 static bool isKeywordWithCondition(const FormatToken &Tok) {
@@ -4646,6 +4653,23 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 (Left.is(tok::r_square) && Left.is(TT_AttributeSquare))) {
   return true;
 }
+if (Left.is(tok::identifier) && Left.Previous &&
+isLambdaRightIntroducerBracket(*Left.Previous)) {
+  // Check if Right is part of a macro call
+  if (Right.MatchingParen && Right.MatchingParen->Next &&
+  Right.MatchingParen->Next->is(tok::l_paren)) {
+return false;
+  }
+  return true;
+}
+if (Left.is(tok::r_paren) && Left.MatchingParen &&
+Left.MatchingParen->Previous) {
+  auto const *LeftParenPrev = Left.MatchingParen->Previous;
+  if (LeftParenPrev->is(tok::identifier) && LeftParenPrev->Previous &&
+  isLambdaRightIntroducerBracket(*LeftParenPrev->Previous)) {
+return true;
+  }
+}
 if (Left.is(TT_ForEachMacro)) {
   return Style.SpaceBeforeParensOptions.AfterForeachMacros ||
  spaceRequiredBeforeParens(Right);
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 6f57f10e12e88..6efcadd1310f1 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -16639,6 +16639,9 @@ TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
   verifyFormat("T A::operator()();", NoSpace);
   verifyFormat("X A::operator++(T);", NoSpace);
   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
+  verifyFormat("auto lambda = [] [[attr]] () { return 0; };", NoSpace);
+  verifyFormat("auto lambda = [] MACRO_ATTR () { return 0; };", NoSpace);
+  verifyFormat("auto lambda = [] FN_MACRO_ATTR(a, (b + c)) () { return 0; };", 
NoSpace);
   verifyFormat("#if (foo || bar) && baz\n"
"#elif ((a || b) && c) || d\n"
"#endif",
@@ -16696,6 +16699,9 @@ TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
   verifyFormat("T A::operator() ();", Space);
   verifyFormat("X A::operator++ (T);", Space);
   verifyFormat("auto lambda = [] () { return 0; };", Space);
+  verifyFormat("auto lambda = [] [[attr]] () { return 0; };", Space);
+  verifyFormat("auto lambda = [] MACRO_ATTR () { return 0; };", Space);
+  verifyFormat("auto lambda = [] FN_MACRO_ATTR(a, (b + c)) () { return 0; };", 
Space);
   verifyFormat("int x = int (y);", Space);
   verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space);
   verifyFormat("__builtin_LINE ()", Space);
@@ -16756,6 +16762,9 @@ TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
   verifyFormat("X A::operator++ (T);", SomeSpace);
   verifyFormat("int x = int (y);", SomeSpace);
   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
+  verifyFormat("auto lambda = [] [[attr]] () { return 0; };", SomeSpace);
+  verifyFormat("auto lambda = [] MACRO_ATTR () { return 0; };", SomeSpace);
+  verifyFormat("auto lambda = [] FN_MACRO_ATTR(a, (b + c)) () { return 0; };", 
SomeSpace);
 
   FormatStyle SpaceControlStatements = getLLVMStyle();
   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;

``




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


[clang] [clang-format] Fix bad spacing of macro after lambda introducer (PR #92673)

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


[clang] [clang-format] Fix bad spacing of macro after lambda introducer (PR #92673)

2024-05-18 Thread Matthew Olsson via cfe-commits

https://github.com/mattco98 created 
https://github.com/llvm/llvm-project/pull/92673

Fixes  #92661.

Also fixes the same problem applied to function-style macros, which I didn't 
consider when creating that issue.

>From 8fe985951273af784588265f5883be03d907744a Mon Sep 17 00:00:00 2001
From: Matthew Olsson 
Date: Sat, 18 May 2024 13:51:58 -0700
Subject: [PATCH] [clang-format] Fix bad spacing of macro after lambda
 introducer

---
 clang/lib/Format/TokenAnnotator.cpp   | 24 
 clang/unittests/Format/FormatTest.cpp |  9 +
 2 files changed, 33 insertions(+)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 7c4c76a91f2c5..5f0040ec22d8b 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -76,6 +76,13 @@ static bool isLambdaParameterList(const FormatToken *Left) {
  Left->Previous->MatchingParen->is(TT_LambdaLSquare);
 }
 
+/// Returns \c true if the token is the right square bracket of a lambda
+/// introducer.
+static bool isLambdaRightIntroducerBracket(const FormatToken &Tok) {
+  return Tok.is(tok::r_square) && Tok.MatchingParen &&
+Tok.MatchingParen->is(TT_LambdaLSquare);
+}
+
 /// Returns \c true if the token is followed by a boolean condition, \c false
 /// otherwise.
 static bool isKeywordWithCondition(const FormatToken &Tok) {
@@ -4646,6 +4653,23 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 (Left.is(tok::r_square) && Left.is(TT_AttributeSquare))) {
   return true;
 }
+if (Left.is(tok::identifier) && Left.Previous &&
+isLambdaRightIntroducerBracket(*Left.Previous)) {
+  // Check if Right is part of a macro call
+  if (Right.MatchingParen && Right.MatchingParen->Next &&
+  Right.MatchingParen->Next->is(tok::l_paren)) {
+return false;
+  }
+  return true;
+}
+if (Left.is(tok::r_paren) && Left.MatchingParen &&
+Left.MatchingParen->Previous) {
+  auto const *LeftParenPrev = Left.MatchingParen->Previous;
+  if (LeftParenPrev->is(tok::identifier) && LeftParenPrev->Previous &&
+  isLambdaRightIntroducerBracket(*LeftParenPrev->Previous)) {
+return true;
+  }
+}
 if (Left.is(TT_ForEachMacro)) {
   return Style.SpaceBeforeParensOptions.AfterForeachMacros ||
  spaceRequiredBeforeParens(Right);
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 6f57f10e12e88..6efcadd1310f1 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -16639,6 +16639,9 @@ TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
   verifyFormat("T A::operator()();", NoSpace);
   verifyFormat("X A::operator++(T);", NoSpace);
   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
+  verifyFormat("auto lambda = [] [[attr]] () { return 0; };", NoSpace);
+  verifyFormat("auto lambda = [] MACRO_ATTR () { return 0; };", NoSpace);
+  verifyFormat("auto lambda = [] FN_MACRO_ATTR(a, (b + c)) () { return 0; };", 
NoSpace);
   verifyFormat("#if (foo || bar) && baz\n"
"#elif ((a || b) && c) || d\n"
"#endif",
@@ -16696,6 +16699,9 @@ TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
   verifyFormat("T A::operator() ();", Space);
   verifyFormat("X A::operator++ (T);", Space);
   verifyFormat("auto lambda = [] () { return 0; };", Space);
+  verifyFormat("auto lambda = [] [[attr]] () { return 0; };", Space);
+  verifyFormat("auto lambda = [] MACRO_ATTR () { return 0; };", Space);
+  verifyFormat("auto lambda = [] FN_MACRO_ATTR(a, (b + c)) () { return 0; };", 
Space);
   verifyFormat("int x = int (y);", Space);
   verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space);
   verifyFormat("__builtin_LINE ()", Space);
@@ -16756,6 +16762,9 @@ TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
   verifyFormat("X A::operator++ (T);", SomeSpace);
   verifyFormat("int x = int (y);", SomeSpace);
   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
+  verifyFormat("auto lambda = [] [[attr]] () { return 0; };", SomeSpace);
+  verifyFormat("auto lambda = [] MACRO_ATTR () { return 0; };", SomeSpace);
+  verifyFormat("auto lambda = [] FN_MACRO_ATTR(a, (b + c)) () { return 0; };", 
SomeSpace);
 
   FormatStyle SpaceControlStatements = getLLVMStyle();
   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;

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


[clang] [llvm] [BPF] Generate BTF info using 'btf:type_tag' annotation (PR #91424)

2024-05-18 Thread via cfe-commits

https://github.com/yonghong-song approved this pull request.

LGTM. The change mostly the same as previous approved patch 
https://reviews.llvm.org/D145891 except adding some BTF Type Tag V1 handling.
I tried a few examples as well as bpf selftest with both V1 and V2. All tests 
are passed.

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


[clang] [llvm] [DebugInfo][BPF] Add 'btf:type_tag' annotation in DWARF (PR #91423)

2024-05-18 Thread via cfe-commits

eddyz87 wrote:

> Test "buildkite/github-pull-requests " failed and I don't know what is the
> reason. I think it is worthwhile to rerun the test to ensure all tests
> passed.
>
CI failure seems to be a fluke as it is reported for
DataFlowSanitizer-x86_64 :: release_shadow_space.c which is completely
unrelated, also CI for 91424 passed (91424 adds one commit to the bpf
backend on top of this revision).

>


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


[clang] [clang] Introduce `SemaPseudoObject` (PR #92646)

2024-05-18 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/92646

>From 81b2c7dbb6fb9cb24d560b6069f60ba3452bbf2a Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Sat, 18 May 2024 14:20:43 +0300
Subject: [PATCH 1/2] [clang] Introduce `SemaPseudoObject`

---
 clang/include/clang/Sema/Sema.h | 57 +++---
 clang/include/clang/Sema/SemaPseudoObject.h | 41 +
 clang/lib/Sema/Sema.cpp |  2 +
 clang/lib/Sema/SemaExpr.cpp |  9 +--
 clang/lib/Sema/SemaPseudoObject.cpp | 65 +++--
 clang/lib/Sema/TreeTransform.h  |  7 ++-
 6 files changed, 107 insertions(+), 74 deletions(-)
 create mode 100644 clang/include/clang/Sema/SemaPseudoObject.h

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d4d4a82525a02..9d26a48dd213a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -173,6 +173,7 @@ class SemaHLSL;
 class SemaObjC;
 class SemaOpenACC;
 class SemaOpenMP;
+class SemaPseudoObject;
 class SemaSYCL;
 class StandardConversionSequence;
 class Stmt;
@@ -470,20 +471,19 @@ class Sema final : public SemaBase {
   // 18. Name Lookup (SemaLookup.cpp)
   // 19. Modules (SemaModule.cpp)
   // 20. C++ Overloading (SemaOverload.cpp)
-  // 21. Pseudo-Object (SemaPseudoObject.cpp)
-  // 22. Statements (SemaStmt.cpp)
-  // 23. `inline asm` Statement (SemaStmtAsm.cpp)
-  // 24. Statement Attribute Handling (SemaStmtAttr.cpp)
-  // 25. C++ Templates (SemaTemplate.cpp)
-  // 26. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
-  // 27. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
-  // 28. C++ Template Declaration Instantiation
+  // 21. Statements (SemaStmt.cpp)
+  // 22. `inline asm` Statement (SemaStmtAsm.cpp)
+  // 23. Statement Attribute Handling (SemaStmtAttr.cpp)
+  // 24. C++ Templates (SemaTemplate.cpp)
+  // 25. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
+  // 26. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
+  // 27. C++ Template Declaration Instantiation
   // (SemaTemplateInstantiateDecl.cpp)
-  // 29. C++ Variadic Templates (SemaTemplateVariadic.cpp)
-  // 30. Constraints and Concepts (SemaConcept.cpp)
-  // 31. Types (SemaType.cpp)
-  // 32. FixIt Helpers (SemaFixItUtils.cpp)
-  // 33. Name Lookup for RISC-V Vector Intrinsic (SemaRISCVVectorLookup.cpp)
+  // 28. C++ Variadic Templates (SemaTemplateVariadic.cpp)
+  // 29. Constraints and Concepts (SemaConcept.cpp)
+  // 30. Types (SemaType.cpp)
+  // 31. FixIt Helpers (SemaFixItUtils.cpp)
+  // 32. Name Lookup for RISC-V Vector Intrinsic (SemaRISCVVectorLookup.cpp)
 
   /// \name Semantic Analysis
   /// Implementations are in Sema.cpp
@@ -1014,6 +1014,11 @@ class Sema final : public SemaBase {
 return *OpenMPPtr;
   }
 
+  SemaPseudoObject &PseudoObject() {
+assert(PseudoObjectPtr);
+return *PseudoObjectPtr;
+  }
+
   SemaSYCL &SYCL() {
 assert(SYCLPtr);
 return *SYCLPtr;
@@ -1055,6 +1060,7 @@ class Sema final : public SemaBase {
   std::unique_ptr ObjCPtr;
   std::unique_ptr OpenACCPtr;
   std::unique_ptr OpenMPPtr;
+  std::unique_ptr PseudoObjectPtr;
   std::unique_ptr SYCLPtr;
 
   ///@}
@@ -6370,6 +6376,8 @@ class Sema final : public SemaBase {
   llvm::SmallVector, 1>
   ImplicitlyRetainedSelfLocs;
 
+  void maybeExtendBlockObject(ExprResult &E);
+
 private:
   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind 
Kind);
 
@@ -8368,29 +8376,6 @@ class Sema final : public SemaBase {
   //
   //
 
-  /// \name Pseudo-Object
-  /// Implementations are in SemaPseudoObject.cpp
-  ///@{
-
-public:
-  void maybeExtendBlockObject(ExprResult &E);
-
-  ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
- UnaryOperatorKind Opcode, Expr *Op);
-  ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
- BinaryOperatorKind Opcode, Expr *LHS,
- Expr *RHS);
-  ExprResult checkPseudoObjectRValue(Expr *E);
-  Expr *recreateSyntacticForm(PseudoObjectExpr *E);
-
-  ///@}
-
-  //
-  //
-  // -
-  //
-  //
-
   /// \name Statements
   /// Implementations are in SemaStmt.cpp
   ///@{
diff --git a/clang/include/clang/Sema/SemaPseudoObject.h 
b/clang/include/clang/Sema/SemaPseudoObject.h
new file mode 100644
index 0..f1f4dc07cf1c1
--- /dev/null
+++ b/clang/include/clang/Sema/SemaPseudoObject.h
@@ -0,0 +1,41 @@
+//===- SemaPseudoObject.h --- Semantic Analysis for Pseudo-Objects 
===//
+//
+// 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
+//
+//===--

[clang] [clang] Introduce `SemaConcept` (PR #92672)

2024-05-18 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 58c778565cd64a69ea86e7e67e6a87fff3b0b224 
354e8ff9f82d26b3611766d6b78b5da76ec87e69 -- clang/include/clang/Sema/Sema.h 
clang/include/clang/Sema/SemaConcept.h clang/lib/Parse/ParseDecl.cpp 
clang/lib/Parse/ParseDeclCXX.cpp clang/lib/Parse/ParseExpr.cpp 
clang/lib/Parse/ParseExprCXX.cpp clang/lib/Parse/ParseTemplate.cpp 
clang/lib/Sema/Sema.cpp clang/lib/Sema/SemaChecking.cpp 
clang/lib/Sema/SemaConcept.cpp clang/lib/Sema/SemaDecl.cpp 
clang/lib/Sema/SemaDeclCXX.cpp clang/lib/Sema/SemaExpr.cpp 
clang/lib/Sema/SemaExprCXX.cpp clang/lib/Sema/SemaOverload.cpp 
clang/lib/Sema/SemaTemplate.cpp clang/lib/Sema/SemaTemplateDeduction.cpp 
clang/lib/Sema/SemaTemplateInstantiate.cpp 
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp clang/lib/Sema/SemaType.cpp 
clang/lib/Sema/TreeTransform.h
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/Sema/SemaConcept.h 
b/clang/include/clang/Sema/SemaConcept.h
index 7591f28acb..96e36dc8a1 100644
--- a/clang/include/clang/Sema/SemaConcept.h
+++ b/clang/include/clang/Sema/SemaConcept.h
@@ -21,7 +21,6 @@
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprConcepts.h"
-#include "clang/AST/DeclTemplate.h"
 #include "clang/AST/NestedNameSpecifier.h"
 #include "clang/AST/TemplateBase.h"
 #include "clang/AST/Type.h"

``




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


[clang] [clang] Introduce `SemaCoroutine` (PR #92645)

2024-05-18 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/92645

>From 4fe09a3411e54561857d2f9d8c1808cb2728e299 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Sat, 18 May 2024 13:33:04 +0300
Subject: [PATCH 1/3] [clang] Introduce `SemaCoroutine`

---
 clang/include/clang/Sema/Sema.h  |  58 +-
 clang/include/clang/Sema/SemaCoroutine.h |  73 
 clang/lib/Parse/ParseExpr.cpp|   3 +-
 clang/lib/Parse/ParseExprCXX.cpp |   3 +-
 clang/lib/Parse/ParseStmt.cpp|   3 +-
 clang/lib/Sema/Sema.cpp  |   4 +-
 clang/lib/Sema/SemaCoroutine.cpp | 218 ---
 clang/lib/Sema/SemaDecl.cpp  |  16 +-
 clang/lib/Sema/SemaStmt.cpp  |   9 +-
 clang/lib/Sema/TreeTransform.h   |  25 +--
 10 files changed, 227 insertions(+), 185 deletions(-)
 create mode 100644 clang/include/clang/Sema/SemaCoroutine.h

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d4d4a82525a02..1d0fbeacfe061 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -168,6 +168,7 @@ class PseudoDestructorTypeStorage;
 class PseudoObjectExpr;
 class QualType;
 class SemaCodeCompletion;
+class SemaCoroutine;
 class SemaCUDA;
 class SemaHLSL;
 class SemaObjC;
@@ -989,6 +990,11 @@ class Sema final : public SemaBase {
 return *CodeCompletionPtr;
   }
 
+  SemaCoroutine &Coroutine() {
+assert(CoroutinePtr);
+return *CoroutinePtr;
+  }
+
   SemaCUDA &CUDA() {
 assert(CUDAPtr);
 return *CUDAPtr;
@@ -1050,6 +1056,7 @@ class Sema final : public SemaBase {
   mutable IdentifierInfo *Ident_super;
 
   std::unique_ptr CodeCompletionPtr;
+  std::unique_ptr CoroutinePtr;
   std::unique_ptr CUDAPtr;
   std::unique_ptr HLSLPtr;
   std::unique_ptr ObjCPtr;
@@ -2267,57 +2274,6 @@ class Sema final : public SemaBase {
   //
   //
 
-  /// \name C++ Coroutines
-  /// Implementations are in SemaCoroutine.cpp
-  ///@{
-
-public:
-  /// The C++ "std::coroutine_traits" template, which is defined in
-  /// \
-  ClassTemplateDecl *StdCoroutineTraitsCache;
-
-  bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
-   StringRef Keyword);
-  ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
-  ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
-  StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
-
-  ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
-  ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
-  UnresolvedLookupExpr *Lookup);
-  ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
-  Expr *Awaiter, bool IsImplicit = false);
-  ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
-UnresolvedLookupExpr *Lookup);
-  ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
-  StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
-   bool IsImplicit = false);
-  StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
-  bool buildCoroutineParameterMoves(SourceLocation Loc);
-  VarDecl *buildCoroutinePromise(SourceLocation Loc);
-  void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
-
-  // As a clang extension, enforces that a non-coroutine function must be 
marked
-  // with [[clang::coro_wrapper]] if it returns a type marked with
-  // [[clang::coro_return_type]].
-  // Expects that FD is not a coroutine.
-  void CheckCoroutineWrapper(FunctionDecl *FD);
-  /// Lookup 'coroutine_traits' in std namespace and std::experimental
-  /// namespace. The namespace found is recorded in Namespace.
-  ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
-   SourceLocation FuncLoc);
-  /// Check that the expression co_await promise.final_suspend() shall not be
-  /// potentially-throwing.
-  bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
-
-  ///@}
-
-  //
-  //
-  // -
-  //
-  //
-
   /// \name C++ Scope Specifiers
   /// Implementations are in SemaCXXScopeSpec.cpp
   ///@{
diff --git a/clang/include/clang/Sema/SemaCoroutine.h 
b/clang/include/clang/Sema/SemaCoroutine.h
new file mode 100644
index 0..20f1fffc970f8
--- /dev/null
+++ b/clang/include/clang/Sema/SemaCoroutine.h
@@ -0,0 +1,73 @@
+//===- SemaCUDA.h - Semantic Analysis for C++20 coroutines 
===//
+//
+// 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
+//
+//===--===//
+/// \file
+/// This fil

[clang] [clang] Introduce `SemaConcept` (PR #92672)

2024-05-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Vlad Serebrennikov (Endilll)


Changes

This patch moves `Sema` functions that handle C++20 concepts into the new 
`SemaConcept` class. This continues previous efforts to split `Sema` up. 
Additional context can be found in #84184.

This patch has 3 commits: the first one covers what already was in 
`SemaConcept.cpp`, the second one moves quite a lot of concepts-related 
functions from `Sema` into `SemaConcept`. The third one, as usual, contains 
formatting changes.

---

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


21 Files Affected:

- (modified) clang/include/clang/Sema/Sema.h (+26-381) 
- (modified) clang/include/clang/Sema/SemaConcept.h (+388-2) 
- (modified) clang/lib/Parse/ParseDecl.cpp (+4-2) 
- (modified) clang/lib/Parse/ParseDeclCXX.cpp (+3-3) 
- (modified) clang/lib/Parse/ParseExpr.cpp (+5-4) 
- (modified) clang/lib/Parse/ParseExprCXX.cpp (+16-14) 
- (modified) clang/lib/Parse/ParseTemplate.cpp (+13-10) 
- (modified) clang/lib/Sema/Sema.cpp (+3-9) 
- (modified) clang/lib/Sema/SemaChecking.cpp (-6) 
- (modified) clang/lib/Sema/SemaConcept.cpp (+809-171) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+7-6) 
- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+4-36) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+4-3) 
- (modified) clang/lib/Sema/SemaExprCXX.cpp (+1-227) 
- (modified) clang/lib/Sema/SemaOverload.cpp (+25-23) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+31-392) 
- (modified) clang/lib/Sema/SemaTemplateDeduction.cpp (+17-44) 
- (modified) clang/lib/Sema/SemaTemplateInstantiate.cpp (+41-3) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+4-2) 
- (modified) clang/lib/Sema/SemaType.cpp (+4-3) 
- (modified) clang/lib/Sema/TreeTransform.h (+12-13) 


``diff
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d4d4a82525a02..be4aebf1d04e2 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -168,6 +168,7 @@ class PseudoDestructorTypeStorage;
 class PseudoObjectExpr;
 class QualType;
 class SemaCodeCompletion;
+class SemaConcept;
 class SemaCUDA;
 class SemaHLSL;
 class SemaObjC;
@@ -181,6 +182,7 @@ class SwitchStmt;
 class TemplateArgument;
 class TemplateArgumentList;
 class TemplateArgumentLoc;
+class TemplateCompareNewDeclInfo;
 class TemplateDecl;
 class TemplateInstantiationCallback;
 class TemplateParameterList;
@@ -989,6 +991,11 @@ class Sema final : public SemaBase {
 return *CodeCompletionPtr;
   }
 
+  SemaConcept &Concept() {
+assert(ConceptPtr);
+return *ConceptPtr;
+  }
+
   SemaCUDA &CUDA() {
 assert(CUDAPtr);
 return *CUDAPtr;
@@ -1050,6 +1057,7 @@ class Sema final : public SemaBase {
   mutable IdentifierInfo *Ident_super;
 
   std::unique_ptr CodeCompletionPtr;
+  std::unique_ptr ConceptPtr;
   std::unique_ptr CUDAPtr;
   std::unique_ptr HLSLPtr;
   std::unique_ptr ObjCPtr;
@@ -2028,8 +2036,6 @@ class Sema final : public SemaBase {
   void CheckTCBEnforcement(const SourceLocation CallExprLoc,
const NamedDecl *Callee);
 
-  void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
-
 private:
   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
 const ArraySubscriptExpr *ASE = nullptr,
@@ -4727,9 +4733,6 @@ class Sema final : public SemaBase {
 
   void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
StringLiteral *DeletedMessage = nullptr);
-  void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
-  ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
-  ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
 
   NamedDecl *
   ActOnDecompositionDeclarator(Scope *S, Declarator &D,
@@ -6811,45 +6814,6 @@ class Sema final : public SemaBase {
   bool IsIfExists, CXXScopeSpec 
&SS,
   UnqualifiedId &Name);
 
-  RequiresExprBodyDecl *
-  ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
- ArrayRef LocalParameters,
- Scope *BodyScope);
-  void ActOnFinishRequiresExpr();
-  concepts::Requirement *ActOnSimpleRequirement(Expr *E);
-  concepts::Requirement *ActOnTypeRequirement(SourceLocation TypenameKWLoc,
-  CXXScopeSpec &SS,
-  SourceLocation NameLoc,
-  const IdentifierInfo *TypeName,
-  TemplateIdAnnotation 
*TemplateId);
-  concepts::Requirement *ActOnCompoundRequirement(Expr *E,
-  SourceLocation NoexceptLoc);
-  concepts::Requirement *ActOnCompoundRequirement(
-  Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
-  Templa

[clang] nonblocking/nonallocating attributes (was: nolock/noalloc) (PR #84983)

2024-05-18 Thread Doug Wyatt via cfe-commits


@@ -1870,6 +1870,28 @@ bool Sema::IsFunctionConversion(QualType FromType, 
QualType ToType,
   FromFn = QT->getAs();
   Changed = true;
 }
+
+// For C, when called from checkPointerTypesForAssignment,
+// we need not to alter FromFn, or else even an innocuous cast
+// like dropping effects will fail. In C++ however we do want to
+// alter FromFn. TODO: Is this correct?

dougsonos wrote:

The test case which exposes a need for this kind of logic is:
```
void nonblocking() [[clang::nonblocking]];
void type_conversions() {
  void (*fp_plain)();
  fp_plain = nonblocking;
}
```

The call chain to `IsFunctionConversion` is:
```
CheckSingleAssignmentConversion
PerformImplicitConversion (in C++ only, not plain C)
TryImplicitConversion
IsStandardConversion
IsFunctionConversion
```

`IsFunctionConversion` drops `noreturn` and `noexcept` from the function type 
very similarly to what this code does for effects. If this code is disabled, 
then an implicit conversion between the two canonically different types fails. 
Then `TryUserDefinedConversion` fails too.

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


[clang] [OpenCL] Fix an infinite loop in builidng AddrSpaceQualType (PR #92612)

2024-05-18 Thread Eli Friedman via cfe-commits


@@ -3054,6 +3054,13 @@ QualType ASTContext::removeAddrSpaceQualType(QualType T) 
const {
   if (!T.hasAddressSpace())
 return T;
 
+  // For arrays, strip the qualifier off the element type, then reconstruct the
+  // array type
+  if (T.getTypePtr()->isArrayType()) {
+Qualifiers Qualfs;
+return getUnqualifiedArrayType(T, Qualfs);

efriedma-quic wrote:

You need to preserve the non-address-space qualifiers, the same way the code 
after the loop does.  Actually, I'd just recommend restructuring to use the 
existing code, something like:

```
if (T.getTypePtr()->isArrayType()) {
  getUnqualifiedArrayType()
} else {
  while (T.hasAddressSpace()) {
 [...]
  }
}
```


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


[clang] [llvm] [inline] Clone return range attribute on the callsite into inlined call (PR #92666)

2024-05-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Andreas Jonson (andjo403)


Changes

CC @goldsteinn @nikic 

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


3 Files Affected:

- (modified) clang/test/Headers/__clang_hip_math.hip (+3-3) 
- (modified) llvm/lib/Transforms/Utils/InlineFunction.cpp (+12-1) 
- (modified) llvm/test/Transforms/Inline/ret_attr_align_and_noundef.ll (+73) 


``diff
diff --git a/clang/test/Headers/__clang_hip_math.hip 
b/clang/test/Headers/__clang_hip_math.hip
index 1271868a53b86..26da82843c512 100644
--- a/clang/test/Headers/__clang_hip_math.hip
+++ b/clang/test/Headers/__clang_hip_math.hip
@@ -231,7 +231,7 @@ extern "C" __device__ uint64_t test___make_mantissa(const 
char *p) {
 
 // CHECK-LABEL: @test_abs(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call noundef i32 @llvm.abs.i32(i32 
[[X:%.*]], i1 true)
+// CHECK-NEXT:[[TMP0:%.*]] = tail call noundef range(i32 0, -2147483648) 
i32 @llvm.abs.i32(i32 [[X:%.*]], i1 true)
 // CHECK-NEXT:ret i32 [[TMP0]]
 //
 extern "C" __device__ int test_abs(int x) {
@@ -240,7 +240,7 @@ extern "C" __device__ int test_abs(int x) {
 
 // CHECK-LABEL: @test_labs(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call noundef i64 @llvm.abs.i64(i64 
[[X:%.*]], i1 true)
+// CHECK-NEXT:[[TMP0:%.*]] = tail call noundef range(i64 0, 
-9223372036854775808) i64 @llvm.abs.i64(i64 [[X:%.*]], i1 true)
 // CHECK-NEXT:ret i64 [[TMP0]]
 //
 extern "C" __device__ long test_labs(long x) {
@@ -249,7 +249,7 @@ extern "C" __device__ long test_labs(long x) {
 
 // CHECK-LABEL: @test_llabs(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call noundef i64 @llvm.abs.i64(i64 
[[X:%.*]], i1 true)
+// CHECK-NEXT:[[TMP0:%.*]] = tail call noundef range(i64 0, 
-9223372036854775808) i64 @llvm.abs.i64(i64 [[X:%.*]], i1 true)
 // CHECK-NEXT:ret i64 [[TMP0]]
 //
 extern "C" __device__ long long test_llabs(long x) {
diff --git a/llvm/lib/Transforms/Utils/InlineFunction.cpp 
b/llvm/lib/Transforms/Utils/InlineFunction.cpp
index 82daaedaa0e81..ccc66c9c5cf23 100644
--- a/llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ b/llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -30,11 +30,12 @@
 #include "llvm/Analysis/ProfileSummaryInfo.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Analysis/VectorUtils.h"
-#include "llvm/IR/AttributeMask.h"
 #include "llvm/IR/Argument.h"
+#include "llvm/IR/AttributeMask.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/CFG.h"
 #include "llvm/IR/Constant.h"
+#include "llvm/IR/ConstantRange.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/DebugInfo.h"
@@ -1444,6 +1445,8 @@ static AttrBuilder 
IdentifyValidPoisonGeneratingAttributes(CallBase &CB) {
 Valid.addAttribute(Attribute::NonNull);
   if (CB.hasRetAttr(Attribute::Alignment))
 Valid.addAlignmentAttr(CB.getRetAlign());
+  if (CB.hasRetAttr(Attribute::Range))
+Valid.addRangeAttr(*CB.getRange());
   return Valid;
 }
 
@@ -1535,6 +1538,14 @@ static void AddReturnAttributes(CallBase &CB, 
ValueToValueMapTy &VMap) {
 if (ValidPG.getAlignment().valueOrOne() < 
AL.getRetAlignment().valueOrOne())
   ValidPG.removeAttribute(Attribute::Alignment);
 if (ValidPG.hasAttributes()) {
+  Attribute CBRange = ValidPG.getAttribute(Attribute::Range);
+  if (CBRange.isValid()) {
+Attribute NewRange = AL.getRetAttr(Attribute::Range);
+if (NewRange.isValid()) {
+  ValidPG.addRangeAttr(
+  CBRange.getRange().intersectWith(NewRange.getRange()));
+}
+  }
   // Three checks.
   // If the callsite has `noundef`, then a poison due to violating the
   // return attribute will create UB anyways so we can always propagate.
diff --git a/llvm/test/Transforms/Inline/ret_attr_align_and_noundef.ll 
b/llvm/test/Transforms/Inline/ret_attr_align_and_noundef.ll
index c038ffccf3e96..f4cebf1fcb5da 100644
--- a/llvm/test/Transforms/Inline/ret_attr_align_and_noundef.ll
+++ b/llvm/test/Transforms/Inline/ret_attr_align_and_noundef.ll
@@ -5,10 +5,12 @@
 
 declare ptr @foo()
 declare void @use.ptr(ptr) willreturn nounwind
+declare void @use.val(i8) willreturn nounwind
 declare void @bar()
 declare void @baz()
 declare ptr @llvm.ptrmask.p0.i64(ptr, i64)
 declare i1 @val()
+declare i8 @val8()
 
 define ptr @callee0123() {
 ; CHECK-LABEL: define ptr @callee0123() {
@@ -337,3 +339,74 @@ define ptr @caller12_todo() {
   %r = call nonnull ptr @callee12()
   ret ptr %r
 }
+
+define i8 @callee13() {
+; CHECK-LABEL: define i8 @callee13() {
+; CHECK-NEXT:[[R:%.*]] = call i8 @val8()
+; CHECK-NEXT:ret i8 [[R]]
+;
+  %r = call i8 @val8()
+  ret i8 %r
+}
+
+define i8 @caller13_okay_use_after_poison_anyways() {
+; CHECK-LABEL: define i8 @caller13_okay_use_after_poison_anyways() {
+; CHECK-NEXT:[[R_I:%.*]] = call range(i8 0, 10) i8 @val8()
+; CHECK-NEXT:call void @use.val(i8 [[R_I]])
+; CHECK-NEXT:ret i

[clang] [llvm] [inline] Clone return range attribute on the callsite into inlined call (PR #92666)

2024-05-18 Thread Andreas Jonson via cfe-commits

https://github.com/andjo403 created 
https://github.com/llvm/llvm-project/pull/92666

CC @goldsteinn @nikic 

>From 6dd513a670e813a5e6745044bc69fdd7a7b7c4d9 Mon Sep 17 00:00:00 2001
From: Andreas Jonson 
Date: Sat, 18 May 2024 19:42:03 +0200
Subject: [PATCH 1/2] [inline] Tests for clone return range attribute on the
 callsite into inlined call [NFC]

---
 .../Inline/ret_attr_align_and_noundef.ll  | 73 +++
 1 file changed, 73 insertions(+)

diff --git a/llvm/test/Transforms/Inline/ret_attr_align_and_noundef.ll 
b/llvm/test/Transforms/Inline/ret_attr_align_and_noundef.ll
index c038ffccf3e96..7e76401c0b4de 100644
--- a/llvm/test/Transforms/Inline/ret_attr_align_and_noundef.ll
+++ b/llvm/test/Transforms/Inline/ret_attr_align_and_noundef.ll
@@ -5,10 +5,12 @@
 
 declare ptr @foo()
 declare void @use.ptr(ptr) willreturn nounwind
+declare void @use.val(i8) willreturn nounwind
 declare void @bar()
 declare void @baz()
 declare ptr @llvm.ptrmask.p0.i64(ptr, i64)
 declare i1 @val()
+declare i8 @val8()
 
 define ptr @callee0123() {
 ; CHECK-LABEL: define ptr @callee0123() {
@@ -337,3 +339,74 @@ define ptr @caller12_todo() {
   %r = call nonnull ptr @callee12()
   ret ptr %r
 }
+
+define i8 @callee13() {
+; CHECK-LABEL: define i8 @callee13() {
+; CHECK-NEXT:[[R:%.*]] = call i8 @val8()
+; CHECK-NEXT:ret i8 [[R]]
+;
+  %r = call i8 @val8()
+  ret i8 %r
+}
+
+define i8 @caller13_okay_use_after_poison_anyways() {
+; CHECK-LABEL: define i8 @caller13_okay_use_after_poison_anyways() {
+; CHECK-NEXT:[[R_I:%.*]] = call i8 @val8()
+; CHECK-NEXT:call void @use.val(i8 [[R_I]])
+; CHECK-NEXT:ret i8 [[R_I]]
+;
+  %r = call range(i8 0, 10) i8 @callee13()
+  call void @use.val(i8 %r)
+  ret i8 %r
+}
+
+define i8 @callee14() {
+; CHECK-LABEL: define i8 @callee14() {
+; CHECK-NEXT:[[R:%.*]] = call noundef i8 @val8()
+; CHECK-NEXT:ret i8 [[R]]
+;
+  %r = call noundef i8 @val8()
+  ret i8 %r
+}
+
+define i8 @caller14_fail_creates_ub() {
+; CHECK-LABEL: define i8 @caller14_fail_creates_ub() {
+; CHECK-NEXT:[[R_I:%.*]] = call noundef i8 @val8()
+; CHECK-NEXT:call void @use.val(i8 [[R_I]])
+; CHECK-NEXT:ret i8 [[R_I]]
+;
+  %r = call range(i8 0, 10) i8 @callee14()
+  call void @use.val(i8 %r)
+  ret i8 %r
+}
+
+define i8 @caller14_okay_is_ub_anyways() {
+; CHECK-LABEL: define i8 @caller14_okay_is_ub_anyways() {
+; CHECK-NEXT:[[R_I:%.*]] = call noundef i8 @val8()
+; CHECK-NEXT:call void @use.val(i8 [[R_I]])
+; CHECK-NEXT:ret i8 [[R_I]]
+;
+  %r = call noundef range(i8 0, 10) i8 @callee14()
+  call void @use.val(i8 %r)
+  ret i8 %r
+}
+
+define i8 @callee15() {
+; CHECK-LABEL: define i8 @callee15() {
+; CHECK-NEXT:[[R:%.*]] = call range(i8 5, 10) i8 @val8()
+; CHECK-NEXT:ret i8 [[R]]
+;
+  %r = call range(i8 5, 10) i8 @val8()
+  ret i8 %r
+}
+
+define i8 @caller15_okay_intersect_ranges() {
+; CHECK-LABEL: define i8 @caller15_okay_intersect_ranges() {
+; CHECK-NEXT:[[R_I:%.*]] = call range(i8 5, 10) i8 @val8()
+; CHECK-NEXT:call void @use.val(i8 [[R_I]])
+; CHECK-NEXT:ret i8 [[R_I]]
+;
+  %r = call range(i8 0, 7) i8 @callee15()
+  call void @use.val(i8 %r)
+  ret i8 %r
+}

>From 9a6ad2805ea6d02050e9ac16e4041ca3277e52a4 Mon Sep 17 00:00:00 2001
From: Andreas Jonson 
Date: Sat, 18 May 2024 19:44:31 +0200
Subject: [PATCH 2/2] [inline] Clone return range attribute on the callsite
 intoinlined call

---
 clang/test/Headers/__clang_hip_math.hip |  6 +++---
 llvm/lib/Transforms/Utils/InlineFunction.cpp| 13 -
 .../Transforms/Inline/ret_attr_align_and_noundef.ll |  6 +++---
 3 files changed, 18 insertions(+), 7 deletions(-)

diff --git a/clang/test/Headers/__clang_hip_math.hip 
b/clang/test/Headers/__clang_hip_math.hip
index 1271868a53b86..26da82843c512 100644
--- a/clang/test/Headers/__clang_hip_math.hip
+++ b/clang/test/Headers/__clang_hip_math.hip
@@ -231,7 +231,7 @@ extern "C" __device__ uint64_t test___make_mantissa(const 
char *p) {
 
 // CHECK-LABEL: @test_abs(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call noundef i32 @llvm.abs.i32(i32 
[[X:%.*]], i1 true)
+// CHECK-NEXT:[[TMP0:%.*]] = tail call noundef range(i32 0, -2147483648) 
i32 @llvm.abs.i32(i32 [[X:%.*]], i1 true)
 // CHECK-NEXT:ret i32 [[TMP0]]
 //
 extern "C" __device__ int test_abs(int x) {
@@ -240,7 +240,7 @@ extern "C" __device__ int test_abs(int x) {
 
 // CHECK-LABEL: @test_labs(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call noundef i64 @llvm.abs.i64(i64 
[[X:%.*]], i1 true)
+// CHECK-NEXT:[[TMP0:%.*]] = tail call noundef range(i64 0, 
-9223372036854775808) i64 @llvm.abs.i64(i64 [[X:%.*]], i1 true)
 // CHECK-NEXT:ret i64 [[TMP0]]
 //
 extern "C" __device__ long test_labs(long x) {
@@ -249,7 +249,7 @@ extern "C" __device__ long test_labs(long x) {
 
 // CHECK-LABEL: @test_llabs(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call noundef i64 @llvm.abs.i64(i64 
[[X:%.*]], i1 true)
+// CH

[clang] [-Wunsafe-buffer-usage] Fix false positives for constant cases (PR #92432)

2024-05-18 Thread via cfe-commits


@@ -420,25 +420,63 @@ AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {
   //already duplicated
   //  - call both from Sema and from here
 
-  const auto *BaseDRE =
-  dyn_cast(Node.getBase()->IgnoreParenImpCasts());
-  if (!BaseDRE)
+  if (const auto *BaseDRE =
+  dyn_cast(Node.getBase()->IgnoreParenImpCasts())) {
+if (!BaseDRE->getDecl())
+  return false;
+if (const auto *CATy = Finder->getASTContext().getAsConstantArrayType(
+BaseDRE->getDecl()->getType())) {
+  if (const auto *IdxLit = dyn_cast(Node.getIdx())) {
+const APInt ArrIdx = IdxLit->getValue();
+// FIXME: ArrIdx.isNegative() we could immediately emit an error as
+// that's a bug
+if (ArrIdx.isNonNegative() &&
+ArrIdx.getLimitedValue() < CATy->getLimitedSize())
+  return true;
+  }
+}
+  }
+
+  if (const auto *BaseSL =
+  dyn_cast(Node.getBase()->IgnoreParenImpCasts())) {
+if (const auto *CATy =
+Finder->getASTContext().getAsConstantArrayType(BaseSL->getType())) 
{
+  if (const auto *IdxLit = dyn_cast(Node.getIdx())) {
+const APInt ArrIdx = IdxLit->getValue();
+// FIXME: ArrIdx.isNegative() we could immediately emit an error as
+// that's a bug
+if (ArrIdx.isNonNegative() &&
+ArrIdx.getLimitedValue() < CATy->getLimitedSize())
+  return true;
+  }
+}
+  }
+
+  return false;
+}
+
+AST_MATCHER(BinaryOperator, isSafePtrArithmetic) {
+  if (Node.getOpcode() != BinaryOperatorKind::BO_Add)
 return false;
-  if (!BaseDRE->getDecl())
+
+  const auto *LHSDRE = dyn_cast(Node.getLHS()->IgnoreImpCasts());
+  if (!LHSDRE)
 return false;
+
   const auto *CATy = Finder->getASTContext().getAsConstantArrayType(
-  BaseDRE->getDecl()->getType());
+  LHSDRE->getDecl()->getType());
   if (!CATy)
 return false;
 
-  if (const auto *IdxLit = dyn_cast(Node.getIdx())) {
-const APInt ArrIdx = IdxLit->getValue();
-// FIXME: ArrIdx.isNegative() we could immediately emit an error as that's 
a
-// bug
-if (ArrIdx.isNonNegative() &&
-ArrIdx.getLimitedValue() < CATy->getLimitedSize())
-  return true;
-  }
+  const auto *RHSIntLit = dyn_cast(Node.getRHS());
+  if (!RHSIntLit)
+return false;
+
+  const APInt BufferOffset = RHSIntLit->getValue();
+
+  if (BufferOffset.isNonNegative() &&

pkasting wrote:

That seems reasonable, but if that's the route, I might want to file a bug 
pre-emptively on further cases that should, or should not, be considered for 
future work.

One of my thoughts with the refactor suggestion below was that if the 
arithmetic/detection got more complex, it would be easier to implement 
consistently in a single place.

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


[clang] [-Wunsafe-buffer-usage] Fix false positives for constant cases (PR #92432)

2024-05-18 Thread via cfe-commits


@@ -420,25 +420,63 @@ AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {
   //already duplicated
   //  - call both from Sema and from here
 
-  const auto *BaseDRE =
-  dyn_cast(Node.getBase()->IgnoreParenImpCasts());
-  if (!BaseDRE)
+  if (const auto *BaseDRE =
+  dyn_cast(Node.getBase()->IgnoreParenImpCasts())) {
+if (!BaseDRE->getDecl())
+  return false;
+if (const auto *CATy = Finder->getASTContext().getAsConstantArrayType(
+BaseDRE->getDecl()->getType())) {
+  if (const auto *IdxLit = dyn_cast(Node.getIdx())) {

pkasting wrote:

I was thinking more a lambda. I don't know LLVM's coding conventions very well, 
though.

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


[clang] HLSL availability diagnostics design doc (PR #92207)

2024-05-18 Thread Helena Kotas via cfe-commits

https://github.com/hekota updated 
https://github.com/llvm/llvm-project/pull/92207

>From 3df0ba0fd2171a0115427bc6ba5e3f8e84831747 Mon Sep 17 00:00:00 2001
From: Helena Kotas 
Date: Tue, 14 May 2024 19:06:59 -0700
Subject: [PATCH 1/8] HLSL Availability Diagnostics Design Document - initial
 commit

---
 clang/docs/HLSL/AvailabilityDiagnostics.rst | 50 +
 clang/docs/HLSL/HLSLDocs.rst|  1 +
 2 files changed, 51 insertions(+)
 create mode 100644 clang/docs/HLSL/AvailabilityDiagnostics.rst

diff --git a/clang/docs/HLSL/AvailabilityDiagnostics.rst 
b/clang/docs/HLSL/AvailabilityDiagnostics.rst
new file mode 100644
index 0..218047495e6b9
--- /dev/null
+++ b/clang/docs/HLSL/AvailabilityDiagnostics.rst
@@ -0,0 +1,50 @@
+=
+HLSL Availability Diagnostics
+=
+
+.. contents::
+   :local:
+
+Introduction
+
+
+HLSL availability diagnostics emits errors or warning when unavailable shader 
APIs are used. Unavailable shader APIs are APIs that are exposed in HLSL code 
but are not available in the target shader stage or shader model version.
+
+There are three modes of HLSL availability diagnostic:
+1. **Default mode** - compiler emits an error when an unavailable shader API 
is found in a code that is reachable from the shader entry point function or 
from an exported library function (when compiling a shader library)
+2. **Relaxed mode** - same as default mode except the compiler emits a 
warning. This mode is enabled by ``-Wno-error=hlsl-availability``.
+3. **Strict mode** - compiler emits an error when when an unavailable API is 
found in parsed code regardless of whether it can be reached from the shader 
entry point or exported functions, or not. This mode is enabled by 
``-fhlsl-strict-diagnostics``.
+
+Implementation Details
+==
+
+Environment Parameter
+-
+
+In order to encode API availability based on the shader model version and 
shader model stage a new ``environment`` parameter was added to the existing 
Clang ``availability`` attribute. 
+
+The values allowed for this parameter are a subset of values allowed as the 
``llvm::Triple`` environment component. If the environment parameters is 
present, the declared availability attribute applies only to targets with the 
same platform and environment.
+
+Default and Relaxed Diagnostic Modes
+
+
+This mode is implemeted in ``DiagnoseHLSLAvailability`` class in 
``SemaHLSL.cpp`` and it is invoked after the whole translation unit is parsed 
(from ``Sema::ActOnEndOfTranslationUnit``). The implementation iterates over 
all shader entry points and exported library functions in the translation unit 
and performs an AST traversal of each function body.
+
+When a reference to another function is found and it has a body, the AST of 
the referenced function is also scanned. This chain of AST traversals will 
reach all of the code that is reachable from the initial shader entry point or 
exported library function.
+
+All shader APIs have an availability attribute that specifies the shader model 
version (and environment, if applicable) when this API was first 
introduced.When a reference to a function without a definition is found and it 
has an availability attribute, the version of the attribute is checked against 
the target shader model version and shader stage (if shader stage context is 
known), and an appropriate diagnostic is generated as needed.
+
+All shader entry functions have ``HLSLShaderAttr`` attribute that specifies 
what type of shader this function represents. However, for exported library 
functions the target shader stage is unknown, so in this case the HLSL API 
availability will be only checked against the shader model version.
+
+A list of functions that were already scanned is kept in order to avoid 
duplicate scans and diagnostics (see 
``DiagnoseHLSLAvailability::ScannedDecls``). It might happen that a shader 
library has multiple shader entry points for different shader stages that all 
call into the same shared function. It is therefore important to record not 
just that a function has been scanned, but also in which shader stage context. 
This is done by using ``llvm::DenseMap`` that maps ``FunctionDecl *`` to a 
``unsigned`` bitmap that represents a set of shader stages (or environments) 
the function has been scanned for. The ``N``'th bit in the set is set if the 
function has been scanned in shader environment whose 
``HLSLShaderAttr::ShaderType`` integer value equals ``N``.
+
+The emitted diagnostic messages belong to ``hlsl-availability`` diagnostic 
group and are reported as errors by default. With 
``-Wno-error=hlsl-availability`` flang they become warning, making it relaxed 
HLSL diagnostics mode.
+
+Strict Diagnostic Mode
+--
+
+When strict HLSL availability diagnostic mode is enabled the compiler must 
report all HLSL API availab

[clang-tools-extra] [clang-tidy] Optimize realpath in readability-identifier-naming (PR #92659)

2024-05-18 Thread Piotr Zegar via cfe-commits

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


[clang-tools-extra] [clang-tidy] Optimize realpath in readability-identifier-naming (PR #92659)

2024-05-18 Thread Piotr Zegar via cfe-commits

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


[clang-tools-extra] [clang-tidy] Optimize realpath in readability-identifier-naming (PR #92659)

2024-05-18 Thread Piotr Zegar via cfe-commits

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


[clang-tools-extra] [clang-tidy] Optimize realpath in readability-identifier-naming (PR #92659)

2024-05-18 Thread via cfe-commits

llvmbot wrote:




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

Author: Piotr Zegar (PiotrZSL)


Changes

- Reduce disk IO usage by adding cache to an realpath introduced by #81985
- Refactor HungarianNotation::getDeclTypeName to remove some string copies and 
use more safe string API.

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


2 Files Affected:

- (modified) clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp 
(+35-33) 
- (modified) clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h 
(+2) 


``diff
diff --git a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
index c3208392df156..b2ab6e283c079 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
@@ -305,27 +305,20 @@ std::string 
IdentifierNamingCheck::HungarianNotation::getDeclTypeName(
   auto &SM = VD->getASTContext().getSourceManager();
   const char *Begin = SM.getCharacterData(VD->getBeginLoc());
   const char *End = SM.getCharacterData(VD->getEndLoc());
-  intptr_t StrLen = End - Begin;
+  if (End < Begin)
+return {};
 
   // FIXME: Sometimes the value that returns from ValDecl->getEndLoc()
   // is wrong(out of location of Decl). This causes `StrLen` will be assigned
   // an unexpected large value. Current workaround to find the terminated
   // character instead of the `getEndLoc()` function.
-  const char *EOL = strchr(Begin, '\n');
-  if (!EOL)
-EOL = Begin + strlen(Begin);
-
-  const char *PosList[] = {strchr(Begin, '='), strchr(Begin, ';'),
-   strchr(Begin, ','), strchr(Begin, ')'), EOL};
-  for (const auto &Pos : PosList) {
-if (Pos > Begin)
-  EOL = std::min(EOL, Pos);
-  }
+  llvm::StringRef NameRef(Begin, End - Begin);
+  auto Pos = NameRef.find_first_of("\n\r=;,)");
+  if (Pos != llvm::StringRef::npos)
+NameRef = NameRef.substr(0, Pos);
 
-  StrLen = EOL - Begin;
-  std::string TypeName;
-  if (StrLen > 0) {
-std::string Type(Begin, StrLen);
+  if (!NameRef.empty()) {
+std::string Type(NameRef.begin(), NameRef.end());
 
 static constexpr StringRef Keywords[] = {
 // Constexpr specifiers
@@ -339,66 +332,67 @@ std::string 
IdentifierNamingCheck::HungarianNotation::getDeclTypeName(
 
 // Remove keywords
 for (StringRef Kw : Keywords) {
-  for (size_t Pos = 0;
-   (Pos = Type.find(Kw.data(), Pos)) != std::string::npos;) {
+  for (size_t Pos = 0; (Pos = Type.find(Kw, Pos)) != std::string::npos;) {
 Type.replace(Pos, Kw.size(), "");
   }
 }
-TypeName = Type.erase(0, Type.find_first_not_of(' '));
 
 // Remove template parameters
 const size_t Pos = Type.find('<');
 if (Pos != std::string::npos) {
-  TypeName = Type.erase(Pos, Type.size() - Pos);
+  Type.erase(Pos);
 }
 
 // Replace spaces with single space.
 for (size_t Pos = 0; (Pos = Type.find("  ", Pos)) != std::string::npos;
- Pos += strlen(" ")) {
-  Type.replace(Pos, strlen("  "), " ");
+ Pos += 2U) {
+  Type.replace(Pos, 2U, " ");
 }
 
 // Replace " &" with "&".
 for (size_t Pos = 0; (Pos = Type.find(" &", Pos)) != std::string::npos;
- Pos += strlen("&")) {
-  Type.replace(Pos, strlen(" &"), "&");
+ Pos += 2U) {
+  Type.replace(Pos, 2U, "&");
 }
 
 // Replace " *" with "* ".
 for (size_t Pos = 0; (Pos = Type.find(" *", Pos)) != std::string::npos;
- Pos += strlen("*")) {
-  Type.replace(Pos, strlen(" *"), "* ");
+ Pos += 1U) {
+  Type.replace(Pos, 2U, "* ");
 }
 
+Type.erase(0, Type.find_first_not_of(' '));
+
 // Remove redundant tailing.
 static constexpr StringRef TailsOfMultiWordType[] = {
 " int", " char", " double", " long", " short"};
 bool RedundantRemoved = false;
 for (auto Kw : TailsOfMultiWordType) {
-  size_t Pos = Type.rfind(Kw.data());
+  size_t Pos = Type.rfind(Kw);
   if (Pos != std::string::npos) {
 const size_t PtrCount = getAsteriskCount(Type, ND);
-Type = Type.substr(0, Pos + Kw.size() + PtrCount);
+Type.erase(Pos + Kw.size() + PtrCount);
 RedundantRemoved = true;
 break;
   }
 }
 
-TypeName = Type.erase(0, Type.find_first_not_of(' '));
+Type.erase(0, Type.find_first_not_of(' '));
 if (!RedundantRemoved) {
   std::size_t FoundSpace = Type.find(' ');
   if (FoundSpace != std::string::npos)
 Type = Type.substr(0, FoundSpace);
 }
 
-TypeName = Type.erase(0, Type.find_first_not_of(' '));
+Type.erase(0, Type.find_first_not_of(' '));
 
 QualType QT = VD->getType();
 if (!QT.isNull() && QT->isArrayType())
-  TypeName.append("[]");
+  Type.append("[]");
+return Type;
   }
 
-  return TypeName;
+  return {};
 }
 
 IdentifierNamingCheck::IdentifierNami

[clang-tools-extra] [clang-tidy] Optimize realpath in readability-identifier-naming (PR #92659)

2024-05-18 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL created 
https://github.com/llvm/llvm-project/pull/92659

- Reduce disk IO usage by adding cache to an realpath introduced by #81985
- Refactor HungarianNotation::getDeclTypeName to remove some string copies and 
use more safe string API.

>From 45bce19a4852ab95c882948ea85ba8d87a4eeef2 Mon Sep 17 00:00:00 2001
From: Piotr Zegar 
Date: Sat, 18 May 2024 16:56:31 +
Subject: [PATCH] [clang-tidy] Optimize readability-identifier-naming

- Reduce disk IO usage by adding cache to an realpath
  introduced by #81985
- Refactor HungarianNotation::getDeclTypeName to remove some
  string copies and use more safe string API.
---
 .../readability/IdentifierNamingCheck.cpp | 68 ++-
 .../readability/IdentifierNamingCheck.h   |  2 +
 2 files changed, 37 insertions(+), 33 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
index c3208392df156..b2ab6e283c079 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
@@ -305,27 +305,20 @@ std::string 
IdentifierNamingCheck::HungarianNotation::getDeclTypeName(
   auto &SM = VD->getASTContext().getSourceManager();
   const char *Begin = SM.getCharacterData(VD->getBeginLoc());
   const char *End = SM.getCharacterData(VD->getEndLoc());
-  intptr_t StrLen = End - Begin;
+  if (End < Begin)
+return {};
 
   // FIXME: Sometimes the value that returns from ValDecl->getEndLoc()
   // is wrong(out of location of Decl). This causes `StrLen` will be assigned
   // an unexpected large value. Current workaround to find the terminated
   // character instead of the `getEndLoc()` function.
-  const char *EOL = strchr(Begin, '\n');
-  if (!EOL)
-EOL = Begin + strlen(Begin);
-
-  const char *PosList[] = {strchr(Begin, '='), strchr(Begin, ';'),
-   strchr(Begin, ','), strchr(Begin, ')'), EOL};
-  for (const auto &Pos : PosList) {
-if (Pos > Begin)
-  EOL = std::min(EOL, Pos);
-  }
+  llvm::StringRef NameRef(Begin, End - Begin);
+  auto Pos = NameRef.find_first_of("\n\r=;,)");
+  if (Pos != llvm::StringRef::npos)
+NameRef = NameRef.substr(0, Pos);
 
-  StrLen = EOL - Begin;
-  std::string TypeName;
-  if (StrLen > 0) {
-std::string Type(Begin, StrLen);
+  if (!NameRef.empty()) {
+std::string Type(NameRef.begin(), NameRef.end());
 
 static constexpr StringRef Keywords[] = {
 // Constexpr specifiers
@@ -339,66 +332,67 @@ std::string 
IdentifierNamingCheck::HungarianNotation::getDeclTypeName(
 
 // Remove keywords
 for (StringRef Kw : Keywords) {
-  for (size_t Pos = 0;
-   (Pos = Type.find(Kw.data(), Pos)) != std::string::npos;) {
+  for (size_t Pos = 0; (Pos = Type.find(Kw, Pos)) != std::string::npos;) {
 Type.replace(Pos, Kw.size(), "");
   }
 }
-TypeName = Type.erase(0, Type.find_first_not_of(' '));
 
 // Remove template parameters
 const size_t Pos = Type.find('<');
 if (Pos != std::string::npos) {
-  TypeName = Type.erase(Pos, Type.size() - Pos);
+  Type.erase(Pos);
 }
 
 // Replace spaces with single space.
 for (size_t Pos = 0; (Pos = Type.find("  ", Pos)) != std::string::npos;
- Pos += strlen(" ")) {
-  Type.replace(Pos, strlen("  "), " ");
+ Pos += 2U) {
+  Type.replace(Pos, 2U, " ");
 }
 
 // Replace " &" with "&".
 for (size_t Pos = 0; (Pos = Type.find(" &", Pos)) != std::string::npos;
- Pos += strlen("&")) {
-  Type.replace(Pos, strlen(" &"), "&");
+ Pos += 2U) {
+  Type.replace(Pos, 2U, "&");
 }
 
 // Replace " *" with "* ".
 for (size_t Pos = 0; (Pos = Type.find(" *", Pos)) != std::string::npos;
- Pos += strlen("*")) {
-  Type.replace(Pos, strlen(" *"), "* ");
+ Pos += 1U) {
+  Type.replace(Pos, 2U, "* ");
 }
 
+Type.erase(0, Type.find_first_not_of(' '));
+
 // Remove redundant tailing.
 static constexpr StringRef TailsOfMultiWordType[] = {
 " int", " char", " double", " long", " short"};
 bool RedundantRemoved = false;
 for (auto Kw : TailsOfMultiWordType) {
-  size_t Pos = Type.rfind(Kw.data());
+  size_t Pos = Type.rfind(Kw);
   if (Pos != std::string::npos) {
 const size_t PtrCount = getAsteriskCount(Type, ND);
-Type = Type.substr(0, Pos + Kw.size() + PtrCount);
+Type.erase(Pos + Kw.size() + PtrCount);
 RedundantRemoved = true;
 break;
   }
 }
 
-TypeName = Type.erase(0, Type.find_first_not_of(' '));
+Type.erase(0, Type.find_first_not_of(' '));
 if (!RedundantRemoved) {
   std::size_t FoundSpace = Type.find(' ');
   if (FoundSpace != std::string::npos)
 Type = Type.substr(0, FoundSpace);
 }
 
-TypeName = Type.erase(0, Type.find_first_not_of(' '));
+Type.erase(0,

[clang] [clang] Introduce `SemaCoroutine` (PR #92645)

2024-05-18 Thread via cfe-commits

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

As said in previous comments, I don't think this is the right direction

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


[clang] [llvm] [DebugInfo][BPF] Add 'btf:type_tag' annotation in DWARF (PR #91423)

2024-05-18 Thread via cfe-commits

yonghong-song wrote:

Okay, I see. Thanks for explanation. I checked the top commit and it looks good 
to me. it is very similar to https://reviews.llvm.org/D143967 except a few 
additions like new llvm internal flag and a couple of places to generate type 
tags based on v1 format.

Test "buildkite/github-pull-requests " failed and I don't know what is the 
reason. I think it is worthwhile to rerun the test to ensure all tests passed.


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


[clang] [llvm] [Inliner] Propagate more attributes to params when inlining (PR #91101)

2024-05-18 Thread via cfe-commits


@@ -1352,20 +1352,43 @@ static void AddParamAndFnBasicAttributes(const CallBase 
&CB,
   auto &Context = CalledFunction->getContext();
 
   // Collect valid attributes for all params.
-  SmallVector ValidParamAttrs;
+  SmallVector ValidObjParamAttrs, ValidExactParamAttrs;
   bool HasAttrToPropagate = false;
 
   for (unsigned I = 0, E = CB.arg_size(); I < E; ++I) {
-ValidParamAttrs.emplace_back(AttrBuilder{CB.getContext()});
+ValidObjParamAttrs.emplace_back(AttrBuilder{CB.getContext()});
+ValidExactParamAttrs.emplace_back(AttrBuilder{CB.getContext()});
 // Access attributes can be propagated to any param with the same 
underlying
 // object as the argument.
 if (CB.paramHasAttr(I, Attribute::ReadNone))
-  ValidParamAttrs.back().addAttribute(Attribute::ReadNone);
+  ValidObjParamAttrs.back().addAttribute(Attribute::ReadNone);
 if (CB.paramHasAttr(I, Attribute::ReadOnly))
-  ValidParamAttrs.back().addAttribute(Attribute::ReadOnly);
+  ValidObjParamAttrs.back().addAttribute(Attribute::ReadOnly);
 if (CB.paramHasAttr(I, Attribute::WriteOnly))
-  ValidParamAttrs.back().addAttribute(Attribute::WriteOnly);
-HasAttrToPropagate |= ValidParamAttrs.back().hasAttributes();
+  ValidObjParamAttrs.back().addAttribute(Attribute::WriteOnly);
+
+// Attributes we can only propagate if the exact parameter is forwarded.
+
+// We can propagate both poison generating an UB generating attributes
+// without any extra checks. The only attribute that is tricky to propagate
+// is `noundef` (skipped for now) as that can create new UB where previous

goldsteinn wrote:

Sorry I misread, you can still create new UB in that `noundef` then 
poison-generating attribute is fine, but combined they create immediate UB i.e: 
https://alive2.llvm.org/ce/z/CgBHpb

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


[clang] [clang] Introduce `SemaCoroutine` (PR #92645)

2024-05-18 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

> What is the goal here? there is a lot of code reuse in C++ and C. and having 
> a file per feature is going to make thing worse (maintenance, unboarding, 
> compile times).

Maintenance: one big blob of code which is `Sema` makes it virtually impossible 
to approach long-standing const-correctness issue in a systematic way, because 
enormous flat list of member functions doesn't help you identify the leaves of 
dependency chains to start there.

Onboarding: this effort started with an impression I had that it's almost 
impossible to wrap your head around `Sema` because of its size. This was an 
onboarding problem for me.

Compile times: per measurements taken in 
https://github.com/llvm/llvm-project/pull/84184#issuecomment-1984528598, 
indirection that splitting of `Sema` introduces doesn't have a noticeable 
impact on both our compile times and runtime performance.

> There are a lot more low-hamging fruits we should do before considering that 
> sort of split.

> Wasm, AMD, Builtins, pragmas, random objects which could be in headers ( 
> NestedNameSpecInfo, ContextRAII, NameClassification, AccessCheckingSFINAE, 
> InstantiatingTemplate, SynthesizedFunctionScope, etc - I would recommend 
> using Aliases so they are still functionally in Sema)

Time for that will come. Irrespective of the order we move stuff out of `Sema`, 
the hard parts (basically all the code for C++98 and, likely, C++11) will 
remain, because we haven't come with a plan for them yet. And those will be 
minor wins in terms of volume of code, because OpenMP miracle is unlikely to 
manifest again (when I was able to reduce `Sema.h` by almost 1k LoC).

C++ features not present in C++98 were identified as potential low-hanging 
fruits, because they are implemented on top of what was already there, and 
coroutines were indeed rather easy to factor out. C++20 modules are definitely 
not a low-hanging fruit, though.

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


[clang] [Clang] Fix P2564 handling of variable initializers (PR #89565)

2024-05-18 Thread Daniel M. Katz via cfe-commits

katzdm wrote:

> @katzdm Does it make sense to file an issue so we don't forget to bring the 
> warning back?

Yep, for sure - I've opened #92656.

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


[clang] [clang][AST] Fix end location of DeclarationNameInfo on instantiated methods (PR #92654)

2024-05-18 Thread via cfe-commits

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


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


[clang] [clang] Introduce `SemaCoroutine` (PR #92645)

2024-05-18 Thread via cfe-commits

cor3ntin wrote:

What is the goal here? there is a lot of code reuse in C++ and C. and having a 
file per feature is going to make thing worse (maintenance, unboarding, compile 
times).
There are a lot more low-hamging fruits we should do before considering that 
sort of split.

Wasm, AMD, Builtins,  pragmas, random objects which could be in headers ( 
NestedNameSpecInfo, ContextRAII, NameClassification, AccessCheckingSFINAE,  
InstantiatingTemplate, SynthesizedFunctionScope, etc - I would recommend using 
Aliases so they are still functionally in Sema)

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


[clang] [clang][AST] Fix end location of DeclarationNameInfo on instantiated methods (PR #92654)

2024-05-18 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll commented:

LGTM, but wait for more reviews.

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


[clang] [clang][AST] Fix end location of DeclarationNameInfo on instantiated methods (PR #92654)

2024-05-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Balazs Benics (steakhal)


Changes

Fixes #71161

[D64087](https://reviews.llvm.org/D64087) updated some locations of the 
instantiated method but forgot `DNLoc`.

`FunctionDecl::getNameInfo()` constructs a `DeclarationNameInfo` using 
`Decl::Loc` as the beginning of the declaration name, and `FunctionDecl::DNLoc` 
to compute the end of the declaration name. The former was updated, but the 
latter was not, so `DeclarationName::getSourceRange()` would return a range 
where the end of the declaration name could come before its beginning.

Patch by Alejandro Alvarez Ayllon
Co-authored-by: steakhal

CPP-5166

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


3 Files Affected:

- (modified) clang/include/clang/AST/Decl.h (+2) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+1) 
- (modified) clang/unittests/AST/DeclTest.cpp (+31) 


``diff
diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 5e485ccb85a13..7fd80b90d1033 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -2188,6 +2188,8 @@ class FunctionDecl : public DeclaratorDecl,
 
   void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
 
+  void setDeclarationNameLoc(DeclarationNameLoc L) { DNLoc = L; }
+
   /// Returns the location of the ellipsis of a variadic function.
   SourceLocation getEllipsisLoc() const {
 const auto *FPT = getType()->getAs();
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 381d79b2fcd46..6d736d0771eac 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -5055,6 +5055,7 @@ void Sema::InstantiateFunctionDefinition(SourceLocation 
PointOfInstantiation,
   Function->setLocation(PatternDecl->getLocation());
   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
   Function->setRangeEnd(PatternDecl->getEndLoc());
+  Function->setDeclarationNameLoc(PatternDecl->getNameInfo().getInfo());
 
   EnterExpressionEvaluationContext EvalContext(
   *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
diff --git a/clang/unittests/AST/DeclTest.cpp b/clang/unittests/AST/DeclTest.cpp
index 2530ce74eb6a3..16aa2b50b7a06 100644
--- a/clang/unittests/AST/DeclTest.cpp
+++ b/clang/unittests/AST/DeclTest.cpp
@@ -545,3 +545,34 @@ TEST(Decl, TemplateArgumentDefaulted) {
   EXPECT_TRUE(ArgList.get(2).getIsDefaulted());
   EXPECT_TRUE(ArgList.get(3).getIsDefaulted());
 }
+
+TEST(Decl, CXXDestructorDeclsShouldHaveWellFormedNameInfoRanges) {
+  // GH71161
+  llvm::Annotations Code(R"cpp(
+template  struct Resource {
+  ~Resource(); // 1
+};
+template 
+Resource::~Resource() {} // 2,3
+
+void instantiate_template() {
+  Resource x;
+}
+)cpp");
+
+  auto AST = tooling::buildASTFromCode(Code.code());
+  ASTContext &Ctx = AST->getASTContext();
+
+  const auto &SM = Ctx.getSourceManager();
+  auto GetNameInfoRange = [&SM](const BoundNodes &Match) {
+const auto *D = Match.getNodeAs("dtor");
+return D->getNameInfo().getSourceRange().printToString(SM);
+  };
+
+  auto Matches = match(findAll(cxxDestructorDecl().bind("dtor")),
+   *Ctx.getTranslationUnitDecl(), Ctx);
+  ASSERT_EQ(Matches.size(), 3U);
+  EXPECT_EQ(GetNameInfoRange(Matches[0]), "");
+  EXPECT_EQ(GetNameInfoRange(Matches[1]), "");
+  EXPECT_EQ(GetNameInfoRange(Matches[2]), "");
+}

``




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


[clang] [clang][AST] Fix end location of DeclarationNameInfo on instantiated methods (PR #92654)

2024-05-18 Thread Balazs Benics via cfe-commits

https://github.com/steakhal created 
https://github.com/llvm/llvm-project/pull/92654

Fixes #71161

[D64087](https://reviews.llvm.org/D64087) updated some locations of the 
instantiated method but forgot `DNLoc`.

`FunctionDecl::getNameInfo()` constructs a `DeclarationNameInfo` using 
`Decl::Loc` as the beginning of the declaration name, and `FunctionDecl::DNLoc` 
to compute the end of the declaration name. The former was updated, but the 
latter was not, so `DeclarationName::getSourceRange()` would return a range 
where the end of the declaration name could come before its beginning.

Patch by Alejandro Alvarez Ayllon
Co-authored-by: steakhal

CPP-5166

>From 58ca4d9be1dbc43ad40b6e26b8a5d79e20be8d93 Mon Sep 17 00:00:00 2001
From: Alejandro _lvarez Ayll_n 
Date: Sat, 18 May 2024 16:53:33 +0200
Subject: [PATCH] [clang][AST] Fix end location of DeclarationNameInfo on
 instantiated methods

Fixes #71161

[D64087](https://reviews.llvm.org/D64087) updated some locations of the
instantiated method but forgot `DNLoc`.

`FunctionDecl::getNameInfo()` constructs a `DeclarationNameInfo` using
`Decl::Loc` as the beginning of the declaration name, and
`FunctionDecl::DNLoc` to compute the end of the declaration name. The
former was updated, but the latter was not, so
`DeclarationName::getSourceRange()` would return a range where the end
of the declaration name could come before its beginning.

Patch by Alejandro Alvarez Ayllon
Co-authored-by: steakhal

CPP-5166
---
 clang/include/clang/AST/Decl.h|  2 ++
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  1 +
 clang/unittests/AST/DeclTest.cpp  | 31 +++
 3 files changed, 34 insertions(+)

diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 5e485ccb85a13..7fd80b90d1033 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -2188,6 +2188,8 @@ class FunctionDecl : public DeclaratorDecl,
 
   void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
 
+  void setDeclarationNameLoc(DeclarationNameLoc L) { DNLoc = L; }
+
   /// Returns the location of the ellipsis of a variadic function.
   SourceLocation getEllipsisLoc() const {
 const auto *FPT = getType()->getAs();
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 381d79b2fcd46..6d736d0771eac 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -5055,6 +5055,7 @@ void Sema::InstantiateFunctionDefinition(SourceLocation 
PointOfInstantiation,
   Function->setLocation(PatternDecl->getLocation());
   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
   Function->setRangeEnd(PatternDecl->getEndLoc());
+  Function->setDeclarationNameLoc(PatternDecl->getNameInfo().getInfo());
 
   EnterExpressionEvaluationContext EvalContext(
   *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
diff --git a/clang/unittests/AST/DeclTest.cpp b/clang/unittests/AST/DeclTest.cpp
index 2530ce74eb6a3..16aa2b50b7a06 100644
--- a/clang/unittests/AST/DeclTest.cpp
+++ b/clang/unittests/AST/DeclTest.cpp
@@ -545,3 +545,34 @@ TEST(Decl, TemplateArgumentDefaulted) {
   EXPECT_TRUE(ArgList.get(2).getIsDefaulted());
   EXPECT_TRUE(ArgList.get(3).getIsDefaulted());
 }
+
+TEST(Decl, CXXDestructorDeclsShouldHaveWellFormedNameInfoRanges) {
+  // GH71161
+  llvm::Annotations Code(R"cpp(
+template  struct Resource {
+  ~Resource(); // 1
+};
+template 
+Resource::~Resource() {} // 2,3
+
+void instantiate_template() {
+  Resource x;
+}
+)cpp");
+
+  auto AST = tooling::buildASTFromCode(Code.code());
+  ASTContext &Ctx = AST->getASTContext();
+
+  const auto &SM = Ctx.getSourceManager();
+  auto GetNameInfoRange = [&SM](const BoundNodes &Match) {
+const auto *D = Match.getNodeAs("dtor");
+return D->getNameInfo().getSourceRange().printToString(SM);
+  };
+
+  auto Matches = match(findAll(cxxDestructorDecl().bind("dtor")),
+   *Ctx.getTranslationUnitDecl(), Ctx);
+  ASSERT_EQ(Matches.size(), 3U);
+  EXPECT_EQ(GetNameInfoRange(Matches[0]), "");
+  EXPECT_EQ(GetNameInfoRange(Matches[1]), "");
+  EXPECT_EQ(GetNameInfoRange(Matches[2]), "");
+}

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


[clang] [clang] Introduce `SemaCoroutine` (PR #92645)

2024-05-18 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

As @erichkeane described it, we're clearing the woods of "core" C++ 
functionality before dealing with the hard parts, like `SemaDeclCXX.cpp` or 
`SemaChecking.cpp`.
Actual LoC wins are secondary, as they have been all along.

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


[clang] [clang] Introduce `SemaExceptionSpec` (PR #92653)

2024-05-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Vlad Serebrennikov (Endilll)


Changes

This patch moves `Sema` functions that handle exception specification into the 
new `SemaExceptionSpec` class. This continues previous efforts to split `Sema` 
up. Additional context can be found in 
https://github.com/llvm/llvm-project/pull/84184.

I also moved several exception specification-related function from 
`SemaDeclCXX.cpp` to `SemaExceptionSpec`, but not all of them. The rest rely on 
TU-local entities in `SemaDeclCXX.cpp` that are shared with the code not 
related to exception specification.

As usual, in order to help reviewing this, formatting changes are split into a 
separate commit.

---

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


21 Files Affected:

- (modified) clang/include/clang/Sema/Sema.h (+28-159) 
- (added) clang/include/clang/Sema/SemaExceptionSpec.h (+187) 
- (modified) clang/lib/Parse/ParseCXXInlineMethods.cpp (+5-6) 
- (modified) clang/lib/Parse/ParseDecl.cpp (+3-1) 
- (modified) clang/lib/Parse/ParseDeclCXX.cpp (+3-2) 
- (modified) clang/lib/Sema/AnalysisBasedWarnings.cpp (+4-2) 
- (modified) clang/lib/Sema/Sema.cpp (+7-5) 
- (modified) clang/lib/Sema/SemaCoroutine.cpp (+3-1) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+7-6) 
- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+26-206) 
- (modified) clang/lib/Sema/SemaExceptionSpec.cpp (+350-106) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+4-2) 
- (modified) clang/lib/Sema/SemaExprCXX.cpp (+14-12) 
- (modified) clang/lib/Sema/SemaExprMember.cpp (+3-1) 
- (modified) clang/lib/Sema/SemaInit.cpp (+5-2) 
- (modified) clang/lib/Sema/SemaOverload.cpp (+4-3) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+4-2) 
- (modified) clang/lib/Sema/SemaTemplateInstantiate.cpp (+29-1) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+6-4) 
- (modified) clang/lib/Sema/SemaType.cpp (+12-11) 
- (modified) clang/lib/Sema/TreeTransform.h (+6-3) 


``diff
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d4d4a82525a02..95a54014cf672 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -169,6 +169,7 @@ class PseudoObjectExpr;
 class QualType;
 class SemaCodeCompletion;
 class SemaCUDA;
+class SemaExceptionSpec;
 class SemaHLSL;
 class SemaObjC;
 class SemaOpenACC;
@@ -461,29 +462,28 @@ class Sema final : public SemaBase {
   // 9. Declarations (SemaDecl.cpp)
   // 10. Declaration Attribute Handling (SemaDeclAttr.cpp)
   // 11. C++ Declarations (SemaDeclCXX.cpp)
-  // 12. C++ Exception Specifications (SemaExceptionSpec.cpp)
-  // 13. Expressions (SemaExpr.cpp)
-  // 14. C++ Expressions (SemaExprCXX.cpp)
-  // 15. Member Access Expressions (SemaExprMember.cpp)
-  // 16. Initializers (SemaInit.cpp)
-  // 17. C++ Lambda Expressions (SemaLambda.cpp)
-  // 18. Name Lookup (SemaLookup.cpp)
-  // 19. Modules (SemaModule.cpp)
-  // 20. C++ Overloading (SemaOverload.cpp)
-  // 21. Pseudo-Object (SemaPseudoObject.cpp)
-  // 22. Statements (SemaStmt.cpp)
-  // 23. `inline asm` Statement (SemaStmtAsm.cpp)
-  // 24. Statement Attribute Handling (SemaStmtAttr.cpp)
-  // 25. C++ Templates (SemaTemplate.cpp)
-  // 26. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
-  // 27. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
-  // 28. C++ Template Declaration Instantiation
+  // 12. Expressions (SemaExpr.cpp)
+  // 13. C++ Expressions (SemaExprCXX.cpp)
+  // 14. Member Access Expressions (SemaExprMember.cpp)
+  // 15. Initializers (SemaInit.cpp)
+  // 16. C++ Lambda Expressions (SemaLambda.cpp)
+  // 17. Name Lookup (SemaLookup.cpp)
+  // 18. Modules (SemaModule.cpp)
+  // 19. C++ Overloading (SemaOverload.cpp)
+  // 20. Pseudo-Object (SemaPseudoObject.cpp)
+  // 21. Statements (SemaStmt.cpp)
+  // 22. `inline asm` Statement (SemaStmtAsm.cpp)
+  // 23. Statement Attribute Handling (SemaStmtAttr.cpp)
+  // 24. C++ Templates (SemaTemplate.cpp)
+  // 25. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
+  // 26. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
+  // 27. C++ Template Declaration Instantiation
   // (SemaTemplateInstantiateDecl.cpp)
-  // 29. C++ Variadic Templates (SemaTemplateVariadic.cpp)
-  // 30. Constraints and Concepts (SemaConcept.cpp)
-  // 31. Types (SemaType.cpp)
-  // 32. FixIt Helpers (SemaFixItUtils.cpp)
-  // 33. Name Lookup for RISC-V Vector Intrinsic (SemaRISCVVectorLookup.cpp)
+  // 28. C++ Variadic Templates (SemaTemplateVariadic.cpp)
+  // 29. Constraints and Concepts (SemaConcept.cpp)
+  // 30. Types (SemaType.cpp)
+  // 31. FixIt Helpers (SemaFixItUtils.cpp)
+  // 32. Name Lookup for RISC-V Vector Intrinsic (SemaRISCVVectorLookup.cpp)
 
   /// \name Semantic Analysis
   /// Implementations are in Sema.cpp
@@ -994,6 +994,11 @@ class Sema final : public SemaBase {
 return *CUDAPtr;
   }
 
+  SemaExceptionSpec &ExceptionSpec() {
+assert(Ex

[clang] [clang] Introduce `SemaCoroutine` (PR #92645)

2024-05-18 Thread via cfe-commits

cor3ntin wrote:

Thanks! However, I am fairly against moving C and C++ features out of Sema, 
especially when the outcome is 50 Loc kess, at the cost of not knowing where to 
put or find things in the long term (as we add coroutines adjacent features, or 
code related to both coroutines and something else).

The previous sema changes made sense (despite the inevitable churn) - I am not 
sure this one does

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


[clang] [Bounds-Safety] Reserve slot in SanitizerHandler enum for Bounds-Safety (PR #91032)

2024-05-18 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka commented:

LGTM

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


[clang] [clang][analyzer] Move checker alpha.security.cert.pos.34c into security.PutenvWithAuto (PR #92424)

2024-05-18 Thread Balazs Benics via cfe-commits
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= 
Message-ID:
In-Reply-To: 


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


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


[clang] [clang][analyzer] Move checker alpha.security.cert.pos.34c into security.PutenvWithAuto (PR #92424)

2024-05-18 Thread Balazs Benics via cfe-commits
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 


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


[clang] [clang][analyzer] Move checker alpha.security.cert.pos.34c into security.PutenvWithAuto (PR #92424)

2024-05-18 Thread Balazs Benics via cfe-commits
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 



@@ -2792,6 +2792,31 @@ Warn on mmap() calls that are both writable and 
executable.
//   code
  }
 
+.. _alpha-security-putenv-stack-array:
+
+alpha.security.PutenvStackArray
+"""

steakhal wrote:

```suggestion
alpha.security.PutenvStackArray (C)
"""
```

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


[clang] [clang][analyzer] Move checker alpha.security.cert.pos.34c into security.PutenvWithAuto (PR #92424)

2024-05-18 Thread Balazs Benics via cfe-commits
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 



@@ -2792,6 +2792,31 @@ Warn on mmap() calls that are both writable and 
executable.
//   code
  }
 
+.. _alpha-security-putenv-stack-array:
+
+alpha.security.PutenvStackArray
+"""
+Finds calls to the ``putenv`` function which pass a pointer to a 
stack-allocated
+(automatic) array as the argument. Function ``putenv`` does not copy the passed
+string, only a pointer to the data is stored and this data can be read even by
+other threads. Content of a stack-allocated array is likely to be overwritten
+after returning from the parent function.
+
+The problem can be solved by using a static array variable or dynamically
+allocated memory. Even better is to avoid using ``putenv`` (it has other
+problems related to memory leaks) and use ``setenv`` instead.
+
+The check corresponds to CERT rule
+`POS34-C. Do not call putenv() with a pointer to an automatic variable as the 
argument
+`_.
+
+.. code-block:: c
+
+  int f() {
+char[] env = "NAME=value";

steakhal wrote:

```suggestion
char env[] = "NAME=value";
```

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


[clang] [llvm] [AArch64] Merge duplicate extension information. (PR #92319)

2024-05-18 Thread Alexandros Lamprineas via cfe-commits


@@ -94,19 +94,21 @@ static void EmitARMTargetDef(RecordKeeper &RK, raw_ostream 
&OS) {
 else
   OS << ", \"" << Alias << "\"";
 OS << ", AArch64::" << AEK;
-if (AEK == "AEK_NONE") {
+auto Name = Rec->getValueAsString("Name");
+if (Name.empty()) {

labrinea wrote:

No, for example all the features I have fused  (FEAT_DPB, FEAT_DPB2, 
FEAT_FLAGM2, FEAT_FRINTTS, FEAT_RCPC2) as well as BTI, are FMVOnly and still 
have a valid +/- TargetFeatureName.

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


[clang] [llvm] [AArch64] Merge duplicate extension information. (PR #92319)

2024-05-18 Thread Alexandros Lamprineas via cfe-commits


@@ -56,43 +52,64 @@ class Extension<
 
 // The FMV priority
 int FMVPriority = _FMVPriority;
+
+// Indicates if the extension is available on the command line.
+string IsFMVOnly = _IsFMVOnly;

labrinea wrote:

We want the ExtensionInfo field to be of type bool. Can we do the type 
conversation in the emitter? If so okay

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


[clang] [llvm] [AArch64] Merge duplicate extension information. (PR #92319)

2024-05-18 Thread Alexandros Lamprineas via cfe-commits


@@ -56,43 +52,64 @@ class Extension<
 
 // The FMV priority
 int FMVPriority = _FMVPriority;
+
+// Indicates if the extension is available on the command line.
+string IsFMVOnly = _IsFMVOnly;
 }
 
 // Some extensions are available for FMV but can not be controlled via the
-// command line. These entries:
-//  - are SubtargetFeatures, so they have (unused) FieldNames on the subtarget
-//e.g. HasFMVOnlyFEAT_XYZ
-//  - have incorrect (empty) Implies fields, because the code that handles FMV
-//ignores these dependencies and looks only at FMVDependencies.
-//  - have no description.
-// 
-// In the generated data structures for extensions (ExtensionInfo), AEK_NONE is
-// used to indicate that a feature is FMV only. Therefore ArchExtKindSpelling 
is
-// manually overridden here.
-class FMVOnlyExtension
-  : Extension {
-let ArchExtKindSpelling = "AEK_NONE"; // AEK_NONE indicates FMV-only 
feature
-}
+// command line, neither have a TargetFeatureName. Since they have no effect
+// on their own, their description is left empty. However they can have side
+// effects by implying other Subtarget Features. These extensions are used
+// in FMV for detection purposes.
+
+let MArchName = "dgh" in
+def : Extension<"", "DGH", "", [], "FEAT_DGH", "", 260, "true">;

labrinea wrote:

Then what makes an Extension with IsFMVOnly=1 different from and 
FMVOnlyExtesion? I believe this will create more confusion. As I explained we 
don't want any extension to be of AEK_NONE type, in order to be able to express 
dependencies.

Do you want to rename the FMVOnlyExtesion class into something else making it 
differ from Extension only for not having a TargetFeatureName?

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


[clang] [clang] Introduce `SemaPseudoObject` (PR #92646)

2024-05-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Vlad Serebrennikov (Endilll)


Changes

This patch moves `Sema` functions that handle pseudo-objects into the new 
`SemaPseudoObject` class. This continues previous efforts to split `Sema` up. 
Additional context can be found in #84184.
As usual, in order to help reviewing this, formatting changes are split into a 
separate commit.

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


6 Files Affected:

- (modified) clang/include/clang/Sema/Sema.h (+21-36) 
- (added) clang/include/clang/Sema/SemaPseudoObject.h (+40) 
- (modified) clang/lib/Sema/Sema.cpp (+2) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+5-4) 
- (modified) clang/lib/Sema/SemaPseudoObject.cpp (+39-36) 
- (modified) clang/lib/Sema/TreeTransform.h (+5-4) 


``diff
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d4d4a82525a02..9d26a48dd213a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -173,6 +173,7 @@ class SemaHLSL;
 class SemaObjC;
 class SemaOpenACC;
 class SemaOpenMP;
+class SemaPseudoObject;
 class SemaSYCL;
 class StandardConversionSequence;
 class Stmt;
@@ -470,20 +471,19 @@ class Sema final : public SemaBase {
   // 18. Name Lookup (SemaLookup.cpp)
   // 19. Modules (SemaModule.cpp)
   // 20. C++ Overloading (SemaOverload.cpp)
-  // 21. Pseudo-Object (SemaPseudoObject.cpp)
-  // 22. Statements (SemaStmt.cpp)
-  // 23. `inline asm` Statement (SemaStmtAsm.cpp)
-  // 24. Statement Attribute Handling (SemaStmtAttr.cpp)
-  // 25. C++ Templates (SemaTemplate.cpp)
-  // 26. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
-  // 27. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
-  // 28. C++ Template Declaration Instantiation
+  // 21. Statements (SemaStmt.cpp)
+  // 22. `inline asm` Statement (SemaStmtAsm.cpp)
+  // 23. Statement Attribute Handling (SemaStmtAttr.cpp)
+  // 24. C++ Templates (SemaTemplate.cpp)
+  // 25. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
+  // 26. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
+  // 27. C++ Template Declaration Instantiation
   // (SemaTemplateInstantiateDecl.cpp)
-  // 29. C++ Variadic Templates (SemaTemplateVariadic.cpp)
-  // 30. Constraints and Concepts (SemaConcept.cpp)
-  // 31. Types (SemaType.cpp)
-  // 32. FixIt Helpers (SemaFixItUtils.cpp)
-  // 33. Name Lookup for RISC-V Vector Intrinsic (SemaRISCVVectorLookup.cpp)
+  // 28. C++ Variadic Templates (SemaTemplateVariadic.cpp)
+  // 29. Constraints and Concepts (SemaConcept.cpp)
+  // 30. Types (SemaType.cpp)
+  // 31. FixIt Helpers (SemaFixItUtils.cpp)
+  // 32. Name Lookup for RISC-V Vector Intrinsic (SemaRISCVVectorLookup.cpp)
 
   /// \name Semantic Analysis
   /// Implementations are in Sema.cpp
@@ -1014,6 +1014,11 @@ class Sema final : public SemaBase {
 return *OpenMPPtr;
   }
 
+  SemaPseudoObject &PseudoObject() {
+assert(PseudoObjectPtr);
+return *PseudoObjectPtr;
+  }
+
   SemaSYCL &SYCL() {
 assert(SYCLPtr);
 return *SYCLPtr;
@@ -1055,6 +1060,7 @@ class Sema final : public SemaBase {
   std::unique_ptr ObjCPtr;
   std::unique_ptr OpenACCPtr;
   std::unique_ptr OpenMPPtr;
+  std::unique_ptr PseudoObjectPtr;
   std::unique_ptr SYCLPtr;
 
   ///@}
@@ -6370,6 +6376,8 @@ class Sema final : public SemaBase {
   llvm::SmallVector, 1>
   ImplicitlyRetainedSelfLocs;
 
+  void maybeExtendBlockObject(ExprResult &E);
+
 private:
   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind 
Kind);
 
@@ -8368,29 +8376,6 @@ class Sema final : public SemaBase {
   //
   //
 
-  /// \name Pseudo-Object
-  /// Implementations are in SemaPseudoObject.cpp
-  ///@{
-
-public:
-  void maybeExtendBlockObject(ExprResult &E);
-
-  ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
- UnaryOperatorKind Opcode, Expr *Op);
-  ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
- BinaryOperatorKind Opcode, Expr *LHS,
- Expr *RHS);
-  ExprResult checkPseudoObjectRValue(Expr *E);
-  Expr *recreateSyntacticForm(PseudoObjectExpr *E);
-
-  ///@}
-
-  //
-  //
-  // -
-  //
-  //
-
   /// \name Statements
   /// Implementations are in SemaStmt.cpp
   ///@{
diff --git a/clang/include/clang/Sema/SemaPseudoObject.h 
b/clang/include/clang/Sema/SemaPseudoObject.h
new file mode 100644
index 0..22d8be2b3726e
--- /dev/null
+++ b/clang/include/clang/Sema/SemaPseudoObject.h
@@ -0,0 +1,40 @@
+//===- SemaPseudoObject.h --- Semantic Analysis for Pseudo-Objects 
===//
+//
+// 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
+//
+//===--

[clang] [clang] Introduce `SemaPseudoObject` (PR #92646)

2024-05-18 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll created 
https://github.com/llvm/llvm-project/pull/92646

This patch moves `Sema` functions that handle pseudo-objects into the new 
`SemaPseudoObject` class. This continues previous efforts to split `Sema` up. 
Additional context can be found in #84184.
As usual, in order to help reviewing this, formatting changes are split into a 
separate commit.

>From 81b2c7dbb6fb9cb24d560b6069f60ba3452bbf2a Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Sat, 18 May 2024 14:20:43 +0300
Subject: [PATCH 1/2] [clang] Introduce `SemaPseudoObject`

---
 clang/include/clang/Sema/Sema.h | 57 +++---
 clang/include/clang/Sema/SemaPseudoObject.h | 41 +
 clang/lib/Sema/Sema.cpp |  2 +
 clang/lib/Sema/SemaExpr.cpp |  9 +--
 clang/lib/Sema/SemaPseudoObject.cpp | 65 +++--
 clang/lib/Sema/TreeTransform.h  |  7 ++-
 6 files changed, 107 insertions(+), 74 deletions(-)
 create mode 100644 clang/include/clang/Sema/SemaPseudoObject.h

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d4d4a82525a02..9d26a48dd213a 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -173,6 +173,7 @@ class SemaHLSL;
 class SemaObjC;
 class SemaOpenACC;
 class SemaOpenMP;
+class SemaPseudoObject;
 class SemaSYCL;
 class StandardConversionSequence;
 class Stmt;
@@ -470,20 +471,19 @@ class Sema final : public SemaBase {
   // 18. Name Lookup (SemaLookup.cpp)
   // 19. Modules (SemaModule.cpp)
   // 20. C++ Overloading (SemaOverload.cpp)
-  // 21. Pseudo-Object (SemaPseudoObject.cpp)
-  // 22. Statements (SemaStmt.cpp)
-  // 23. `inline asm` Statement (SemaStmtAsm.cpp)
-  // 24. Statement Attribute Handling (SemaStmtAttr.cpp)
-  // 25. C++ Templates (SemaTemplate.cpp)
-  // 26. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
-  // 27. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
-  // 28. C++ Template Declaration Instantiation
+  // 21. Statements (SemaStmt.cpp)
+  // 22. `inline asm` Statement (SemaStmtAsm.cpp)
+  // 23. Statement Attribute Handling (SemaStmtAttr.cpp)
+  // 24. C++ Templates (SemaTemplate.cpp)
+  // 25. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
+  // 26. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
+  // 27. C++ Template Declaration Instantiation
   // (SemaTemplateInstantiateDecl.cpp)
-  // 29. C++ Variadic Templates (SemaTemplateVariadic.cpp)
-  // 30. Constraints and Concepts (SemaConcept.cpp)
-  // 31. Types (SemaType.cpp)
-  // 32. FixIt Helpers (SemaFixItUtils.cpp)
-  // 33. Name Lookup for RISC-V Vector Intrinsic (SemaRISCVVectorLookup.cpp)
+  // 28. C++ Variadic Templates (SemaTemplateVariadic.cpp)
+  // 29. Constraints and Concepts (SemaConcept.cpp)
+  // 30. Types (SemaType.cpp)
+  // 31. FixIt Helpers (SemaFixItUtils.cpp)
+  // 32. Name Lookup for RISC-V Vector Intrinsic (SemaRISCVVectorLookup.cpp)
 
   /// \name Semantic Analysis
   /// Implementations are in Sema.cpp
@@ -1014,6 +1014,11 @@ class Sema final : public SemaBase {
 return *OpenMPPtr;
   }
 
+  SemaPseudoObject &PseudoObject() {
+assert(PseudoObjectPtr);
+return *PseudoObjectPtr;
+  }
+
   SemaSYCL &SYCL() {
 assert(SYCLPtr);
 return *SYCLPtr;
@@ -1055,6 +1060,7 @@ class Sema final : public SemaBase {
   std::unique_ptr ObjCPtr;
   std::unique_ptr OpenACCPtr;
   std::unique_ptr OpenMPPtr;
+  std::unique_ptr PseudoObjectPtr;
   std::unique_ptr SYCLPtr;
 
   ///@}
@@ -6370,6 +6376,8 @@ class Sema final : public SemaBase {
   llvm::SmallVector, 1>
   ImplicitlyRetainedSelfLocs;
 
+  void maybeExtendBlockObject(ExprResult &E);
+
 private:
   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind 
Kind);
 
@@ -8368,29 +8376,6 @@ class Sema final : public SemaBase {
   //
   //
 
-  /// \name Pseudo-Object
-  /// Implementations are in SemaPseudoObject.cpp
-  ///@{
-
-public:
-  void maybeExtendBlockObject(ExprResult &E);
-
-  ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
- UnaryOperatorKind Opcode, Expr *Op);
-  ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
- BinaryOperatorKind Opcode, Expr *LHS,
- Expr *RHS);
-  ExprResult checkPseudoObjectRValue(Expr *E);
-  Expr *recreateSyntacticForm(PseudoObjectExpr *E);
-
-  ///@}
-
-  //
-  //
-  // -
-  //
-  //
-
   /// \name Statements
   /// Implementations are in SemaStmt.cpp
   ///@{
diff --git a/clang/include/clang/Sema/SemaPseudoObject.h 
b/clang/include/clang/Sema/SemaPseudoObject.h
new file mode 100644
index 0..f1f4dc07cf1c1
--- /dev/null
+++ b/clang/include/clang/Sema/SemaPseudoObject.h
@@ -0,0 +1,41 @@
+//===- SemaPseudoObject.h --- Semantic Analysis for Pseudo-Objects 

[clang] [clang] Introduce `SemaCoroutine` (PR #92645)

2024-05-18 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/92645

>From 4fe09a3411e54561857d2f9d8c1808cb2728e299 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Sat, 18 May 2024 13:33:04 +0300
Subject: [PATCH 1/3] [clang] Introduce `SemaCoroutine`

---
 clang/include/clang/Sema/Sema.h  |  58 +-
 clang/include/clang/Sema/SemaCoroutine.h |  73 
 clang/lib/Parse/ParseExpr.cpp|   3 +-
 clang/lib/Parse/ParseExprCXX.cpp |   3 +-
 clang/lib/Parse/ParseStmt.cpp|   3 +-
 clang/lib/Sema/Sema.cpp  |   4 +-
 clang/lib/Sema/SemaCoroutine.cpp | 218 ---
 clang/lib/Sema/SemaDecl.cpp  |  16 +-
 clang/lib/Sema/SemaStmt.cpp  |   9 +-
 clang/lib/Sema/TreeTransform.h   |  25 +--
 10 files changed, 227 insertions(+), 185 deletions(-)
 create mode 100644 clang/include/clang/Sema/SemaCoroutine.h

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d4d4a82525a02..1d0fbeacfe061 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -168,6 +168,7 @@ class PseudoDestructorTypeStorage;
 class PseudoObjectExpr;
 class QualType;
 class SemaCodeCompletion;
+class SemaCoroutine;
 class SemaCUDA;
 class SemaHLSL;
 class SemaObjC;
@@ -989,6 +990,11 @@ class Sema final : public SemaBase {
 return *CodeCompletionPtr;
   }
 
+  SemaCoroutine &Coroutine() {
+assert(CoroutinePtr);
+return *CoroutinePtr;
+  }
+
   SemaCUDA &CUDA() {
 assert(CUDAPtr);
 return *CUDAPtr;
@@ -1050,6 +1056,7 @@ class Sema final : public SemaBase {
   mutable IdentifierInfo *Ident_super;
 
   std::unique_ptr CodeCompletionPtr;
+  std::unique_ptr CoroutinePtr;
   std::unique_ptr CUDAPtr;
   std::unique_ptr HLSLPtr;
   std::unique_ptr ObjCPtr;
@@ -2267,57 +2274,6 @@ class Sema final : public SemaBase {
   //
   //
 
-  /// \name C++ Coroutines
-  /// Implementations are in SemaCoroutine.cpp
-  ///@{
-
-public:
-  /// The C++ "std::coroutine_traits" template, which is defined in
-  /// \
-  ClassTemplateDecl *StdCoroutineTraitsCache;
-
-  bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
-   StringRef Keyword);
-  ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
-  ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
-  StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
-
-  ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
-  ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
-  UnresolvedLookupExpr *Lookup);
-  ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
-  Expr *Awaiter, bool IsImplicit = false);
-  ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
-UnresolvedLookupExpr *Lookup);
-  ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
-  StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
-   bool IsImplicit = false);
-  StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
-  bool buildCoroutineParameterMoves(SourceLocation Loc);
-  VarDecl *buildCoroutinePromise(SourceLocation Loc);
-  void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
-
-  // As a clang extension, enforces that a non-coroutine function must be 
marked
-  // with [[clang::coro_wrapper]] if it returns a type marked with
-  // [[clang::coro_return_type]].
-  // Expects that FD is not a coroutine.
-  void CheckCoroutineWrapper(FunctionDecl *FD);
-  /// Lookup 'coroutine_traits' in std namespace and std::experimental
-  /// namespace. The namespace found is recorded in Namespace.
-  ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
-   SourceLocation FuncLoc);
-  /// Check that the expression co_await promise.final_suspend() shall not be
-  /// potentially-throwing.
-  bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
-
-  ///@}
-
-  //
-  //
-  // -
-  //
-  //
-
   /// \name C++ Scope Specifiers
   /// Implementations are in SemaCXXScopeSpec.cpp
   ///@{
diff --git a/clang/include/clang/Sema/SemaCoroutine.h 
b/clang/include/clang/Sema/SemaCoroutine.h
new file mode 100644
index 0..20f1fffc970f8
--- /dev/null
+++ b/clang/include/clang/Sema/SemaCoroutine.h
@@ -0,0 +1,73 @@
+//===- SemaCUDA.h - Semantic Analysis for C++20 coroutines 
===//
+//
+// 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
+//
+//===--===//
+/// \file
+/// This fil

[clang] [clang] Introduce `SemaCoroutine` (PR #92645)

2024-05-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-coroutines

Author: Vlad Serebrennikov (Endilll)


Changes

This patch moves coroutines-specific `Sema` functions into the new 
`SemaCoroutine` class. This continues previous efforts to split `Sema` up. 
Additional context can be found in #84184.
As usual, in order to help reviewing this, formatting changes are split into a 
separate commit.

---

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


10 Files Affected:

- (modified) clang/include/clang/Sema/Sema.h (+7-51) 
- (added) clang/include/clang/Sema/SemaCoroutine.h (+73) 
- (modified) clang/lib/Parse/ParseExpr.cpp (+3-1) 
- (modified) clang/lib/Parse/ParseExprCXX.cpp (+2-1) 
- (modified) clang/lib/Parse/ParseStmt.cpp (+3-1) 
- (modified) clang/lib/Sema/Sema.cpp (+4-2) 
- (modified) clang/lib/Sema/SemaCoroutine.cpp (+153-120) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+3-13) 
- (modified) clang/lib/Sema/SemaStmt.cpp (+6-5) 
- (modified) clang/lib/Sema/TreeTransform.h (+17-14) 


``diff
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d4d4a82525a02..1d0fbeacfe061 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -168,6 +168,7 @@ class PseudoDestructorTypeStorage;
 class PseudoObjectExpr;
 class QualType;
 class SemaCodeCompletion;
+class SemaCoroutine;
 class SemaCUDA;
 class SemaHLSL;
 class SemaObjC;
@@ -989,6 +990,11 @@ class Sema final : public SemaBase {
 return *CodeCompletionPtr;
   }
 
+  SemaCoroutine &Coroutine() {
+assert(CoroutinePtr);
+return *CoroutinePtr;
+  }
+
   SemaCUDA &CUDA() {
 assert(CUDAPtr);
 return *CUDAPtr;
@@ -1050,6 +1056,7 @@ class Sema final : public SemaBase {
   mutable IdentifierInfo *Ident_super;
 
   std::unique_ptr CodeCompletionPtr;
+  std::unique_ptr CoroutinePtr;
   std::unique_ptr CUDAPtr;
   std::unique_ptr HLSLPtr;
   std::unique_ptr ObjCPtr;
@@ -2267,57 +2274,6 @@ class Sema final : public SemaBase {
   //
   //
 
-  /// \name C++ Coroutines
-  /// Implementations are in SemaCoroutine.cpp
-  ///@{
-
-public:
-  /// The C++ "std::coroutine_traits" template, which is defined in
-  /// \
-  ClassTemplateDecl *StdCoroutineTraitsCache;
-
-  bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
-   StringRef Keyword);
-  ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
-  ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
-  StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
-
-  ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
-  ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
-  UnresolvedLookupExpr *Lookup);
-  ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
-  Expr *Awaiter, bool IsImplicit = false);
-  ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
-UnresolvedLookupExpr *Lookup);
-  ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
-  StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
-   bool IsImplicit = false);
-  StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
-  bool buildCoroutineParameterMoves(SourceLocation Loc);
-  VarDecl *buildCoroutinePromise(SourceLocation Loc);
-  void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
-
-  // As a clang extension, enforces that a non-coroutine function must be 
marked
-  // with [[clang::coro_wrapper]] if it returns a type marked with
-  // [[clang::coro_return_type]].
-  // Expects that FD is not a coroutine.
-  void CheckCoroutineWrapper(FunctionDecl *FD);
-  /// Lookup 'coroutine_traits' in std namespace and std::experimental
-  /// namespace. The namespace found is recorded in Namespace.
-  ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
-   SourceLocation FuncLoc);
-  /// Check that the expression co_await promise.final_suspend() shall not be
-  /// potentially-throwing.
-  bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
-
-  ///@}
-
-  //
-  //
-  // -
-  //
-  //
-
   /// \name C++ Scope Specifiers
   /// Implementations are in SemaCXXScopeSpec.cpp
   ///@{
diff --git a/clang/include/clang/Sema/SemaCoroutine.h 
b/clang/include/clang/Sema/SemaCoroutine.h
new file mode 100644
index 0..d4ca6cb0d860a
--- /dev/null
+++ b/clang/include/clang/Sema/SemaCoroutine.h
@@ -0,0 +1,73 @@
+//===- SemaCUDA.h - Semantic Analysis for C++20 coroutines 
===//
+//
+// 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

[clang] [clang] Introduce `SemaCoroutine` (PR #92645)

2024-05-18 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll created 
https://github.com/llvm/llvm-project/pull/92645

This patch moves coroutines-specific `Sema` functions into the new 
`SemaCoroutine` class. This continues previous efforts to split `Sema` up. 
Additional context can be found in #84184.
As usual, in order to help reviewing this, formatting changes are split into a 
separate commit.

>From 4fe09a3411e54561857d2f9d8c1808cb2728e299 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Sat, 18 May 2024 13:33:04 +0300
Subject: [PATCH 1/2] [clang] Introduce `SemaCoroutine`

---
 clang/include/clang/Sema/Sema.h  |  58 +-
 clang/include/clang/Sema/SemaCoroutine.h |  73 
 clang/lib/Parse/ParseExpr.cpp|   3 +-
 clang/lib/Parse/ParseExprCXX.cpp |   3 +-
 clang/lib/Parse/ParseStmt.cpp|   3 +-
 clang/lib/Sema/Sema.cpp  |   4 +-
 clang/lib/Sema/SemaCoroutine.cpp | 218 ---
 clang/lib/Sema/SemaDecl.cpp  |  16 +-
 clang/lib/Sema/SemaStmt.cpp  |   9 +-
 clang/lib/Sema/TreeTransform.h   |  25 +--
 10 files changed, 227 insertions(+), 185 deletions(-)
 create mode 100644 clang/include/clang/Sema/SemaCoroutine.h

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d4d4a82525a02..1d0fbeacfe061 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -168,6 +168,7 @@ class PseudoDestructorTypeStorage;
 class PseudoObjectExpr;
 class QualType;
 class SemaCodeCompletion;
+class SemaCoroutine;
 class SemaCUDA;
 class SemaHLSL;
 class SemaObjC;
@@ -989,6 +990,11 @@ class Sema final : public SemaBase {
 return *CodeCompletionPtr;
   }
 
+  SemaCoroutine &Coroutine() {
+assert(CoroutinePtr);
+return *CoroutinePtr;
+  }
+
   SemaCUDA &CUDA() {
 assert(CUDAPtr);
 return *CUDAPtr;
@@ -1050,6 +1056,7 @@ class Sema final : public SemaBase {
   mutable IdentifierInfo *Ident_super;
 
   std::unique_ptr CodeCompletionPtr;
+  std::unique_ptr CoroutinePtr;
   std::unique_ptr CUDAPtr;
   std::unique_ptr HLSLPtr;
   std::unique_ptr ObjCPtr;
@@ -2267,57 +2274,6 @@ class Sema final : public SemaBase {
   //
   //
 
-  /// \name C++ Coroutines
-  /// Implementations are in SemaCoroutine.cpp
-  ///@{
-
-public:
-  /// The C++ "std::coroutine_traits" template, which is defined in
-  /// \
-  ClassTemplateDecl *StdCoroutineTraitsCache;
-
-  bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
-   StringRef Keyword);
-  ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
-  ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
-  StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
-
-  ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
-  ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
-  UnresolvedLookupExpr *Lookup);
-  ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
-  Expr *Awaiter, bool IsImplicit = false);
-  ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
-UnresolvedLookupExpr *Lookup);
-  ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
-  StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
-   bool IsImplicit = false);
-  StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
-  bool buildCoroutineParameterMoves(SourceLocation Loc);
-  VarDecl *buildCoroutinePromise(SourceLocation Loc);
-  void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
-
-  // As a clang extension, enforces that a non-coroutine function must be 
marked
-  // with [[clang::coro_wrapper]] if it returns a type marked with
-  // [[clang::coro_return_type]].
-  // Expects that FD is not a coroutine.
-  void CheckCoroutineWrapper(FunctionDecl *FD);
-  /// Lookup 'coroutine_traits' in std namespace and std::experimental
-  /// namespace. The namespace found is recorded in Namespace.
-  ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
-   SourceLocation FuncLoc);
-  /// Check that the expression co_await promise.final_suspend() shall not be
-  /// potentially-throwing.
-  bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
-
-  ///@}
-
-  //
-  //
-  // -
-  //
-  //
-
   /// \name C++ Scope Specifiers
   /// Implementations are in SemaCXXScopeSpec.cpp
   ///@{
diff --git a/clang/include/clang/Sema/SemaCoroutine.h 
b/clang/include/clang/Sema/SemaCoroutine.h
new file mode 100644
index 0..20f1fffc970f8
--- /dev/null
+++ b/clang/include/clang/Sema/SemaCoroutine.h
@@ -0,0 +1,73 @@
+//===- SemaCUDA.h - Semantic Analysis for C++20 coroutines 
===//
+//
+// Part of the LLVM Project, 

[clang] [RISCV] Remove unneeded multiply in RISCV CodeGenTypes (PR #92644)

2024-05-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Brandon Wu (4vtomat)


Changes

The NumVectors other than 1 is handled by the code above.


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


1 Files Affected:

- (modified) clang/lib/CodeGen/CodeGenTypes.cpp (+1-2) 


``diff
diff --git a/clang/lib/CodeGen/CodeGenTypes.cpp 
b/clang/lib/CodeGen/CodeGenTypes.cpp
index e8d75eda029e6..0a926e4ac27fe 100644
--- a/clang/lib/CodeGen/CodeGenTypes.cpp
+++ b/clang/lib/CodeGen/CodeGenTypes.cpp
@@ -523,8 +523,7 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) {
   return llvm::StructType::get(getLLVMContext(), EltTys);
 }
 return llvm::ScalableVectorType::get(ConvertType(Info.ElementType),
- Info.EC.getKnownMinValue() *
- Info.NumVectors);
+ Info.EC.getKnownMinValue());
   }
 #define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS)  
\
   case BuiltinType::Id: {  
\

``




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


[clang] [RISCV] Remove unneeded multiply in RISCV CodeGenTypes (PR #92644)

2024-05-18 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Brandon Wu (4vtomat)


Changes

The NumVectors other than 1 is handled by the code above.


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


1 Files Affected:

- (modified) clang/lib/CodeGen/CodeGenTypes.cpp (+1-2) 


``diff
diff --git a/clang/lib/CodeGen/CodeGenTypes.cpp 
b/clang/lib/CodeGen/CodeGenTypes.cpp
index e8d75eda029e6..0a926e4ac27fe 100644
--- a/clang/lib/CodeGen/CodeGenTypes.cpp
+++ b/clang/lib/CodeGen/CodeGenTypes.cpp
@@ -523,8 +523,7 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) {
   return llvm::StructType::get(getLLVMContext(), EltTys);
 }
 return llvm::ScalableVectorType::get(ConvertType(Info.ElementType),
- Info.EC.getKnownMinValue() *
- Info.NumVectors);
+ Info.EC.getKnownMinValue());
   }
 #define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS)  
\
   case BuiltinType::Id: {  
\

``




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


[clang] [RISCV] Remove unneeded multiply in RISCV CodeGenTypes (PR #92644)

2024-05-18 Thread Brandon Wu via cfe-commits

https://github.com/4vtomat created 
https://github.com/llvm/llvm-project/pull/92644

The NumVectors other than 1 is handled by the code above.


>From 4dbcf6e577d5f1aea0cde72e3a5a7fd73620b2d9 Mon Sep 17 00:00:00 2001
From: Brandon Wu 
Date: Sat, 18 May 2024 03:07:43 -0700
Subject: [PATCH] [RISCV] Remove unneeded multiply in RISCV CodeGenTypes

The NumVectors other than 1 is handled by the code above.
---
 clang/lib/CodeGen/CodeGenTypes.cpp | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/clang/lib/CodeGen/CodeGenTypes.cpp 
b/clang/lib/CodeGen/CodeGenTypes.cpp
index e8d75eda029e6..0a926e4ac27fe 100644
--- a/clang/lib/CodeGen/CodeGenTypes.cpp
+++ b/clang/lib/CodeGen/CodeGenTypes.cpp
@@ -523,8 +523,7 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) {
   return llvm::StructType::get(getLLVMContext(), EltTys);
 }
 return llvm::ScalableVectorType::get(ConvertType(Info.ElementType),
- Info.EC.getKnownMinValue() *
- Info.NumVectors);
+ Info.EC.getKnownMinValue());
   }
 #define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS)  
\
   case BuiltinType::Id: {  
\

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


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

2024-05-18 Thread Vikram Hegde via cfe-commits

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


[clang] [alpha.webkit.UncountedLocalVarsChecker] Detect assignments to uncounted local variable and parameters. (PR #92639)

2024-05-18 Thread via cfe-commits

llvmbot wrote:




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

Author: Ryosuke Niwa (rniwa)


Changes

This PR updates alpha.webkit.UncountedLocalVarsChecker to emit warnings for 
assignments to uncounted local variable and parameters instead of just the 
initialization during the declaration.

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


2 Files Affected:

- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp (+37-24) 
- (modified) clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp (+42) 


``diff
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
index 0d9710a5e2d83..6c0d56303d5ad 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
@@ -135,7 +135,19 @@ class UncountedLocalVarsChecker
   bool shouldVisitImplicitCode() const { return false; }
 
   bool VisitVarDecl(VarDecl *V) {
-Checker->visitVarDecl(V);
+auto *Init = V->getInit();
+if (Init && V->isLocalVarDecl())
+  Checker->visitVarDecl(V, Init);
+return true;
+  }
+
+  bool VisitBinaryOperator(const BinaryOperator *BO) {
+if (BO->isAssignmentOp()) {
+  if (auto *VarRef = dyn_cast(BO->getLHS())) {
+if (auto *V = dyn_cast(VarRef->getDecl()))
+  Checker->visitVarDecl(V, BO->getRHS());
+  }
+}
 return true;
   }
 
@@ -174,7 +186,7 @@ class UncountedLocalVarsChecker
 visitor.TraverseDecl(const_cast(TUD));
   }
 
-  void visitVarDecl(const VarDecl *V) const {
+  void visitVarDecl(const VarDecl *V, const Expr *Value) const {
 if (shouldSkipVarDecl(V))
   return;
 
@@ -184,12 +196,8 @@ class UncountedLocalVarsChecker
 
 std::optional IsUncountedPtr = isUncountedPtr(ArgType);
 if (IsUncountedPtr && *IsUncountedPtr) {
-  const Expr *const InitExpr = V->getInit();
-  if (!InitExpr)
-return; // FIXME: later on we might warn on uninitialized vars too
-
   if (tryToFindPtrOrigin(
-  InitExpr, /*StopAtFirstRefCountedObj=*/false,
+  Value, /*StopAtFirstRefCountedObj=*/false,
   [&](const clang::Expr *InitArgOrigin, bool IsSafe) {
 if (!InitArgOrigin)
   return true;
@@ -232,34 +240,39 @@ class UncountedLocalVarsChecker
   }))
 return;
 
-  reportBug(V);
+  reportBug(V, Value);
 }
   }
 
   bool shouldSkipVarDecl(const VarDecl *V) const {
 assert(V);
-if (!V->isLocalVarDecl())
-  return true;
-
-if (BR->getSourceManager().isInSystemHeader(V->getLocation()))
-  return true;
-
-return false;
+return BR->getSourceManager().isInSystemHeader(V->getLocation());
   }
 
-  void reportBug(const VarDecl *V) const {
+  void reportBug(const VarDecl *V, const Expr *Value) const {
 assert(V);
 SmallString<100> Buf;
 llvm::raw_svector_ostream Os(Buf);
 
-Os << "Local variable ";
-printQuotedQualifiedName(Os, V);
-Os << " is uncounted and unsafe.";
-
-PathDiagnosticLocation BSLoc(V->getLocation(), BR->getSourceManager());
-auto Report = std::make_unique(Bug, Os.str(), BSLoc);
-Report->addRange(V->getSourceRange());
-BR->emitReport(std::move(Report));
+if (dyn_cast(V)) {
+  Os << "Assignment to an uncounted parameter ";
+  printQuotedQualifiedName(Os, V);
+  Os << " is unsafe.";
+
+  PathDiagnosticLocation BSLoc(Value->getExprLoc(), 
BR->getSourceManager());
+  auto Report = std::make_unique(Bug, Os.str(), BSLoc);
+  Report->addRange(Value->getSourceRange());
+  BR->emitReport(std::move(Report));
+} else {
+  Os << "Local variable ";
+  printQuotedQualifiedName(Os, V);
+  Os << " is uncounted and unsafe.";
+
+  PathDiagnosticLocation BSLoc(V->getLocation(), BR->getSourceManager());
+  auto Report = std::make_unique(Bug, Os.str(), BSLoc);
+  Report->addRange(V->getSourceRange());
+  BR->emitReport(std::move(Report));
+}
   }
 };
 } // namespace
diff --git a/clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp 
b/clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp
index 632a82eb0d8d1..abcb9c5122f70 100644
--- a/clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp
@@ -216,3 +216,45 @@ void foo() {
 }
 
 } // namespace conditional_op
+
+namespace local_assignment_basic {
+
+RefCountable *provide_ref_ctnbl();
+
+void foo(RefCountable* a) {
+  RefCountable* b = a;
+  // expected-warning@-1{{Local variable 'b' is uncounted and unsafe 
[alpha.webkit.UncountedLocalVarsChecker]}}
+  if (b->trivial())
+b = provide_ref_ctnbl();
+}
+
+void bar(RefCountable* a) {
+  RefCountable* b;
+  // expected-warning@-1{{Local variable

[clang] [alpha.webkit.UncountedLocalVarsChecker] Detect assignments to uncounted local variable and parameters. (PR #92639)

2024-05-18 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa created https://github.com/llvm/llvm-project/pull/92639

This PR updates alpha.webkit.UncountedLocalVarsChecker to emit warnings for 
assignments to uncounted local variable and parameters instead of just the 
initialization during the declaration.

>From 5ae3b193a6ec3617c99297da5b8d276b0e5bbc01 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sat, 18 May 2024 02:17:30 -0700
Subject: [PATCH] [alpha.webkit.UncountedLocalVarsChecker] Detect assignments
 to uncounted local variable and parameters.

This PR updates alpha.webkit.UncountedLocalVarsChecker to emit warnings for 
assignments to uncounted
local variable and parameters instead of just the initialization during the 
declaration.
---
 .../WebKit/UncountedLocalVarsChecker.cpp  | 61 +++
 .../Checkers/WebKit/uncounted-local-vars.cpp  | 42 +
 2 files changed, 79 insertions(+), 24 deletions(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
index 0d9710a5e2d83..6c0d56303d5ad 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
@@ -135,7 +135,19 @@ class UncountedLocalVarsChecker
   bool shouldVisitImplicitCode() const { return false; }
 
   bool VisitVarDecl(VarDecl *V) {
-Checker->visitVarDecl(V);
+auto *Init = V->getInit();
+if (Init && V->isLocalVarDecl())
+  Checker->visitVarDecl(V, Init);
+return true;
+  }
+
+  bool VisitBinaryOperator(const BinaryOperator *BO) {
+if (BO->isAssignmentOp()) {
+  if (auto *VarRef = dyn_cast(BO->getLHS())) {
+if (auto *V = dyn_cast(VarRef->getDecl()))
+  Checker->visitVarDecl(V, BO->getRHS());
+  }
+}
 return true;
   }
 
@@ -174,7 +186,7 @@ class UncountedLocalVarsChecker
 visitor.TraverseDecl(const_cast(TUD));
   }
 
-  void visitVarDecl(const VarDecl *V) const {
+  void visitVarDecl(const VarDecl *V, const Expr *Value) const {
 if (shouldSkipVarDecl(V))
   return;
 
@@ -184,12 +196,8 @@ class UncountedLocalVarsChecker
 
 std::optional IsUncountedPtr = isUncountedPtr(ArgType);
 if (IsUncountedPtr && *IsUncountedPtr) {
-  const Expr *const InitExpr = V->getInit();
-  if (!InitExpr)
-return; // FIXME: later on we might warn on uninitialized vars too
-
   if (tryToFindPtrOrigin(
-  InitExpr, /*StopAtFirstRefCountedObj=*/false,
+  Value, /*StopAtFirstRefCountedObj=*/false,
   [&](const clang::Expr *InitArgOrigin, bool IsSafe) {
 if (!InitArgOrigin)
   return true;
@@ -232,34 +240,39 @@ class UncountedLocalVarsChecker
   }))
 return;
 
-  reportBug(V);
+  reportBug(V, Value);
 }
   }
 
   bool shouldSkipVarDecl(const VarDecl *V) const {
 assert(V);
-if (!V->isLocalVarDecl())
-  return true;
-
-if (BR->getSourceManager().isInSystemHeader(V->getLocation()))
-  return true;
-
-return false;
+return BR->getSourceManager().isInSystemHeader(V->getLocation());
   }
 
-  void reportBug(const VarDecl *V) const {
+  void reportBug(const VarDecl *V, const Expr *Value) const {
 assert(V);
 SmallString<100> Buf;
 llvm::raw_svector_ostream Os(Buf);
 
-Os << "Local variable ";
-printQuotedQualifiedName(Os, V);
-Os << " is uncounted and unsafe.";
-
-PathDiagnosticLocation BSLoc(V->getLocation(), BR->getSourceManager());
-auto Report = std::make_unique(Bug, Os.str(), BSLoc);
-Report->addRange(V->getSourceRange());
-BR->emitReport(std::move(Report));
+if (dyn_cast(V)) {
+  Os << "Assignment to an uncounted parameter ";
+  printQuotedQualifiedName(Os, V);
+  Os << " is unsafe.";
+
+  PathDiagnosticLocation BSLoc(Value->getExprLoc(), 
BR->getSourceManager());
+  auto Report = std::make_unique(Bug, Os.str(), BSLoc);
+  Report->addRange(Value->getSourceRange());
+  BR->emitReport(std::move(Report));
+} else {
+  Os << "Local variable ";
+  printQuotedQualifiedName(Os, V);
+  Os << " is uncounted and unsafe.";
+
+  PathDiagnosticLocation BSLoc(V->getLocation(), BR->getSourceManager());
+  auto Report = std::make_unique(Bug, Os.str(), BSLoc);
+  Report->addRange(V->getSourceRange());
+  BR->emitReport(std::move(Report));
+}
   }
 };
 } // namespace
diff --git a/clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp 
b/clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp
index 632a82eb0d8d1..abcb9c5122f70 100644
--- a/clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp
@@ -216,3 +216,45 @@ void foo() {
 }
 
 } // namespace conditional_op
+
+namespace local_assignment_basic {
+
+RefCountable *p

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

2024-05-18 Thread Vikram Hegde via cfe-commits

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


[clang] f7b0b99 - [clang][NFC] Further improvements to const-correctness

2024-05-18 Thread Vlad Serebrennikov via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-05-18T12:10:39+03:00
New Revision: f7b0b99c52ee36ed6ca8abcce74a752e483768d6

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

LOG: [clang][NFC] Further improvements to const-correctness

Added: 


Modified: 
clang/include/clang/Serialization/ASTWriter.h
clang/lib/Basic/SourceManager.cpp
clang/lib/Frontend/CompilerInstance.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/lib/Serialization/ASTWriterStmt.cpp

Removed: 




diff  --git a/clang/include/clang/Serialization/ASTWriter.h 
b/clang/include/clang/Serialization/ASTWriter.h
index 7bb0e81545bd1..6aa2796a41e0c 100644
--- a/clang/include/clang/Serialization/ASTWriter.h
+++ b/clang/include/clang/Serialization/ASTWriter.h
@@ -565,7 +565,8 @@ class ASTWriter : public ASTDeserializationListener,
 
   void GenerateNameLookupTable(const DeclContext *DC,
llvm::SmallVectorImpl &LookupTable);
-  uint64_t WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC);
+  uint64_t WriteDeclContextLexicalBlock(ASTContext &Context,
+const DeclContext *DC);
   uint64_t WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC);
   void WriteTypeDeclOffsets();
   void WriteFileDeclIDsMap();

diff  --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index afdb5b0e92d64..753601e01b5c3 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -276,14 +276,14 @@ void SourceManager::AddLineNote(SourceLocation Loc, 
unsigned LineNo,
   std::pair LocInfo = getDecomposedExpansionLoc(Loc);
 
   bool Invalid = false;
-  const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
+  SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
   if (!Entry.isFile() || Invalid)
 return;
 
-  const SrcMgr::FileInfo &FileInfo = Entry.getFile();
+  SrcMgr::FileInfo &FileInfo = Entry.getFile();
 
   // Remember that this file has #line directives now if it doesn't already.
-  const_cast(FileInfo).setHasLineDirectives();
+  FileInfo.setHasLineDirectives();
 
   (void) getLineTable();
 

diff  --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index 66a45b888f15c..6242b5a7d9fe3 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -411,8 +411,7 @@ static void InitializeFileRemapping(DiagnosticsEngine 
&Diags,
   SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
 else
   SourceMgr.overrideFileContents(
-  FromFile, std::unique_ptr(
-const_cast(RB.second)));
+  FromFile, std::unique_ptr(RB.second));
   }
 
   // Remap files in the source manager (with other files).

diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index 510f61d9cccd8..f50f9569c0a5e 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -1649,8 +1649,7 @@ bool ASTReader::ReadSLocEntry(int ID) {
   FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
 FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
 BaseOffset + Record[0]);
-SrcMgr::FileInfo &FileInfo =
-  const_cast(SourceMgr.getSLocEntry(FID).getFile());
+SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
 FileInfo.NumCreatedFIDs = Record[5];
 if (Record[3])
   FileInfo.setHasLineDirectives();
@@ -1693,8 +1692,7 @@ bool ASTReader::ReadSLocEntry(int ID) {
 FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
 BaseOffset + Offset, IncludeLoc);
 if (Record[3]) {
-  auto &FileInfo =
-  const_cast(SourceMgr.getSLocEntry(FID).getFile());
+  auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
   FileInfo.setHasLineDirectives();
 }
 break;

diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index dd5d65b2eb20e..2a107e4c56a3a 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -3304,7 +3304,7 @@ static bool IsInternalDeclFromFileContext(const Decl *D) {
 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
 /// bitstream, or 0 if no block was written.
 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
- DeclContext *DC) {
+ const DeclContext *DC) {
   if (DC->decls_empty())
 return 0;
 
@@ -5698,8 +5698,8 @@ void ASTWriter::WriteDeclU

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

2024-05-18 Thread Vikram Hegde via cfe-commits


@@ -243,11 +243,16 @@ def VOP_READFIRSTLANE : VOPProfile <[i32, i32, untyped, 
untyped]> {
 // FIXME: Specify SchedRW for READFIRSTLANE_B32
 // TODO: There is VOP3 encoding also
 def V_READFIRSTLANE_B32 : VOP1_Pseudo <"v_readfirstlane_b32", 
VOP_READFIRSTLANE,
-   getVOP1Pat.ret, 1> {
+   [], 1> {
   let isConvergent = 1;
 }
 
+foreach vt = Reg32Types.types in {
+  def : GCNPat<(vt (AMDGPUreadfirstlane (vt VRegOrLdsSrc_32:$src0))),
+(V_READFIRSTLANE_B32 (vt VRegOrLdsSrc_32:$src0))

vikramRH wrote:

Done

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


[clang] [Clang] Fix __is_array returning true for zero-sized arrays (PR #86652)

2024-05-18 Thread Nikolas Klauser via cfe-commits

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

>From 90f88bdac3dc40635c58f3f67e29354e6a32896e Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Tue, 26 Mar 2024 12:23:24 +0100
Subject: [PATCH] [Clang] Fix __is_array returning true for zero-sized arrays

---
 clang/docs/ReleaseNotes.rst| 2 ++
 clang/lib/Sema/SemaExprCXX.cpp | 4 
 clang/test/SemaCXX/type-traits.cpp | 4 +++-
 3 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7fbe2fec6ca06..e668202853710 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -345,6 +345,8 @@ Bug Fixes in This Version
 - Fixes an assertion failure on invalid code when trying to define member
   functions in lambdas.
 
+- ``__is_array`` no longer returns ``true`` for zero-sized arrays. Fixes 
(#GH54705).
+
 Bug Fixes to Compiler Builtins
 ^^
 
diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index c34a40fa7c81a..93d2b4b259fbc 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -5143,6 +5143,10 @@ static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait 
UTT,
   case UTT_IsFloatingPoint:
 return T->isFloatingType();
   case UTT_IsArray:
+// zero-sized arrays aren't considered arrays in partial specializations,
+// so __is_array shouldn't consider them arrays either.
+if (const auto* CAT = C.getAsConstantArrayType(T))
+  return CAT->getSize() != 0;
 return T->isArrayType();
   case UTT_IsBoundedArray:
 if (!T->isVariableArrayType()) {
diff --git a/clang/test/SemaCXX/type-traits.cpp 
b/clang/test/SemaCXX/type-traits.cpp
index 14ec17989ec7c..49df4b668513c 100644
--- a/clang/test/SemaCXX/type-traits.cpp
+++ b/clang/test/SemaCXX/type-traits.cpp
@@ -25,6 +25,7 @@ typedef Empty EmptyArMB[1][2];
 typedef int Int;
 typedef Int IntAr[10];
 typedef Int IntArNB[];
+typedef Int IntArZero[0];
 class Statics { static int priv; static NonPOD np; };
 union EmptyUnion {};
 union IncompleteUnion; // expected-note {{forward declaration of 
'IncompleteUnion'}}
@@ -685,6 +686,7 @@ void is_array()
 {
   static_assert(__is_array(IntAr));
   static_assert(__is_array(IntArNB));
+  static_assert(!__is_array(IntArZero));
   static_assert(__is_array(UnionAr));
 
   static_assert(!__is_array(void));
@@ -1804,7 +1806,7 @@ void is_layout_compatible(int n)
   static_assert(!__is_layout_compatible(EnumForward, int));
   static_assert(!__is_layout_compatible(EnumClassForward, int));
   // FIXME: the following should be rejected (array of unknown bound and void 
are the only allowed incomplete types)
-  static_assert(__is_layout_compatible(CStructIncomplete, CStructIncomplete)); 
+  static_assert(__is_layout_compatible(CStructIncomplete, CStructIncomplete));
   static_assert(!__is_layout_compatible(CStruct, CStructIncomplete));
   static_assert(__is_layout_compatible(CStructIncomplete[2], 
CStructIncomplete[2]));
 }

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


[clang] [Clang] Fix __is_array returning true for zero-sized arrays (PR #86652)

2024-05-18 Thread Nikolas Klauser via cfe-commits

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

>From 90f88bdac3dc40635c58f3f67e29354e6a32896e Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Tue, 26 Mar 2024 12:23:24 +0100
Subject: [PATCH] [Clang] Fix __is_array returning true for zero-sized arrays

---
 clang/docs/ReleaseNotes.rst| 2 ++
 clang/lib/Sema/SemaExprCXX.cpp | 4 
 clang/test/SemaCXX/type-traits.cpp | 4 +++-
 3 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7fbe2fec6ca06..e668202853710 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -345,6 +345,8 @@ Bug Fixes in This Version
 - Fixes an assertion failure on invalid code when trying to define member
   functions in lambdas.
 
+- ``__is_array`` no longer returns ``true`` for zero-sized arrays. Fixes 
(#GH54705).
+
 Bug Fixes to Compiler Builtins
 ^^
 
diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index c34a40fa7c81a..93d2b4b259fbc 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -5143,6 +5143,10 @@ static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait 
UTT,
   case UTT_IsFloatingPoint:
 return T->isFloatingType();
   case UTT_IsArray:
+// zero-sized arrays aren't considered arrays in partial specializations,
+// so __is_array shouldn't consider them arrays either.
+if (const auto* CAT = C.getAsConstantArrayType(T))
+  return CAT->getSize() != 0;
 return T->isArrayType();
   case UTT_IsBoundedArray:
 if (!T->isVariableArrayType()) {
diff --git a/clang/test/SemaCXX/type-traits.cpp 
b/clang/test/SemaCXX/type-traits.cpp
index 14ec17989ec7c..49df4b668513c 100644
--- a/clang/test/SemaCXX/type-traits.cpp
+++ b/clang/test/SemaCXX/type-traits.cpp
@@ -25,6 +25,7 @@ typedef Empty EmptyArMB[1][2];
 typedef int Int;
 typedef Int IntAr[10];
 typedef Int IntArNB[];
+typedef Int IntArZero[0];
 class Statics { static int priv; static NonPOD np; };
 union EmptyUnion {};
 union IncompleteUnion; // expected-note {{forward declaration of 
'IncompleteUnion'}}
@@ -685,6 +686,7 @@ void is_array()
 {
   static_assert(__is_array(IntAr));
   static_assert(__is_array(IntArNB));
+  static_assert(!__is_array(IntArZero));
   static_assert(__is_array(UnionAr));
 
   static_assert(!__is_array(void));
@@ -1804,7 +1806,7 @@ void is_layout_compatible(int n)
   static_assert(!__is_layout_compatible(EnumForward, int));
   static_assert(!__is_layout_compatible(EnumClassForward, int));
   // FIXME: the following should be rejected (array of unknown bound and void 
are the only allowed incomplete types)
-  static_assert(__is_layout_compatible(CStructIncomplete, CStructIncomplete)); 
+  static_assert(__is_layout_compatible(CStructIncomplete, CStructIncomplete));
   static_assert(!__is_layout_compatible(CStruct, CStructIncomplete));
   static_assert(__is_layout_compatible(CStructIncomplete[2], 
CStructIncomplete[2]));
 }

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


[clang] [Clang] Fix __is_array returning true for zero-sized arrays (PR #86652)

2024-05-18 Thread Nikolas Klauser via cfe-commits

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

>From 90f88bdac3dc40635c58f3f67e29354e6a32896e Mon Sep 17 00:00:00 2001
From: Nikolas Klauser 
Date: Tue, 26 Mar 2024 12:23:24 +0100
Subject: [PATCH] [Clang] Fix __is_array returning true for zero-sized arrays

---
 clang/docs/ReleaseNotes.rst| 2 ++
 clang/lib/Sema/SemaExprCXX.cpp | 4 
 clang/test/SemaCXX/type-traits.cpp | 4 +++-
 3 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7fbe2fec6ca06..e668202853710 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -345,6 +345,8 @@ Bug Fixes in This Version
 - Fixes an assertion failure on invalid code when trying to define member
   functions in lambdas.
 
+- ``__is_array`` no longer returns ``true`` for zero-sized arrays. Fixes 
(#GH54705).
+
 Bug Fixes to Compiler Builtins
 ^^
 
diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index c34a40fa7c81a..93d2b4b259fbc 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -5143,6 +5143,10 @@ static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait 
UTT,
   case UTT_IsFloatingPoint:
 return T->isFloatingType();
   case UTT_IsArray:
+// zero-sized arrays aren't considered arrays in partial specializations,
+// so __is_array shouldn't consider them arrays either.
+if (const auto* CAT = C.getAsConstantArrayType(T))
+  return CAT->getSize() != 0;
 return T->isArrayType();
   case UTT_IsBoundedArray:
 if (!T->isVariableArrayType()) {
diff --git a/clang/test/SemaCXX/type-traits.cpp 
b/clang/test/SemaCXX/type-traits.cpp
index 14ec17989ec7c..49df4b668513c 100644
--- a/clang/test/SemaCXX/type-traits.cpp
+++ b/clang/test/SemaCXX/type-traits.cpp
@@ -25,6 +25,7 @@ typedef Empty EmptyArMB[1][2];
 typedef int Int;
 typedef Int IntAr[10];
 typedef Int IntArNB[];
+typedef Int IntArZero[0];
 class Statics { static int priv; static NonPOD np; };
 union EmptyUnion {};
 union IncompleteUnion; // expected-note {{forward declaration of 
'IncompleteUnion'}}
@@ -685,6 +686,7 @@ void is_array()
 {
   static_assert(__is_array(IntAr));
   static_assert(__is_array(IntArNB));
+  static_assert(!__is_array(IntArZero));
   static_assert(__is_array(UnionAr));
 
   static_assert(!__is_array(void));
@@ -1804,7 +1806,7 @@ void is_layout_compatible(int n)
   static_assert(!__is_layout_compatible(EnumForward, int));
   static_assert(!__is_layout_compatible(EnumClassForward, int));
   // FIXME: the following should be rejected (array of unknown bound and void 
are the only allowed incomplete types)
-  static_assert(__is_layout_compatible(CStructIncomplete, CStructIncomplete)); 
+  static_assert(__is_layout_compatible(CStructIncomplete, CStructIncomplete));
   static_assert(!__is_layout_compatible(CStruct, CStructIncomplete));
   static_assert(__is_layout_compatible(CStructIncomplete[2], 
CStructIncomplete[2]));
 }

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


[clang] [clang][ThreadSafety] Skip past implicit cast in `translateAttrExpr` (PR #92277)

2024-05-18 Thread Antonio Frighetto via cfe-commits

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


[clang] 2c2e050 - [clang][ThreadSafety] Skip past implicit cast in `translateAttrExpr`

2024-05-18 Thread Antonio Frighetto via cfe-commits

Author: Antonio Frighetto
Date: 2024-05-18T09:49:10+02:00
New Revision: 2c2e0507e92bdb77a01828f899ff59e44492b537

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

LOG: [clang][ThreadSafety] Skip past implicit cast in `translateAttrExpr`

Ignore `ImplicitCastExpr` when building `AttrExp` for capability
attribute diagnostics.

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

Added: 


Modified: 
clang/lib/Analysis/ThreadSafetyCommon.cpp
clang/test/SemaCXX/warn-thread-safety-analysis.cpp

Removed: 




diff  --git a/clang/lib/Analysis/ThreadSafetyCommon.cpp 
b/clang/lib/Analysis/ThreadSafetyCommon.cpp
index a3b378c42df33..3e8c959ccee4f 100644
--- a/clang/lib/Analysis/ThreadSafetyCommon.cpp
+++ b/clang/lib/Analysis/ThreadSafetyCommon.cpp
@@ -197,7 +197,7 @@ CapabilityExpr SExprBuilder::translateAttrExpr(const Expr 
*AttrExp,
   else if (const auto *UO = dyn_cast(AttrExp)) {
 if (UO->getOpcode() == UO_LNot) {
   Neg = true;
-  AttrExp = UO->getSubExpr();
+  AttrExp = UO->getSubExpr()->IgnoreImplicit();
 }
   }
 

diff  --git a/clang/test/SemaCXX/warn-thread-safety-analysis.cpp 
b/clang/test/SemaCXX/warn-thread-safety-analysis.cpp
index dfb966d3b5902..749d9e135d941 100644
--- a/clang/test/SemaCXX/warn-thread-safety-analysis.cpp
+++ b/clang/test/SemaCXX/warn-thread-safety-analysis.cpp
@@ -5341,7 +5341,7 @@ void dispatch_log(const char *msg) 
__attribute__((requires_capability(!FlightCon
 void dispatch_log2(const char *msg) 
__attribute__((requires_capability(Logger))) {}
 
 void flight_control_entry(void) 
__attribute__((requires_capability(FlightControl))) {
-  dispatch_log("wrong"); /* expected-warning {{cannot call function 
'dispatch_log' while mutex 'FlightControl' is held}} */
+  dispatch_log("wrong"); /* expected-warning {{cannot call function 
'dispatch_log' while role 'FlightControl' is held}} */
   dispatch_log2("also wrong"); /* expected-warning {{calling function 
'dispatch_log2' requires holding role 'Logger' exclusively}} */
 }
 



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


[clang] [clang][ThreadSafety] Skip past implicit cast in `translateAttrExpr` (PR #92277)

2024-05-18 Thread Antonio Frighetto via cfe-commits

https://github.com/antoniofrighetto updated 
https://github.com/llvm/llvm-project/pull/92277

>From 2c2e0507e92bdb77a01828f899ff59e44492b537 Mon Sep 17 00:00:00 2001
From: Antonio Frighetto 
Date: Wed, 15 May 2024 17:03:02 +0200
Subject: [PATCH] [clang][ThreadSafety] Skip past implicit cast in
 `translateAttrExpr`

Ignore `ImplicitCastExpr` when building `AttrExp` for capability
attribute diagnostics.

Fixes: https://github.com/llvm/llvm-project/issues/92118.
---
 clang/lib/Analysis/ThreadSafetyCommon.cpp  | 2 +-
 clang/test/SemaCXX/warn-thread-safety-analysis.cpp | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Analysis/ThreadSafetyCommon.cpp 
b/clang/lib/Analysis/ThreadSafetyCommon.cpp
index a3b378c42df33..3e8c959ccee4f 100644
--- a/clang/lib/Analysis/ThreadSafetyCommon.cpp
+++ b/clang/lib/Analysis/ThreadSafetyCommon.cpp
@@ -197,7 +197,7 @@ CapabilityExpr SExprBuilder::translateAttrExpr(const Expr 
*AttrExp,
   else if (const auto *UO = dyn_cast(AttrExp)) {
 if (UO->getOpcode() == UO_LNot) {
   Neg = true;
-  AttrExp = UO->getSubExpr();
+  AttrExp = UO->getSubExpr()->IgnoreImplicit();
 }
   }
 
diff --git a/clang/test/SemaCXX/warn-thread-safety-analysis.cpp 
b/clang/test/SemaCXX/warn-thread-safety-analysis.cpp
index dfb966d3b5902..749d9e135d941 100644
--- a/clang/test/SemaCXX/warn-thread-safety-analysis.cpp
+++ b/clang/test/SemaCXX/warn-thread-safety-analysis.cpp
@@ -5341,7 +5341,7 @@ void dispatch_log(const char *msg) 
__attribute__((requires_capability(!FlightCon
 void dispatch_log2(const char *msg) 
__attribute__((requires_capability(Logger))) {}
 
 void flight_control_entry(void) 
__attribute__((requires_capability(FlightControl))) {
-  dispatch_log("wrong"); /* expected-warning {{cannot call function 
'dispatch_log' while mutex 'FlightControl' is held}} */
+  dispatch_log("wrong"); /* expected-warning {{cannot call function 
'dispatch_log' while role 'FlightControl' is held}} */
   dispatch_log2("also wrong"); /* expected-warning {{calling function 
'dispatch_log2' requires holding role 'Logger' exclusively}} */
 }
 

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


[clang] [BoundsSafety] Allow 'counted_by' attribute on pointers in structs in C (PR #90786)

2024-05-18 Thread Dan Liew via cfe-commits

delcypher wrote:

Ok. Now I see what's happening.

These lines here are basically giving ownership of `LateParsedAttribute` to the 
`LateParsedAttrList`

```
  // Handle attributes with arguments that require late parsing.
  LateParsedAttribute *LA =
  new LateParsedAttribute(this, *AttrName, AttrNameLoc);
  LateAttrs->push_back(LA);
```

However `LateParsedAttrList` is basically just a 

```
class LateParsedAttrList: public SmallVector {
...
}
```

so it won't free the pointers when the list is destroyed. If we look at the C++ 
code that handles this we can see a bunch of manual memory management.

```
/// Parse all attributes in LAs, and attach them to Decl D.
void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
 bool EnterScope, bool OnDefinition) {
  assert(LAs.parseSoon() &&
 "Attribute list should be marked for immediate parsing.");
  for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
if (D)
  LAs[i]->addDecl(D);
ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
delete LAs[i];
  }
  LAs.clear();
}
```

This is a silly footgun. `LateParsedAttrList` should properly take ownership of 
its pointers by deleting them when the list is destroyed.

For now we should just replicate what is done for C++ but once we're confident 
we've fixed things we should make `LateParsedAttrList` properly own its 
pointers.

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


[clang] [OpenCL] Fix an infinite loop in builidng AddrSpaceQualType (PR #92612)

2024-05-18 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,25 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 4
+//RUN: %clang_cc1 %s -emit-llvm -O1 -o - | FileCheck %s

arsenm wrote:

codegen tests need an explicit target 

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