[clang] [AST] Use explicit type erasure in TypeSourceInfo constructor (PR #68435)

2023-10-20 Thread Shivam Gupta via cfe-commits

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


[clang] 826c93f - [AST] Use explicit type erasure in TypeSourceInfo constructor (#68435)

2023-10-20 Thread via cfe-commits

Author: Arseny
Date: 2023-10-21T10:40:58+05:30
New Revision: 826c93f96efd8e34781c12cfcc6e7284691f6e8c

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

LOG: [AST] Use explicit type erasure in TypeSourceInfo constructor (#68435)

When this file is included in a project compiled with GCC 13 `-Werror`,
compilation fails with the following diagnostic:

/usr/lib/llvm-17.0/include/clang/AST/TypeLoc.h: In constructor
'clang::TypeSourceInfo::TypeSourceInfo(clang::QualType, size_t)':
/usr/lib/llvm-17.0/include/clang/AST/TypeLoc.h:245:9: error: 'void*
memset(void*, int, size_t)' clearing an object of non-trivial type
'class clang::TypeSourceInfo'; use assignment instead
[-Werror=class-memaccess]
  245 |   memset(this + 1, 0, DataSize);
  |   ~~^~~


To avoid this, we add an explicit type cast. The cast to `void*` makes
sense, since other member functions of `TypeSourceInfo` also treat the
buffer `(this + 1)` of length `DataSize` as opaque memory, and was
likely left out by mistake.

Fixes: 4498663f3de0 ("[AST] Initialized data after TypeSourceInfo")

I also suggest to apply this to release/17.x if possible.

Added: 


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

Removed: 




diff  --git a/clang/include/clang/AST/TypeLoc.h 
b/clang/include/clang/AST/TypeLoc.h
index 98427a8dcbfe660..5bb487f1a7f4455 100644
--- a/clang/include/clang/AST/TypeLoc.h
+++ b/clang/include/clang/AST/TypeLoc.h
@@ -243,7 +243,7 @@ class TypeLoc {
 
 inline TypeSourceInfo::TypeSourceInfo(QualType ty, size_t DataSize) : Ty(ty) {
   // Init data attached to the object. See getTypeLoc.
-  memset(this + 1, 0, DataSize);
+  memset(static_cast(this + 1), 0, DataSize);
 }
 
 /// Return the TypeLoc for a type source info.



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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

2023-10-20 Thread Owen Pan via cfe-commits
=?utf-8?q?Bj=C3=B6rn_Sch=C3=A4pers?= 
Message-ID:
In-Reply-To: 



@@ -3102,7 +3102,9 @@ TEST_F(FormatTestComments, DontAlignNamespaceComments) {
   StringRef Input = "namespace A {\n"
 "  TESTSUITE(B) {\n"
 "namespace C {\n"
-"  namespace D {} // namespace D\n"
+"  namespace D {\n"
+"// ...\n"

owenca wrote:

```suggestion
"  namespace D { //\n"
```
To keep the `namespace` empty like before.

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


[clang] [Driver] Clean up unused archicture related bits for *BSD's (PR #69809)

2023-10-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Brad Smith (brad0)


Changes

- FreeBSD removed big-endian arm with 12.0.
- OpenBSD never had big-endian arm support. I added it just in case, but it has 
never been used.
- Remove sparcel bits. It was sprinkled in a few places but it will never be a 
thing.
- Remove 32-bit sparc bits for FreeBSD. FreeBSD has never had 32-bit sparc 
support.

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


5 Files Affected:

- (modified) clang/lib/Basic/Targets.cpp (-8) 
- (modified) clang/lib/Driver/ToolChains/FreeBSD.cpp (+1-3) 
- (modified) clang/lib/Driver/ToolChains/NetBSD.cpp (+1-2) 
- (modified) clang/lib/Driver/ToolChains/OpenBSD.cpp (+1-2) 
- (modified) clang/test/Driver/freebsd.c (+3-8) 


``diff
diff --git a/clang/lib/Basic/Targets.cpp b/clang/lib/Basic/Targets.cpp
index 8130f90a276749e..ea002bb464fcc58 100644
--- a/clang/lib/Basic/Targets.cpp
+++ b/clang/lib/Basic/Targets.cpp
@@ -247,12 +247,8 @@ std::unique_ptr AllocateTarget(const 
llvm::Triple ,
 switch (os) {
 case llvm::Triple::Linux:
   return std::make_unique>(Triple, Opts);
-case llvm::Triple::FreeBSD:
-  return std::make_unique>(Triple, 
Opts);
 case llvm::Triple::NetBSD:
   return std::make_unique>(Triple, Opts);
-case llvm::Triple::OpenBSD:
-  return std::make_unique>(Triple, 
Opts);
 case llvm::Triple::RTEMS:
   return std::make_unique>(Triple, Opts);
 case llvm::Triple::NaCl:
@@ -487,15 +483,11 @@ std::unique_ptr AllocateTarget(const 
llvm::Triple ,
   return std::make_unique(Triple, Opts);
 }
 
-  // The 'sparcel' architecture copies all the above cases except for Solaris.
   case llvm::Triple::sparcel:
 switch (os) {
 case llvm::Triple::Linux:
   return std::make_unique>(Triple,
 Opts);
-case llvm::Triple::NetBSD:
-  return std::make_unique>(Triple,
- Opts);
 case llvm::Triple::RTEMS:
   return std::make_unique>(Triple,
 Opts);
diff --git a/clang/lib/Driver/ToolChains/FreeBSD.cpp 
b/clang/lib/Driver/ToolChains/FreeBSD.cpp
index 7a61159ba4a7308..f4c2f70e73576f6 100644
--- a/clang/lib/Driver/ToolChains/FreeBSD.cpp
+++ b/clang/lib/Driver/ToolChains/FreeBSD.cpp
@@ -88,8 +88,6 @@ void freebsd::Assembler::ConstructJob(Compilation , const 
JobAction ,
 CmdArgs.push_back("-meabi=5");
 break;
   }
-  case llvm::Triple::sparc:
-  case llvm::Triple::sparcel:
   case llvm::Triple::sparcv9: {
 std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
 CmdArgs.push_back(
@@ -167,7 +165,7 @@ void freebsd::Linker::ConstructJob(Compilation , const 
JobAction ,
   CmdArgs.push_back("/libexec/ld-elf.so.1");
 }
 const llvm::Triple  = ToolChain.getTriple();
-if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc || T.isX86())
+if (Arch == llvm::Triple::arm || T.isX86())
   CmdArgs.push_back("--hash-style=both");
 CmdArgs.push_back("--enable-new-dtags");
   }
diff --git a/clang/lib/Driver/ToolChains/NetBSD.cpp 
b/clang/lib/Driver/ToolChains/NetBSD.cpp
index 1c901f70f72ca2e..6267344d819d9a0 100644
--- a/clang/lib/Driver/ToolChains/NetBSD.cpp
+++ b/clang/lib/Driver/ToolChains/NetBSD.cpp
@@ -78,8 +78,7 @@ void netbsd::Assembler::ConstructJob(Compilation , const 
JobAction ,
 break;
   }
 
-  case llvm::Triple::sparc:
-  case llvm::Triple::sparcel: {
+  case llvm::Triple::sparc: {
 CmdArgs.push_back("-32");
 std::string CPU = getCPUName(D, Args, Triple);
 CmdArgs.push_back(sparc::getSparcAsmModeForCPU(CPU, Triple));
diff --git a/clang/lib/Driver/ToolChains/OpenBSD.cpp 
b/clang/lib/Driver/ToolChains/OpenBSD.cpp
index e874f245776c4fc..cefbdff20ead93f 100644
--- a/clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ b/clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -45,8 +45,7 @@ void openbsd::Assembler::ConstructJob(Compilation , const 
JobAction ,
 CmdArgs.push_back("--32");
 break;
 
-  case llvm::Triple::arm:
-  case llvm::Triple::armeb: {
+  case llvm::Triple::arm: {
 StringRef MArch, MCPU;
 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
 std::string Arch = arm::getARMTargetCPU(MCPU, MArch, Triple);
diff --git a/clang/test/Driver/freebsd.c b/clang/test/Driver/freebsd.c
index afa0a17249851b3..e1ce8889459f974 100644
--- a/clang/test/Driver/freebsd.c
+++ b/clang/test/Driver/freebsd.c
@@ -163,9 +163,9 @@
 // CHECK-ARM-EABIHF-NOT: as{{.*}}" "-mfpu=softvfp"
 // CHECK-ARM-EABIHF-NOT: as{{.*}}" "-matpcs"
 
-// RUN: %clang --target=sparc-unknown-freebsd -### %s -fpic -no-integrated-as 
2>&1 \
-// RUN:   | FileCheck --check-prefix=CHECK-SPARC-PIE %s
-// CHECK-SPARC-PIE: as{{.*}}" "-KPIC
+// RUN: %clang --target=sparc64-unknown-freebsd -### %s -fpic 
-no-integrated-as 2>&1 \
+// RUN:   | FileCheck 

[clang] [Driver] Clean up unused archicture related bits for *BSD's (PR #69809)

2023-10-20 Thread Brad Smith via cfe-commits

https://github.com/brad0 created https://github.com/llvm/llvm-project/pull/69809

- FreeBSD removed big-endian arm with 12.0.
- OpenBSD never had big-endian arm support. I added it just in case, but it has 
never been used.
- Remove sparcel bits. It was sprinkled in a few places but it will never be a 
thing.
- Remove 32-bit sparc bits for FreeBSD. FreeBSD has never had 32-bit sparc 
support.

>From 469132f39c171592c6ca0344fc36ab95bf63f380 Mon Sep 17 00:00:00 2001
From: Brad Smith 
Date: Thu, 5 Oct 2023 18:41:03 -0400
Subject: [PATCH] [Driver] Clean up unused archicture related bits for *BSD's

- FreeBSD removed big-endian arm with 12.0.
- OpenBSD never had big-endian arm support. I added it just in case, but it has
  never been used.
- Remove sparcel bits. It was sprinkled in a few places but it will never be a
  thing.
- Remove 32-bit sparc bits for FreeBSD. FreeBSD has never had 32-bit sparc
  support.
---
 clang/lib/Basic/Targets.cpp |  8 
 clang/lib/Driver/ToolChains/FreeBSD.cpp |  4 +---
 clang/lib/Driver/ToolChains/NetBSD.cpp  |  3 +--
 clang/lib/Driver/ToolChains/OpenBSD.cpp |  3 +--
 clang/test/Driver/freebsd.c | 11 +++
 5 files changed, 6 insertions(+), 23 deletions(-)

diff --git a/clang/lib/Basic/Targets.cpp b/clang/lib/Basic/Targets.cpp
index 8130f90a276749e..ea002bb464fcc58 100644
--- a/clang/lib/Basic/Targets.cpp
+++ b/clang/lib/Basic/Targets.cpp
@@ -247,12 +247,8 @@ std::unique_ptr AllocateTarget(const 
llvm::Triple ,
 switch (os) {
 case llvm::Triple::Linux:
   return std::make_unique>(Triple, Opts);
-case llvm::Triple::FreeBSD:
-  return std::make_unique>(Triple, 
Opts);
 case llvm::Triple::NetBSD:
   return std::make_unique>(Triple, Opts);
-case llvm::Triple::OpenBSD:
-  return std::make_unique>(Triple, 
Opts);
 case llvm::Triple::RTEMS:
   return std::make_unique>(Triple, Opts);
 case llvm::Triple::NaCl:
@@ -487,15 +483,11 @@ std::unique_ptr AllocateTarget(const 
llvm::Triple ,
   return std::make_unique(Triple, Opts);
 }
 
-  // The 'sparcel' architecture copies all the above cases except for Solaris.
   case llvm::Triple::sparcel:
 switch (os) {
 case llvm::Triple::Linux:
   return std::make_unique>(Triple,
 Opts);
-case llvm::Triple::NetBSD:
-  return std::make_unique>(Triple,
- Opts);
 case llvm::Triple::RTEMS:
   return std::make_unique>(Triple,
 Opts);
diff --git a/clang/lib/Driver/ToolChains/FreeBSD.cpp 
b/clang/lib/Driver/ToolChains/FreeBSD.cpp
index 7a61159ba4a7308..f4c2f70e73576f6 100644
--- a/clang/lib/Driver/ToolChains/FreeBSD.cpp
+++ b/clang/lib/Driver/ToolChains/FreeBSD.cpp
@@ -88,8 +88,6 @@ void freebsd::Assembler::ConstructJob(Compilation , const 
JobAction ,
 CmdArgs.push_back("-meabi=5");
 break;
   }
-  case llvm::Triple::sparc:
-  case llvm::Triple::sparcel:
   case llvm::Triple::sparcv9: {
 std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
 CmdArgs.push_back(
@@ -167,7 +165,7 @@ void freebsd::Linker::ConstructJob(Compilation , const 
JobAction ,
   CmdArgs.push_back("/libexec/ld-elf.so.1");
 }
 const llvm::Triple  = ToolChain.getTriple();
-if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc || T.isX86())
+if (Arch == llvm::Triple::arm || T.isX86())
   CmdArgs.push_back("--hash-style=both");
 CmdArgs.push_back("--enable-new-dtags");
   }
diff --git a/clang/lib/Driver/ToolChains/NetBSD.cpp 
b/clang/lib/Driver/ToolChains/NetBSD.cpp
index 1c901f70f72ca2e..6267344d819d9a0 100644
--- a/clang/lib/Driver/ToolChains/NetBSD.cpp
+++ b/clang/lib/Driver/ToolChains/NetBSD.cpp
@@ -78,8 +78,7 @@ void netbsd::Assembler::ConstructJob(Compilation , const 
JobAction ,
 break;
   }
 
-  case llvm::Triple::sparc:
-  case llvm::Triple::sparcel: {
+  case llvm::Triple::sparc: {
 CmdArgs.push_back("-32");
 std::string CPU = getCPUName(D, Args, Triple);
 CmdArgs.push_back(sparc::getSparcAsmModeForCPU(CPU, Triple));
diff --git a/clang/lib/Driver/ToolChains/OpenBSD.cpp 
b/clang/lib/Driver/ToolChains/OpenBSD.cpp
index e874f245776c4fc..cefbdff20ead93f 100644
--- a/clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ b/clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -45,8 +45,7 @@ void openbsd::Assembler::ConstructJob(Compilation , const 
JobAction ,
 CmdArgs.push_back("--32");
 break;
 
-  case llvm::Triple::arm:
-  case llvm::Triple::armeb: {
+  case llvm::Triple::arm: {
 StringRef MArch, MCPU;
 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
 std::string Arch = arm::getARMTargetCPU(MCPU, MArch, Triple);
diff --git a/clang/test/Driver/freebsd.c b/clang/test/Driver/freebsd.c
index afa0a17249851b3..e1ce8889459f974 100644
--- a/clang/test/Driver/freebsd.c
+++ 

[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Joseph Huber via cfe-commits


@@ -0,0 +1,80 @@
+//===-- State.cpp - OpenMP State & ICV interface - C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//===--===//
+
+#include "Allocator.h"
+#include "Configuration.h"
+#include "Environment.h"
+#include "Mapping.h"
+#include "Synchronization.h"
+#include "Types.h"
+#include "Utils.h"
+
+using namespace ompx;
+
+#pragma omp begin declare target device_type(nohost)
+
+[[gnu::used, gnu::retain, gnu::weak,
+  gnu::visibility(
+  "protected")]] DeviceMemoryPoolTy __omp_rtl_device_memory_pool;
+[[gnu::used, gnu::retain, gnu::weak,
+  gnu::visibility("protected")]] DeviceMemoryPoolTrackingTy
+__omp_rtl_device_memory_pool_tracker;
+
+/// Stateless bump allocator that uses the __omp_rtl_device_memory_pool
+/// directly.
+struct BumpAllocatorTy final {
+
+  void *alloc(uint64_t Size) {
+Size = utils::roundUp(Size, uint64_t(allocator::ALIGNMENT));
+
+if (config::isDebugMode(DeviceDebugKind::AllocationTracker)) {
+  atomic::add(&__omp_rtl_device_memory_pool_tracker.NumAllocations, 1,
+  atomic::seq_cst);
+  atomic::add(&__omp_rtl_device_memory_pool_tracker.AllocationTotal, Size,
+  atomic::seq_cst);
+  atomic::min(&__omp_rtl_device_memory_pool_tracker.AllocationMin, Size,
+  atomic::seq_cst);
+  atomic::max(&__omp_rtl_device_memory_pool_tracker.AllocationMax, Size,
+  atomic::seq_cst);
+}
+
+uint64_t *Data =
+reinterpret_cast(&__omp_rtl_device_memory_pool.Ptr);
+uint64_t End =
+reinterpret_cast(Data) + __omp_rtl_device_memory_pool.Size;
+
+uint64_t OldData = atomic::add(Data, Size, atomic::seq_cst);
+if (OldData + Size > End)
+  __builtin_trap();

jhuber6 wrote:

I guess I'm just averse to traps because they currently deadlock on my machine. 
I still haven't tracked down the cause of that however.

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Shilei Tian via cfe-commits

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Shilei Tian via cfe-commits


@@ -0,0 +1,80 @@
+//===-- State.cpp - OpenMP State & ICV interface - C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//===--===//
+
+#include "Allocator.h"
+#include "Configuration.h"
+#include "Environment.h"
+#include "Mapping.h"
+#include "Synchronization.h"
+#include "Types.h"
+#include "Utils.h"
+
+using namespace ompx;
+
+#pragma omp begin declare target device_type(nohost)
+
+[[gnu::used, gnu::retain, gnu::weak,
+  gnu::visibility(
+  "protected")]] DeviceMemoryPoolTy __omp_rtl_device_memory_pool;
+[[gnu::used, gnu::retain, gnu::weak,
+  gnu::visibility("protected")]] DeviceMemoryPoolTrackingTy
+__omp_rtl_device_memory_pool_tracker;
+
+/// Stateless bump allocator that uses the __omp_rtl_device_memory_pool
+/// directly.
+struct BumpAllocatorTy final {
+
+  void *alloc(uint64_t Size) {
+Size = utils::roundUp(Size, uint64_t(allocator::ALIGNMENT));
+
+if (config::isDebugMode(DeviceDebugKind::AllocationTracker)) {
+  atomic::add(&__omp_rtl_device_memory_pool_tracker.NumAllocations, 1,
+  atomic::seq_cst);
+  atomic::add(&__omp_rtl_device_memory_pool_tracker.AllocationTotal, Size,
+  atomic::seq_cst);
+  atomic::min(&__omp_rtl_device_memory_pool_tracker.AllocationMin, Size,
+  atomic::seq_cst);
+  atomic::max(&__omp_rtl_device_memory_pool_tracker.AllocationMax, Size,
+  atomic::seq_cst);
+}
+
+uint64_t *Data =
+reinterpret_cast(&__omp_rtl_device_memory_pool.Ptr);
+uint64_t End =
+reinterpret_cast(Data) + __omp_rtl_device_memory_pool.Size;
+
+uint64_t OldData = atomic::add(Data, Size, atomic::seq_cst);
+if (OldData + Size > End)
+  __builtin_trap();

shiltian wrote:

Based on my experience it's not always easy to expose a dereference `nullptr` 
on a GPU. Given what we have right now in this allocator, it is better to just 
trap if we don't have enough memory.

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Joseph Huber via cfe-commits


@@ -0,0 +1,80 @@
+//===-- State.cpp - OpenMP State & ICV interface - C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//===--===//
+
+#include "Allocator.h"
+#include "Configuration.h"
+#include "Environment.h"
+#include "Mapping.h"
+#include "Synchronization.h"
+#include "Types.h"
+#include "Utils.h"
+
+using namespace ompx;
+
+#pragma omp begin declare target device_type(nohost)
+
+[[gnu::used, gnu::retain, gnu::weak,
+  gnu::visibility(
+  "protected")]] DeviceMemoryPoolTy __omp_rtl_device_memory_pool;
+[[gnu::used, gnu::retain, gnu::weak,
+  gnu::visibility("protected")]] DeviceMemoryPoolTrackingTy
+__omp_rtl_device_memory_pool_tracker;
+
+/// Stateless bump allocator that uses the __omp_rtl_device_memory_pool
+/// directly.
+struct BumpAllocatorTy final {
+
+  void *alloc(uint64_t Size) {
+Size = utils::roundUp(Size, uint64_t(allocator::ALIGNMENT));
+
+if (config::isDebugMode(DeviceDebugKind::AllocationTracker)) {
+  atomic::add(&__omp_rtl_device_memory_pool_tracker.NumAllocations, 1,
+  atomic::seq_cst);
+  atomic::add(&__omp_rtl_device_memory_pool_tracker.AllocationTotal, Size,
+  atomic::seq_cst);
+  atomic::min(&__omp_rtl_device_memory_pool_tracker.AllocationMin, Size,
+  atomic::seq_cst);
+  atomic::max(&__omp_rtl_device_memory_pool_tracker.AllocationMax, Size,
+  atomic::seq_cst);
+}
+
+uint64_t *Data =
+reinterpret_cast(&__omp_rtl_device_memory_pool.Ptr);
+uint64_t End =
+reinterpret_cast(Data) + __omp_rtl_device_memory_pool.Size;
+
+uint64_t OldData = atomic::add(Data, Size, atomic::seq_cst);
+if (OldData + Size > End)
+  __builtin_trap();

jhuber6 wrote:

True, but I figured the inevitable dereference of the nullptr would be a good 
trap that's usually more easily connected with `malloc`.

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Johannes Doerfert via cfe-commits


@@ -0,0 +1,80 @@
+//===-- State.cpp - OpenMP State & ICV interface - C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//===--===//
+
+#include "Allocator.h"
+#include "Configuration.h"
+#include "Environment.h"
+#include "Mapping.h"
+#include "Synchronization.h"
+#include "Types.h"
+#include "Utils.h"
+
+using namespace ompx;
+
+#pragma omp begin declare target device_type(nohost)
+
+[[gnu::used, gnu::retain, gnu::weak,
+  gnu::visibility(
+  "protected")]] DeviceMemoryPoolTy __omp_rtl_device_memory_pool;
+[[gnu::used, gnu::retain, gnu::weak,
+  gnu::visibility("protected")]] DeviceMemoryPoolTrackingTy
+__omp_rtl_device_memory_pool_tracker;
+
+/// Stateless bump allocator that uses the __omp_rtl_device_memory_pool
+/// directly.
+struct BumpAllocatorTy final {
+
+  void *alloc(uint64_t Size) {
+Size = utils::roundUp(Size, uint64_t(allocator::ALIGNMENT));
+
+if (config::isDebugMode(DeviceDebugKind::AllocationTracker)) {
+  atomic::add(&__omp_rtl_device_memory_pool_tracker.NumAllocations, 1,
+  atomic::seq_cst);
+  atomic::add(&__omp_rtl_device_memory_pool_tracker.AllocationTotal, Size,
+  atomic::seq_cst);
+  atomic::min(&__omp_rtl_device_memory_pool_tracker.AllocationMin, Size,
+  atomic::seq_cst);
+  atomic::max(&__omp_rtl_device_memory_pool_tracker.AllocationMax, Size,
+  atomic::seq_cst);
+}
+
+uint64_t *Data =
+reinterpret_cast(&__omp_rtl_device_memory_pool.Ptr);
+uint64_t End =
+reinterpret_cast(Data) + __omp_rtl_device_memory_pool.Size;
+
+uint64_t OldData = atomic::add(Data, Size, atomic::seq_cst);
+if (OldData + Size > End)
+  __builtin_trap();

jdoerfert wrote:

This allocator is not a production allocator. Right now, we run into too many 
problems. And honestly, nobody checks for nullptr.

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Johannes Doerfert via cfe-commits


@@ -36,6 +46,15 @@ extern "C" {
 #pragma omp end declare variant
 
 #ifdef __AMDGCN__
+#pragma omp begin declare variant match(   
\
+device = {arch(amdgcn)},   
\
+implementation = {extension(disable_implicit_base)})
+
+void *malloc(size_t Size) { return llvm_device_malloc(Size); }
+void free(void *Ptr) { llvm_device_free(Ptr); }

jdoerfert wrote:

You're right. We always replace calls to malloc. I can try your proposal, it's 
a little unfortunate that we then provide different entry points but that might 
be the price to pay.

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Joseph Huber via cfe-commits


@@ -36,6 +46,15 @@ extern "C" {
 #pragma omp end declare variant
 
 #ifdef __AMDGCN__
+#pragma omp begin declare variant match(   
\
+device = {arch(amdgcn)},   
\
+implementation = {extension(disable_implicit_base)})
+
+void *malloc(size_t Size) { return llvm_device_malloc(Size); }
+void free(void *Ptr) { llvm_device_free(Ptr); }

jhuber6 wrote:

Unsure how to feel about this, here we always replace `malloc` calls with the 
one inside the OpenMP device runtime library won't it?

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 commented:

I figured we would just have an internal implementation of `malloc` provided by 
the OpenMP device runtime library. The variants make this more difficult, but 
we could just use `#ifdef __AMDGPU__` instead of an OpenMP variant so we can 
declare it as `extern "C"` inside the AMDGPU device RTL. Since we use a 
two-step compilation and always compile with clang it should be legal.

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Joseph Huber via cfe-commits


@@ -0,0 +1,80 @@
+//===-- State.cpp - OpenMP State & ICV interface - C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//===--===//
+
+#include "Allocator.h"
+#include "Configuration.h"
+#include "Environment.h"
+#include "Mapping.h"
+#include "Synchronization.h"
+#include "Types.h"
+#include "Utils.h"
+
+using namespace ompx;
+
+#pragma omp begin declare target device_type(nohost)
+
+[[gnu::used, gnu::retain, gnu::weak,
+  gnu::visibility(
+  "protected")]] DeviceMemoryPoolTy __omp_rtl_device_memory_pool;
+[[gnu::used, gnu::retain, gnu::weak,
+  gnu::visibility("protected")]] DeviceMemoryPoolTrackingTy
+__omp_rtl_device_memory_pool_tracker;
+
+/// Stateless bump allocator that uses the __omp_rtl_device_memory_pool
+/// directly.
+struct BumpAllocatorTy final {
+
+  void *alloc(uint64_t Size) {
+Size = utils::roundUp(Size, uint64_t(allocator::ALIGNMENT));
+
+if (config::isDebugMode(DeviceDebugKind::AllocationTracker)) {
+  atomic::add(&__omp_rtl_device_memory_pool_tracker.NumAllocations, 1,
+  atomic::seq_cst);
+  atomic::add(&__omp_rtl_device_memory_pool_tracker.AllocationTotal, Size,
+  atomic::seq_cst);
+  atomic::min(&__omp_rtl_device_memory_pool_tracker.AllocationMin, Size,
+  atomic::seq_cst);
+  atomic::max(&__omp_rtl_device_memory_pool_tracker.AllocationMax, Size,
+  atomic::seq_cst);
+}
+
+uint64_t *Data =
+reinterpret_cast(&__omp_rtl_device_memory_pool.Ptr);
+uint64_t End =
+reinterpret_cast(Data) + __omp_rtl_device_memory_pool.Size;
+
+uint64_t OldData = atomic::add(Data, Size, atomic::seq_cst);
+if (OldData + Size > End)
+  __builtin_trap();

jhuber6 wrote:

Why not just return `nullptr`? Isn't that the expect failure mode for a 
`malloc` call?

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Joseph Huber via cfe-commits

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Johannes Doerfert via cfe-commits

https://github.com/jdoerfert updated 
https://github.com/llvm/llvm-project/pull/69806

>From f3e7e4008cc2acf9101721efd0b7c736b7d982c0 Mon Sep 17 00:00:00 2001
From: Johannes Doerfert 
Date: Sat, 30 Sep 2023 23:37:28 -0700
Subject: [PATCH] [OpenMP] Basic BumpAllocator for (AMD)GPUs

The patch contains a basic BumpAllocator for (AMD)GPUs to allow us to
run more tests. The allocator implements `malloc`, both internally and
externally, while we continue to default to the NVIDIA `malloc` when we
target NVIDIA GPUs. Once we have smarter or customizable allocators we
should consider this choice, for now, this allocator is better than
none. It traps if it is out of memory, making it easy to debug. Heap
size is configured via `LIBOMPTARGET_HEAP_SIZE` and defaults to 512MB.
It allows to track allocation statistics via
`LIBOMPTARGET_DEVICE_RTL_DEBUG=8` (together with
`-fopenmp-target-debug=8`). Two tests were added, and one was enabled.

This is the next step towards fixing
 https://github.com/llvm/llvm-project/issues/66708
---
 .../__clang_openmp_device_functions.h | 22 -
 openmp/docs/design/Runtimes.rst   |  1 +
 openmp/libomptarget/DeviceRTL/CMakeLists.txt  |  2 +
 .../DeviceRTL/include/Allocator.h | 44 ++
 .../libomptarget/DeviceRTL/src/Allocator.cpp  | 80 +
 openmp/libomptarget/DeviceRTL/src/Kernel.cpp  |  2 +
 openmp/libomptarget/DeviceRTL/src/State.cpp   | 45 +-
 openmp/libomptarget/include/Environment.h | 21 +
 .../plugins-nextgen/amdgpu/src/rtl.cpp| 13 ++-
 .../PluginInterface/PluginInterface.cpp   | 87 ++-
 .../common/PluginInterface/PluginInterface.h  | 11 +++
 .../plugins-nextgen/cuda/src/rtl.cpp  |  5 ++
 .../generic-elf-64bit/src/rtl.cpp |  3 +-
 .../test/mapping/lambda_mapping.cpp   |  8 +-
 openmp/libomptarget/test/offloading/malloc.c  | 37 
 .../test/offloading/malloc_parallel.c | 42 +
 16 files changed, 384 insertions(+), 39 deletions(-)
 create mode 100644 openmp/libomptarget/DeviceRTL/include/Allocator.h
 create mode 100644 openmp/libomptarget/DeviceRTL/src/Allocator.cpp
 create mode 100644 openmp/libomptarget/test/offloading/malloc.c
 create mode 100644 openmp/libomptarget/test/offloading/malloc_parallel.c

diff --git 
a/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h 
b/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
index d5b6846b0348859..d1da5c278572178 100644
--- a/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
+++ b/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
@@ -15,9 +15,19 @@
 #endif
 
 #ifdef __cplusplus
+#include 
+#include 
+#include 
 extern "C" {
+#else
+#include 
+#include 
+#include 
 #endif
 
+void *llvm_device_malloc(uint64_t Size);
+void llvm_device_free(void *Ptr);
+
 #pragma omp begin declare variant match(   
\
 device = {arch(nvptx, nvptx64)}, implementation = {extension(match_any)})
 
@@ -36,6 +46,15 @@ extern "C" {
 #pragma omp end declare variant
 
 #ifdef __AMDGCN__
+#pragma omp begin declare variant match(   
\
+device = {arch(amdgcn)},   
\
+implementation = {extension(disable_implicit_base)})
+
+void *malloc(size_t Size) { return llvm_device_malloc(Size); }
+void free(void *Ptr) { llvm_device_free(Ptr); }
+
+#pragma omp end declare variant
+
 #pragma omp begin declare variant match(device = {arch(amdgcn)})
 
 // Import types which will be used by __clang_hip_libdevice_declares.h
@@ -64,9 +83,6 @@ extern "C" {
 // need to `include ` in C++ mode.
 #ifdef __cplusplus
 
-// We require malloc/free.
-#include 
-
 #pragma push_macro("OPENMP_NOEXCEPT")
 #if __cplusplus >= 201103L
 #define OPENMP_NOEXCEPT noexcept
diff --git a/openmp/docs/design/Runtimes.rst b/openmp/docs/design/Runtimes.rst
index 4c848ca76fb8d57..62ed75797955e28 100644
--- a/openmp/docs/design/Runtimes.rst
+++ b/openmp/docs/design/Runtimes.rst
@@ -1465,3 +1465,4 @@ debugging features are supported.
 
 * Enable debugging assertions in the device. ``0x01``
 * Enable diagnosing common problems during offloading . ``0x4``
+* Enable device malloc statistics (amdgpu only). ``0x8``
diff --git a/openmp/libomptarget/DeviceRTL/CMakeLists.txt 
b/openmp/libomptarget/DeviceRTL/CMakeLists.txt
index fee2414b456a14c..f71bdeae3d7f091 100644
--- a/openmp/libomptarget/DeviceRTL/CMakeLists.txt
+++ b/openmp/libomptarget/DeviceRTL/CMakeLists.txt
@@ -83,6 +83,7 @@ endif()
 list(REMOVE_DUPLICATES LIBOMPTARGET_DEVICE_ARCHITECTURES)
 
 set(include_files
+  ${include_directory}/Allocator.h
   ${include_directory}/Configuration.h
   ${include_directory}/Debug.h
   ${include_directory}/Interface.h
@@ -95,6 +96,7 @@ set(include_files
 )
 
 set(src_files
+  ${source_directory}/Allocator.cpp
   ${source_directory}/Configuration.cpp
   

[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Johannes Doerfert via cfe-commits

https://github.com/jdoerfert updated 
https://github.com/llvm/llvm-project/pull/69806

>From 70619108a402b01c5f1f9d307a8cf21289849d74 Mon Sep 17 00:00:00 2001
From: Johannes Doerfert 
Date: Sat, 30 Sep 2023 23:37:28 -0700
Subject: [PATCH] [OpenMP] Basic BumpAllocator for (AMD)GPUs

The patch contains a basic BumpAllocator for (AMD)GPUs to allow us to
run more tests. The allocator implements `malloc`, both internally and
externally, while we continue to default to the NVIDIA `malloc` when we
target NVIDIA GPUs. Once we have smarter or customizable allocators we
should consider this choice, for now, this allocator is better than
none. It traps if it is out of memory, making it easy to debug. Heap
size is configured via `LIBOMPTARGET_HEAP_SIZE` and defaults to 512MB.
It allows to track allocation statistics via
`LIBOMPTARGET_DEVICE_RTL_DEBUG=8` (together with
`-fopenmp-target-debug=8`). Two tests were added, and one was enabled.

This is the next step towards fixing
 https://github.com/llvm/llvm-project/issues/66708
---
 .../__clang_openmp_device_functions.h | 22 -
 openmp/docs/design/Runtimes.rst   |  1 +
 openmp/libomptarget/DeviceRTL/CMakeLists.txt  |  2 +
 .../DeviceRTL/include/Allocator.h | 44 ++
 .../libomptarget/DeviceRTL/src/Allocator.cpp  | 80 +
 openmp/libomptarget/DeviceRTL/src/Kernel.cpp  |  2 +
 openmp/libomptarget/DeviceRTL/src/State.cpp   | 45 +-
 openmp/libomptarget/DeviceRTL/src/exports |  1 +
 openmp/libomptarget/include/Environment.h | 21 +
 .../plugins-nextgen/amdgpu/src/rtl.cpp| 13 ++-
 .../PluginInterface/PluginInterface.cpp   | 87 ++-
 .../common/PluginInterface/PluginInterface.h  | 11 +++
 .../plugins-nextgen/cuda/src/rtl.cpp  |  5 ++
 .../generic-elf-64bit/src/rtl.cpp |  3 +-
 .../test/mapping/lambda_mapping.cpp   |  8 +-
 openmp/libomptarget/test/offloading/malloc.c  | 37 
 .../test/offloading/malloc_parallel.c | 42 +
 17 files changed, 385 insertions(+), 39 deletions(-)
 create mode 100644 openmp/libomptarget/DeviceRTL/include/Allocator.h
 create mode 100644 openmp/libomptarget/DeviceRTL/src/Allocator.cpp
 create mode 100644 openmp/libomptarget/test/offloading/malloc.c
 create mode 100644 openmp/libomptarget/test/offloading/malloc_parallel.c

diff --git 
a/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h 
b/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
index d5b6846b0348859..d1da5c278572178 100644
--- a/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
+++ b/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
@@ -15,9 +15,19 @@
 #endif
 
 #ifdef __cplusplus
+#include 
+#include 
+#include 
 extern "C" {
+#else
+#include 
+#include 
+#include 
 #endif
 
+void *llvm_device_malloc(uint64_t Size);
+void llvm_device_free(void *Ptr);
+
 #pragma omp begin declare variant match(   
\
 device = {arch(nvptx, nvptx64)}, implementation = {extension(match_any)})
 
@@ -36,6 +46,15 @@ extern "C" {
 #pragma omp end declare variant
 
 #ifdef __AMDGCN__
+#pragma omp begin declare variant match(   
\
+device = {arch(amdgcn)},   
\
+implementation = {extension(disable_implicit_base)})
+
+void *malloc(size_t Size) { return llvm_device_malloc(Size); }
+void free(void *Ptr) { llvm_device_free(Ptr); }
+
+#pragma omp end declare variant
+
 #pragma omp begin declare variant match(device = {arch(amdgcn)})
 
 // Import types which will be used by __clang_hip_libdevice_declares.h
@@ -64,9 +83,6 @@ extern "C" {
 // need to `include ` in C++ mode.
 #ifdef __cplusplus
 
-// We require malloc/free.
-#include 
-
 #pragma push_macro("OPENMP_NOEXCEPT")
 #if __cplusplus >= 201103L
 #define OPENMP_NOEXCEPT noexcept
diff --git a/openmp/docs/design/Runtimes.rst b/openmp/docs/design/Runtimes.rst
index 4c848ca76fb8d57..62ed75797955e28 100644
--- a/openmp/docs/design/Runtimes.rst
+++ b/openmp/docs/design/Runtimes.rst
@@ -1465,3 +1465,4 @@ debugging features are supported.
 
 * Enable debugging assertions in the device. ``0x01``
 * Enable diagnosing common problems during offloading . ``0x4``
+* Enable device malloc statistics (amdgpu only). ``0x8``
diff --git a/openmp/libomptarget/DeviceRTL/CMakeLists.txt 
b/openmp/libomptarget/DeviceRTL/CMakeLists.txt
index fee2414b456a14c..f71bdeae3d7f091 100644
--- a/openmp/libomptarget/DeviceRTL/CMakeLists.txt
+++ b/openmp/libomptarget/DeviceRTL/CMakeLists.txt
@@ -83,6 +83,7 @@ endif()
 list(REMOVE_DUPLICATES LIBOMPTARGET_DEVICE_ARCHITECTURES)
 
 set(include_files
+  ${include_directory}/Allocator.h
   ${include_directory}/Configuration.h
   ${include_directory}/Debug.h
   ${include_directory}/Interface.h
@@ -95,6 +96,7 @@ set(include_files
 )
 
 set(src_files
+  ${source_directory}/Allocator.cpp
   

[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Johannes Doerfert via cfe-commits


@@ -15,9 +15,19 @@
 #endif
 
 #ifdef __cplusplus
+#include 

jdoerfert wrote:

this is not freestanding

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Joseph Huber via cfe-commits


@@ -15,9 +15,19 @@
 #endif
 
 #ifdef __cplusplus
+#include 

jhuber6 wrote:

I'm unsure if there's ever a reason to include the C++ wrappers in a 
freestanding environment. Without C++, these go straight to the `clang` 
resource directly. With the C++ versions they go through the system which 
hopefully ends up at the resource directory intact.

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Joseph Huber via cfe-commits


@@ -48,25 +48,17 @@ namespace {
 extern "C" {
 [[gnu::weak, gnu::leaf]] void *malloc(uint64_t Size);
 [[gnu::weak, gnu::leaf]] void free(void *Ptr);
-}
 
-///}
+void *llvm_device_malloc(uint64_t Size) { return allocator::alloc(Size); }
+void llvm_device_free(void *Ptr) { allocator::free(Ptr); }
 
-/// AMDGCN implementations of the shuffle sync idiom.
-///
-///{
 #pragma omp begin declare variant match(device = {arch(amdgcn)})
 
-extern "C" {
-void *malloc(uint64_t Size) {
-  // TODO: Use some preallocated space for dynamic malloc.
-  return nullptr;
-}
-
-void free(void *Ptr) {}
-}
+void *malloc(uint64_t Size) { return llvm_device_malloc(Size); }

jhuber6 wrote:

These need to be marked weak if we want them to defer to a stronger definition 
of `malloc` (e.g. one coming from `libc` if linked)

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Joseph Huber via cfe-commits


@@ -16,3 +16,4 @@ free
 memcmp
 printf
 __assert_fail
+malloc

jhuber6 wrote:

This is already in the file

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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Johannes Doerfert via cfe-commits

https://github.com/jdoerfert updated 
https://github.com/llvm/llvm-project/pull/69806

>From 50807ba3714b5556e9971f3f009fbd8bea70e15f Mon Sep 17 00:00:00 2001
From: Johannes Doerfert 
Date: Sat, 30 Sep 2023 23:37:28 -0700
Subject: [PATCH] [OpenMP] Basic BumpAllocator for (AMD)GPUs

The patch contains a basic BumpAllocator for (AMD)GPUs to allow us to
run more tests. The allocator implements `malloc`, both internally and
externally, while we continue to default to the NVIDIA `malloc` when we
target NVIDIA GPUs. Once we have smarter or customizable allocators we
should consider this choice, for now, this allocator is better than
none. It traps if it is out of memory, making it easy to debug. Heap
size is configured via `LIBOMPTARGET_HEAP_SIZE` and defaults to 512MB.
It allows to track allocation statistics via
`LIBOMPTARGET_DEVICE_RTL_DEBUG=8` (together with
`-fopenmp-target-debug=8`). Two tests were added, and one was enabled.

This is the next step towards fixing
 https://github.com/llvm/llvm-project/issues/66708
---
 .../__clang_openmp_device_functions.h | 22 -
 openmp/docs/design/Runtimes.rst   |  1 +
 openmp/libomptarget/DeviceRTL/CMakeLists.txt  |  2 +
 .../DeviceRTL/include/Allocator.h | 44 ++
 .../libomptarget/DeviceRTL/src/Allocator.cpp  | 80 +
 openmp/libomptarget/DeviceRTL/src/Kernel.cpp  |  2 +
 openmp/libomptarget/DeviceRTL/src/State.cpp   | 44 +-
 openmp/libomptarget/DeviceRTL/src/exports |  1 +
 openmp/libomptarget/include/Environment.h | 21 +
 .../plugins-nextgen/amdgpu/src/rtl.cpp| 13 ++-
 .../PluginInterface/PluginInterface.cpp   | 87 ++-
 .../common/PluginInterface/PluginInterface.h  | 11 +++
 .../plugins-nextgen/cuda/src/rtl.cpp  |  5 ++
 .../generic-elf-64bit/src/rtl.cpp |  3 +-
 .../test/mapping/lambda_mapping.cpp   |  8 +-
 openmp/libomptarget/test/offloading/malloc.c  | 37 
 .../test/offloading/malloc_parallel.c | 42 +
 17 files changed, 385 insertions(+), 38 deletions(-)
 create mode 100644 openmp/libomptarget/DeviceRTL/include/Allocator.h
 create mode 100644 openmp/libomptarget/DeviceRTL/src/Allocator.cpp
 create mode 100644 openmp/libomptarget/test/offloading/malloc.c
 create mode 100644 openmp/libomptarget/test/offloading/malloc_parallel.c

diff --git 
a/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h 
b/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
index d5b6846b0348859..d1da5c278572178 100644
--- a/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
+++ b/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
@@ -15,9 +15,19 @@
 #endif
 
 #ifdef __cplusplus
+#include 
+#include 
+#include 
 extern "C" {
+#else
+#include 
+#include 
+#include 
 #endif
 
+void *llvm_device_malloc(uint64_t Size);
+void llvm_device_free(void *Ptr);
+
 #pragma omp begin declare variant match(   
\
 device = {arch(nvptx, nvptx64)}, implementation = {extension(match_any)})
 
@@ -36,6 +46,15 @@ extern "C" {
 #pragma omp end declare variant
 
 #ifdef __AMDGCN__
+#pragma omp begin declare variant match(   
\
+device = {arch(amdgcn)},   
\
+implementation = {extension(disable_implicit_base)})
+
+void *malloc(size_t Size) { return llvm_device_malloc(Size); }
+void free(void *Ptr) { llvm_device_free(Ptr); }
+
+#pragma omp end declare variant
+
 #pragma omp begin declare variant match(device = {arch(amdgcn)})
 
 // Import types which will be used by __clang_hip_libdevice_declares.h
@@ -64,9 +83,6 @@ extern "C" {
 // need to `include ` in C++ mode.
 #ifdef __cplusplus
 
-// We require malloc/free.
-#include 
-
 #pragma push_macro("OPENMP_NOEXCEPT")
 #if __cplusplus >= 201103L
 #define OPENMP_NOEXCEPT noexcept
diff --git a/openmp/docs/design/Runtimes.rst b/openmp/docs/design/Runtimes.rst
index 4c848ca76fb8d57..62ed75797955e28 100644
--- a/openmp/docs/design/Runtimes.rst
+++ b/openmp/docs/design/Runtimes.rst
@@ -1465,3 +1465,4 @@ debugging features are supported.
 
 * Enable debugging assertions in the device. ``0x01``
 * Enable diagnosing common problems during offloading . ``0x4``
+* Enable device malloc statistics (amdgpu only). ``0x8``
diff --git a/openmp/libomptarget/DeviceRTL/CMakeLists.txt 
b/openmp/libomptarget/DeviceRTL/CMakeLists.txt
index fee2414b456a14c..f71bdeae3d7f091 100644
--- a/openmp/libomptarget/DeviceRTL/CMakeLists.txt
+++ b/openmp/libomptarget/DeviceRTL/CMakeLists.txt
@@ -83,6 +83,7 @@ endif()
 list(REMOVE_DUPLICATES LIBOMPTARGET_DEVICE_ARCHITECTURES)
 
 set(include_files
+  ${include_directory}/Allocator.h
   ${include_directory}/Configuration.h
   ${include_directory}/Debug.h
   ${include_directory}/Interface.h
@@ -95,6 +96,7 @@ set(include_files
 )
 
 set(src_files
+  ${source_directory}/Allocator.cpp
   

[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff 1cea309b7e2256746c72f3177e1a5b226bed4f83 
d30ff2ef5df686c99184eec7caf175371694cd2d -- 
openmp/libomptarget/DeviceRTL/include/Allocator.h 
openmp/libomptarget/DeviceRTL/src/Allocator.cpp 
openmp/libomptarget/test/offloading/malloc.c 
openmp/libomptarget/test/offloading/malloc_parallel.c 
clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h 
openmp/libomptarget/DeviceRTL/src/Kernel.cpp 
openmp/libomptarget/DeviceRTL/src/State.cpp 
openmp/libomptarget/include/Environment.h 
openmp/libomptarget/plugins-nextgen/amdgpu/src/rtl.cpp 
openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.cpp 
openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.h 
openmp/libomptarget/plugins-nextgen/cuda/src/rtl.cpp 
openmp/libomptarget/plugins-nextgen/generic-elf-64bit/src/rtl.cpp 
openmp/libomptarget/test/mapping/lambda_mapping.cpp
``





View the diff from clang-format here.


``diff
diff --git a/openmp/libomptarget/DeviceRTL/src/State.cpp 
b/openmp/libomptarget/DeviceRTL/src/State.cpp
index 5a21f4b47..3f829b579 100644
--- a/openmp/libomptarget/DeviceRTL/src/State.cpp
+++ b/openmp/libomptarget/DeviceRTL/src/State.cpp
@@ -28,7 +28,8 @@ using namespace ompx;
 ///{
 
 /// External symbol to access dynamic shared memory.
-[[gnu::aligned(allocator::ALIGNMENT)]] extern unsigned char 
DynamicSharedBuffer[];
+[[gnu::aligned(
+allocator::ALIGNMENT)]] extern unsigned char DynamicSharedBuffer[];
 #pragma omp allocate(DynamicSharedBuffer) allocator(omp_pteam_mem_alloc)
 
 /// The kernel environment passed to the init method by the compiler.
@@ -96,8 +97,10 @@ private:
   }
 
   /// The actual storage, shared among all warps.
-  [[gnu::aligned(allocator::ALIGNMENT)]] unsigned char 
Data[state::SharedScratchpadSize];
-  [[gnu::aligned(allocator::ALIGNMENT)]] unsigned char 
Usage[mapping::MaxThreadsPerTeam];
+  [[gnu::aligned(
+  allocator::ALIGNMENT)]] unsigned char Data[state::SharedScratchpadSize];
+  [[gnu::aligned(
+  allocator::ALIGNMENT)]] unsigned char Usage[mapping::MaxThreadsPerTeam];
 };
 
 static_assert(state::SharedScratchpadSize / mapping::MaxThreadsPerTeam <= 256,

``




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


[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Johannes Doerfert via cfe-commits

https://github.com/jdoerfert updated 
https://github.com/llvm/llvm-project/pull/69806

>From d0df9cbcb01528760c45898891e175f915dddbb1 Mon Sep 17 00:00:00 2001
From: Johannes Doerfert 
Date: Sat, 30 Sep 2023 23:37:28 -0700
Subject: [PATCH] [OpenMP] Basic BumpAllocator for (AMD)GPUs

The patch contains a basic BumpAllocator for (AMD)GPUs to allow us to
run more tests. The allocator implements `malloc`, both internally and
externally, while we continue to default to the NVIDIA `malloc` when we
target NVIDIA GPUs. Once we have smarter or customizable allocators we
should consider this choice, for now, this allocator is better than
none. It traps if it is out of memory, making it easy to debug. Heap
size is configured via `LIBOMPTARGET_HEAP_SIZE` and defaults to 512MB.
It allows to track allocation statistics via
`LIBOMPTARGET_DEVICE_RTL_DEBUG=8` (together with
`-fopenmp-target-debug=8`). Two tests were added, and one was enabled.

This is the next step towards fixing
 https://github.com/llvm/llvm-project/issues/66708
---
 .../__clang_openmp_device_functions.h | 22 -
 openmp/docs/design/Runtimes.rst   |  1 +
 openmp/libomptarget/DeviceRTL/CMakeLists.txt  |  2 +
 .../DeviceRTL/include/Allocator.h | 44 ++
 .../libomptarget/DeviceRTL/src/Allocator.cpp  | 80 +
 openmp/libomptarget/DeviceRTL/src/Kernel.cpp  |  2 +
 openmp/libomptarget/DeviceRTL/src/State.cpp   | 41 -
 openmp/libomptarget/DeviceRTL/src/exports |  1 +
 openmp/libomptarget/include/Environment.h | 21 +
 .../plugins-nextgen/amdgpu/src/rtl.cpp| 13 ++-
 .../PluginInterface/PluginInterface.cpp   | 87 ++-
 .../common/PluginInterface/PluginInterface.h  | 11 +++
 .../plugins-nextgen/cuda/src/rtl.cpp  |  5 ++
 .../generic-elf-64bit/src/rtl.cpp |  3 +-
 .../test/mapping/lambda_mapping.cpp   |  8 +-
 openmp/libomptarget/test/offloading/malloc.c  | 37 
 .../test/offloading/malloc_parallel.c | 42 +
 17 files changed, 382 insertions(+), 38 deletions(-)
 create mode 100644 openmp/libomptarget/DeviceRTL/include/Allocator.h
 create mode 100644 openmp/libomptarget/DeviceRTL/src/Allocator.cpp
 create mode 100644 openmp/libomptarget/test/offloading/malloc.c
 create mode 100644 openmp/libomptarget/test/offloading/malloc_parallel.c

diff --git 
a/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h 
b/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
index d5b6846b0348859..d1da5c278572178 100644
--- a/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
+++ b/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
@@ -15,9 +15,19 @@
 #endif
 
 #ifdef __cplusplus
+#include 
+#include 
+#include 
 extern "C" {
+#else
+#include 
+#include 
+#include 
 #endif
 
+void *llvm_device_malloc(uint64_t Size);
+void llvm_device_free(void *Ptr);
+
 #pragma omp begin declare variant match(   
\
 device = {arch(nvptx, nvptx64)}, implementation = {extension(match_any)})
 
@@ -36,6 +46,15 @@ extern "C" {
 #pragma omp end declare variant
 
 #ifdef __AMDGCN__
+#pragma omp begin declare variant match(   
\
+device = {arch(amdgcn)},   
\
+implementation = {extension(disable_implicit_base)})
+
+void *malloc(size_t Size) { return llvm_device_malloc(Size); }
+void free(void *Ptr) { llvm_device_free(Ptr); }
+
+#pragma omp end declare variant
+
 #pragma omp begin declare variant match(device = {arch(amdgcn)})
 
 // Import types which will be used by __clang_hip_libdevice_declares.h
@@ -64,9 +83,6 @@ extern "C" {
 // need to `include ` in C++ mode.
 #ifdef __cplusplus
 
-// We require malloc/free.
-#include 
-
 #pragma push_macro("OPENMP_NOEXCEPT")
 #if __cplusplus >= 201103L
 #define OPENMP_NOEXCEPT noexcept
diff --git a/openmp/docs/design/Runtimes.rst b/openmp/docs/design/Runtimes.rst
index 4c848ca76fb8d57..62ed75797955e28 100644
--- a/openmp/docs/design/Runtimes.rst
+++ b/openmp/docs/design/Runtimes.rst
@@ -1465,3 +1465,4 @@ debugging features are supported.
 
 * Enable debugging assertions in the device. ``0x01``
 * Enable diagnosing common problems during offloading . ``0x4``
+* Enable device malloc statistics (amdgpu only). ``0x8``
diff --git a/openmp/libomptarget/DeviceRTL/CMakeLists.txt 
b/openmp/libomptarget/DeviceRTL/CMakeLists.txt
index fee2414b456a14c..f71bdeae3d7f091 100644
--- a/openmp/libomptarget/DeviceRTL/CMakeLists.txt
+++ b/openmp/libomptarget/DeviceRTL/CMakeLists.txt
@@ -83,6 +83,7 @@ endif()
 list(REMOVE_DUPLICATES LIBOMPTARGET_DEVICE_ARCHITECTURES)
 
 set(include_files
+  ${include_directory}/Allocator.h
   ${include_directory}/Configuration.h
   ${include_directory}/Debug.h
   ${include_directory}/Interface.h
@@ -95,6 +96,7 @@ set(include_files
 )
 
 set(src_files
+  ${source_directory}/Allocator.cpp
   

[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-openmp

Author: Johannes Doerfert (jdoerfert)


Changes

The patch contains a basic BumpAllocator for (AMD)GPUs to allow us to run more 
tests. The allocator implements `malloc`, both internally and externally, while 
we continue to default to the NVIDIA `malloc` when we target NVIDIA GPUs. Once 
we have smarter or customizable allocators we should consider this choice, for 
now, this allocator is better than none. It traps if it is out of memory, 
making it easy to debug. Heap size is configured via `LIBOMPTARGET_HEAP_SIZE` 
and defaults to 512MB. It allows to track allocation statistics via
`LIBOMPTARGET_DEVICE_RTL_DEBUG=8` (together with
`-fopenmp-target-debug=8`). Two tests were added, and one was enabled.

This is the next step towards fixing
 https://github.com/llvm/llvm-project/issues/66708

---

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


17 Files Affected:

- (modified) 
clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h (+16-4) 
- (modified) openmp/docs/design/Runtimes.rst (+1) 
- (modified) openmp/libomptarget/DeviceRTL/CMakeLists.txt (+2) 
- (added) openmp/libomptarget/DeviceRTL/include/Allocator.h (+44) 
- (added) openmp/libomptarget/DeviceRTL/src/Allocator.cpp (+80) 
- (modified) openmp/libomptarget/DeviceRTL/src/Kernel.cpp (+2) 
- (modified) openmp/libomptarget/DeviceRTL/src/State.cpp (+17-24) 
- (modified) openmp/libomptarget/DeviceRTL/src/exports (+1) 
- (modified) openmp/libomptarget/include/Environment.h (+21) 
- (modified) openmp/libomptarget/plugins-nextgen/amdgpu/src/rtl.cpp (+11-2) 
- (modified) 
openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.cpp 
(+83-4) 
- (modified) 
openmp/libomptarget/plugins-nextgen/common/PluginInterface/PluginInterface.h 
(+11) 
- (modified) openmp/libomptarget/plugins-nextgen/cuda/src/rtl.cpp (+5) 
- (modified) openmp/libomptarget/plugins-nextgen/generic-elf-64bit/src/rtl.cpp 
(+2-1) 
- (modified) openmp/libomptarget/test/mapping/lambda_mapping.cpp (+4-4) 
- (added) openmp/libomptarget/test/offloading/malloc.c (+37) 
- (added) openmp/libomptarget/test/offloading/malloc_parallel.c (+42) 


``diff
diff --git 
a/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h 
b/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
index d5b6846b0348859..54497ede9721484 100644
--- a/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
+++ b/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
@@ -15,9 +15,19 @@
 #endif
 
 #ifdef __cplusplus
+#include 
+#include 
+#include 
 extern "C" {
+#else
+#include 
+#include 
+#include 
 #endif
 
+void *llvm_device_malloc(uint64_t Size);
+void llvm_device_free(void *Ptr);
+
 #pragma omp begin declare variant match(   
\
 device = {arch(nvptx, nvptx64)}, implementation = {extension(match_any)})
 
@@ -36,7 +46,12 @@ extern "C" {
 #pragma omp end declare variant
 
 #ifdef __AMDGCN__
-#pragma omp begin declare variant match(device = {arch(amdgcn)})
+#pragma omp begin declare variant match(   
\
+device = {arch(amdgcn)},   
\
+implementation = {extension(disable_implicit_base)})
+
+void *malloc(size_t Size) { return llvm_device_malloc(Size); }
+void free(void *Ptr) { llvm_device_free(Ptr); }
 
 // Import types which will be used by __clang_hip_libdevice_declares.h
 #ifndef __cplusplus
@@ -64,9 +79,6 @@ extern "C" {
 // need to `include ` in C++ mode.
 #ifdef __cplusplus
 
-// We require malloc/free.
-#include 
-
 #pragma push_macro("OPENMP_NOEXCEPT")
 #if __cplusplus >= 201103L
 #define OPENMP_NOEXCEPT noexcept
diff --git a/openmp/docs/design/Runtimes.rst b/openmp/docs/design/Runtimes.rst
index 4c848ca76fb8d57..62ed75797955e28 100644
--- a/openmp/docs/design/Runtimes.rst
+++ b/openmp/docs/design/Runtimes.rst
@@ -1465,3 +1465,4 @@ debugging features are supported.
 
 * Enable debugging assertions in the device. ``0x01``
 * Enable diagnosing common problems during offloading . ``0x4``
+* Enable device malloc statistics (amdgpu only). ``0x8``
diff --git a/openmp/libomptarget/DeviceRTL/CMakeLists.txt 
b/openmp/libomptarget/DeviceRTL/CMakeLists.txt
index fee2414b456a14c..f71bdeae3d7f091 100644
--- a/openmp/libomptarget/DeviceRTL/CMakeLists.txt
+++ b/openmp/libomptarget/DeviceRTL/CMakeLists.txt
@@ -83,6 +83,7 @@ endif()
 list(REMOVE_DUPLICATES LIBOMPTARGET_DEVICE_ARCHITECTURES)
 
 set(include_files
+  ${include_directory}/Allocator.h
   ${include_directory}/Configuration.h
   ${include_directory}/Debug.h
   ${include_directory}/Interface.h
@@ -95,6 +96,7 @@ set(include_files
 )
 
 set(src_files
+  ${source_directory}/Allocator.cpp
   ${source_directory}/Configuration.cpp
   ${source_directory}/Debug.cpp
   ${source_directory}/Kernel.cpp
diff --git 

[clang] [OpenMP] Basic BumpAllocator for (AMD)GPUs (PR #69806)

2023-10-20 Thread Johannes Doerfert via cfe-commits

https://github.com/jdoerfert created 
https://github.com/llvm/llvm-project/pull/69806

The patch contains a basic BumpAllocator for (AMD)GPUs to allow us to run more 
tests. The allocator implements `malloc`, both internally and externally, while 
we continue to default to the NVIDIA `malloc` when we target NVIDIA GPUs. Once 
we have smarter or customizable allocators we should consider this choice, for 
now, this allocator is better than none. It traps if it is out of memory, 
making it easy to debug. Heap size is configured via `LIBOMPTARGET_HEAP_SIZE` 
and defaults to 512MB. It allows to track allocation statistics via
`LIBOMPTARGET_DEVICE_RTL_DEBUG=8` (together with
`-fopenmp-target-debug=8`). Two tests were added, and one was enabled.

This is the next step towards fixing
 https://github.com/llvm/llvm-project/issues/66708

>From d30ff2ef5df686c99184eec7caf175371694cd2d Mon Sep 17 00:00:00 2001
From: Johannes Doerfert 
Date: Sat, 30 Sep 2023 23:37:28 -0700
Subject: [PATCH] [OpenMP] Basic BumpAllocator for (AMD)GPUs

The patch contains a basic BumpAllocator for (AMD)GPUs to allow us to
run more tests. The allocator implements `malloc`, both internally and
externally, while we continue to default to the NVIDIA `malloc` when we
target NVIDIA GPUs. Once we have smarter or customizable allocators we
should consider this choice, for now, this allocator is better than
none. It traps if it is out of memory, making it easy to debug. Heap
size is configured via `LIBOMPTARGET_HEAP_SIZE` and defaults to 512MB.
It allows to track allocation statistics via
`LIBOMPTARGET_DEVICE_RTL_DEBUG=8` (together with
`-fopenmp-target-debug=8`). Two tests were added, and one was enabled.

This is the next step towards fixing
 https://github.com/llvm/llvm-project/issues/66708
---
 .../__clang_openmp_device_functions.h | 20 -
 openmp/docs/design/Runtimes.rst   |  1 +
 openmp/libomptarget/DeviceRTL/CMakeLists.txt  |  2 +
 .../DeviceRTL/include/Allocator.h | 44 ++
 .../libomptarget/DeviceRTL/src/Allocator.cpp  | 80 +
 openmp/libomptarget/DeviceRTL/src/Kernel.cpp  |  2 +
 openmp/libomptarget/DeviceRTL/src/State.cpp   | 41 -
 openmp/libomptarget/DeviceRTL/src/exports |  1 +
 openmp/libomptarget/include/Environment.h | 21 +
 .../plugins-nextgen/amdgpu/src/rtl.cpp| 13 ++-
 .../PluginInterface/PluginInterface.cpp   | 87 ++-
 .../common/PluginInterface/PluginInterface.h  | 11 +++
 .../plugins-nextgen/cuda/src/rtl.cpp  |  5 ++
 .../generic-elf-64bit/src/rtl.cpp |  3 +-
 .../test/mapping/lambda_mapping.cpp   |  8 +-
 openmp/libomptarget/test/offloading/malloc.c  | 37 
 .../test/offloading/malloc_parallel.c | 42 +
 17 files changed, 379 insertions(+), 39 deletions(-)
 create mode 100644 openmp/libomptarget/DeviceRTL/include/Allocator.h
 create mode 100644 openmp/libomptarget/DeviceRTL/src/Allocator.cpp
 create mode 100644 openmp/libomptarget/test/offloading/malloc.c
 create mode 100644 openmp/libomptarget/test/offloading/malloc_parallel.c

diff --git 
a/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h 
b/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
index d5b6846b0348859..54497ede9721484 100644
--- a/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
+++ b/clang/lib/Headers/openmp_wrappers/__clang_openmp_device_functions.h
@@ -15,9 +15,19 @@
 #endif
 
 #ifdef __cplusplus
+#include 
+#include 
+#include 
 extern "C" {
+#else
+#include 
+#include 
+#include 
 #endif
 
+void *llvm_device_malloc(uint64_t Size);
+void llvm_device_free(void *Ptr);
+
 #pragma omp begin declare variant match(   
\
 device = {arch(nvptx, nvptx64)}, implementation = {extension(match_any)})
 
@@ -36,7 +46,12 @@ extern "C" {
 #pragma omp end declare variant
 
 #ifdef __AMDGCN__
-#pragma omp begin declare variant match(device = {arch(amdgcn)})
+#pragma omp begin declare variant match(   
\
+device = {arch(amdgcn)},   
\
+implementation = {extension(disable_implicit_base)})
+
+void *malloc(size_t Size) { return llvm_device_malloc(Size); }
+void free(void *Ptr) { llvm_device_free(Ptr); }
 
 // Import types which will be used by __clang_hip_libdevice_declares.h
 #ifndef __cplusplus
@@ -64,9 +79,6 @@ extern "C" {
 // need to `include ` in C++ mode.
 #ifdef __cplusplus
 
-// We require malloc/free.
-#include 
-
 #pragma push_macro("OPENMP_NOEXCEPT")
 #if __cplusplus >= 201103L
 #define OPENMP_NOEXCEPT noexcept
diff --git a/openmp/docs/design/Runtimes.rst b/openmp/docs/design/Runtimes.rst
index 4c848ca76fb8d57..62ed75797955e28 100644
--- a/openmp/docs/design/Runtimes.rst
+++ b/openmp/docs/design/Runtimes.rst
@@ -1465,3 +1465,4 @@ debugging features are supported.
 
 * Enable debugging assertions in the device. ``0x01``
  

[clang-tools-extra] [clang][dataflow]Use cast_or_null instead of cast to prevent crash (PR #68510)

2023-10-20 Thread Qizhi Hu via cfe-commits

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


[clang] 14bc11a - [clang][dataflow]Use cast_or_null instead of cast to prevent crash (#68510)

2023-10-20 Thread via cfe-commits

Author: Qizhi Hu
Date: 2023-10-21T09:39:30+08:00
New Revision: 14bc11a651971bbbdf96565898be2c94fa2b1cf5

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

LOG: [clang][dataflow]Use cast_or_null instead of cast to prevent crash (#68510)

`getStorageLocation` may return `nullptr` and this will produce crash
when use `cast`, use `dyn_cast_or_null` instead. I test it locally using
[FTXUI](https://github.com/ArthurSonzogni/FTXUI) and it may be the cause
of issue [issue](https://github.com/llvm/llvm-project/issues/68412), but
I am not sure.

Co-authored-by: huqizhi 

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/unchecked-optional-access/absl/types/optional.h

clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 59e096282e77917..b5348384e965ab5 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -219,6 +219,10 @@ Changes in existing checks
   ` check, so that it does not
   warn on macros starting with underscore and lowercase letter.
 
+- Improved :doc:`bugprone-unchecked-optional-access
+  ` check, so that it 
does
+  not crash during handling of optional values.
+
 - Improved :doc:`bugprone-undefined-memory-manipulation
   ` check to support
   fixed-size arrays of non-trivial types.

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/unchecked-optional-access/absl/types/optional.h
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/unchecked-optional-access/absl/types/optional.h
index 154cc262ab7cd79..3e692f347aa1ea5 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/unchecked-optional-access/absl/types/optional.h
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/Inputs/unchecked-optional-access/absl/types/optional.h
@@ -66,6 +66,8 @@ class optional {
   void reset() noexcept;
 
   void swap(optional ) noexcept;
+
+  template  optional =(const U );
 };
 
 } // namespace absl

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp
index 1921291f2187d92..13a3ff52f3ebc59 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp
@@ -180,3 +180,23 @@ void std_forward_rvalue_ref_safe(absl::optional&& 
opt) {
 
   std::forward>(opt).value();
 }
+
+namespace std {
+
+template  class vector {
+public:
+  T [](unsigned long index);
+  bool empty();
+};
+
+} // namespace std
+
+struct S {
+  absl::optional x;
+};
+std::vector vec;
+
+void foo() {
+  if (!vec.empty())
+vec[0].x = 0;
+}

diff  --git 
a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp 
b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
index f61f26ff27804ec..8bd9a030f50cda0 100644
--- a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -599,7 +599,7 @@ void transferAssignment(const CXXOperatorCallExpr *E, 
BoolValue ,
 LatticeTransferState ) {
   assert(E->getNumArgs() > 0);
 
-  if (auto *Loc = cast(
+  if (auto *Loc = cast_or_null(
   State.Env.getStorageLocation(*E->getArg(0 {
 createOptionalValue(*Loc, HasValueVal, State.Env);
 

diff  --git 
a/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
index c41a378a8341b71..76af8baba851839 100644
--- 
a/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ 
b/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -2131,6 +2131,24 @@ TEST_P(UncheckedOptionalAccessTest, OptionalSwap) {
   )");
 }
 
+TEST_P(UncheckedOptionalAccessTest, OptionalReturnedFromFuntionCall) {
+  ExpectDiagnosticsFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+
+struct S {
+  $ns::$optional x;
+} s;
+S getOptional() {
+  return s;
+}
+
+void target() {
+  getOptional().x = 0;
+}
+  )");
+}
+
 TEST_P(UncheckedOptionalAccessTest, StdSwap) {
   ExpectDiagnosticsFor(
   R"(



___
cfe-commits mailing list

[clang] [flang][driver] support -dumpversion and -dumpmachine (PR #68896)

2023-10-20 Thread Yuanfang Chen via cfe-commits

yuanfang-chen wrote:

> You are adding a support for these new flags in `flang-new`, which is 
> implemented in terms of `clangDriver` - this scenario (i.e. the two projects 
> being out of sync) would be very unlikely at the moment (perhaps even 
> impossible). And even if that was desired, you'd need to update Flang's 
> driver too. I'd rather keep this to the required minimum. If you really want 
> to keep this, you will need to update flang/tools/flang-driver/driver.cpp too.

Thanks for the explanation. I've updated the patch.

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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

2023-10-20 Thread Owen Pan via cfe-commits
=?utf-8?q?Björn_Schäpers?= 
Message-ID:
In-Reply-To: 


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


[clang] [flang][driver] support -dumpversion and -dumpmachine (PR #68896)

2023-10-20 Thread Yuanfang Chen via cfe-commits

https://github.com/yuanfang-chen updated 
https://github.com/llvm/llvm-project/pull/68896

>From db72a97acc7fd5a517b5ccd525fcf8a7b714fa29 Mon Sep 17 00:00:00 2001
From: Yuanfang Chen 
Date: Sat, 21 Oct 2023 01:18:47 +
Subject: [PATCH] [flang][driver] support -dumpversion and -dumpmachine

Match GCC driver. GCC has -cc1/-fc1 support too, but this patch does not 
address that.
---
 clang/include/clang/Driver/Options.td| 8 ++--
 flang/test/Driver/driver-help-hidden.f90 | 2 ++
 flang/test/Driver/driver-help.f90| 2 ++
 flang/test/Driver/dumpmachine.f90| 8 
 flang/test/Driver/immediate-options.f90  | 2 ++
 5 files changed, 20 insertions(+), 2 deletions(-)
 create mode 100644 flang/test/Driver/dumpmachine.f90
 create mode 100644 flang/test/Driver/immediate-options.f90

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c272a7f1c398aa6..cae7bd07fc3cc54 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1375,9 +1375,13 @@ def dsym_dir : JoinedOrSeparate<["-"], "dsym-dir">,
 def dumpdir : Separate<["-"], "dumpdir">, Visibility<[ClangOption, CC1Option]>,
   MetaVarName<"">,
   HelpText<"Use  as a prefix to form auxiliary and dump file names">;
-def dumpmachine : Flag<["-"], "dumpmachine">;
+def dumpmachine : Flag<["-"], "dumpmachine">,
+  Visibility<[ClangOption, FlangOption]>,
+  HelpText<"Display the compiler's target processor">;
+def dumpversion : Flag<["-"], "dumpversion">,
+  Visibility<[ClangOption, FlangOption]>,
+  HelpText<"Display the version of the compiler">;
 def dumpspecs : Flag<["-"], "dumpspecs">, Flags<[Unsupported]>;
-def dumpversion : Flag<["-"], "dumpversion">;
 def dylib__file : Separate<["-"], "dylib_file">;
 def dylinker__install__name : JoinedOrSeparate<["-"], "dylinker_install_name">;
 def dylinker : Flag<["-"], "dylinker">;
diff --git a/flang/test/Driver/driver-help-hidden.f90 
b/flang/test/Driver/driver-help-hidden.f90
index 807b0f938d27b5c..caea8880ba8fb8e 100644
--- a/flang/test/Driver/driver-help-hidden.f90
+++ b/flang/test/Driver/driver-help-hidden.f90
@@ -21,6 +21,8 @@
 ! CHECK-NEXT: -ccc-print-phases   Dump list of actions to perform
 ! CHECK-NEXT: -cppEnable predefined and command line 
preprocessor macros
 ! CHECK-NEXT: -c  Only run preprocess, compile, and 
assemble steps
+! CHECK-NEXT: -dumpmachineDisplay the compiler's target processor
+! CHECK-NEXT: -dumpversionDisplay the version of the compiler
 ! CHECK-NEXT: -D =  Define  to  (or 1 if 
 omitted)
 ! CHECK-NEXT: -emit-llvm  Use the LLVM representation for 
assembler and object files
 ! CHECK-NEXT: -E  Only run the preprocessor
diff --git a/flang/test/Driver/driver-help.f90 
b/flang/test/Driver/driver-help.f90
index 4894f90f5310439..1580c267cfc6ae6 100644
--- a/flang/test/Driver/driver-help.f90
+++ b/flang/test/Driver/driver-help.f90
@@ -17,6 +17,8 @@
 ! HELP-NEXT: -###Print (but do not run) the commands to 
run for this compilation
 ! HELP-NEXT: -cppEnable predefined and command line 
preprocessor macros
 ! HELP-NEXT: -c  Only run preprocess, compile, and 
assemble steps
+! HELP-NEXT: -dumpmachineDisplay the compiler's target processor
+! HELP-NEXT: -dumpversionDisplay the version of the compiler
 ! HELP-NEXT: -D =  Define  to  (or 1 if 
 omitted)
 ! HELP-NEXT: -emit-llvm  Use the LLVM representation for assembler 
and object files
 ! HELP-NEXT: -E  Only run the preprocessor
diff --git a/flang/test/Driver/dumpmachine.f90 
b/flang/test/Driver/dumpmachine.f90
new file mode 100644
index 000..b68705707eefa04
--- /dev/null
+++ b/flang/test/Driver/dumpmachine.f90
@@ -0,0 +1,8 @@
+! Test that -dumpmachine prints the target triple.
+
+! Note: Debian GCC may omit "unknown-".
+! RUN: %flang --target=x86_64-linux-gnu -dumpmachine | FileCheck %s 
--check-prefix=X86_64
+! X86_64: x86_64-unknown-linux-gnu
+
+! RUN: %flang --target=xxx-pc-freebsd -dumpmachine | FileCheck %s 
--check-prefix=FREEBSD
+! FREEBSD: xxx-pc-freebsd
diff --git a/flang/test/Driver/immediate-options.f90 
b/flang/test/Driver/immediate-options.f90
new file mode 100644
index 000..81c1e7181ba7935
--- /dev/null
+++ b/flang/test/Driver/immediate-options.f90
@@ -0,0 +1,2 @@
+! RUN: %flang -dumpversion | FileCheck %s -check-prefix=DUMPVERSION
+! DUMPVERSION: {{[0-9]+\.[0-9.]+}}

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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

2023-10-20 Thread Owen Pan via cfe-commits
=?utf-8?q?Bj=C3=B6rn_Sch=C3=A4pers?= 
Message-ID:
In-Reply-To: 



@@ -1118,16 +1121,39 @@ void WhitespaceManager::alignTrailingComments() {
   }
 }
 
-// We don't want to align namespace end comments.
-const bool DontAlignThisComment =
-I > 0 && C.NewlinesBefore == 0 &&
-Changes[I - 1].Tok->is(TT_NamespaceRBrace);
-if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
-DontAlignThisComment) {
+// We don't want to align comments which end a scope, which are here
+// identified by most closing braces.
+const bool DontAlignThisComment = [&] {
+  if (I == 0 || C.NewlinesBefore > 0)
+return false;
+  const auto *Tok = Changes[I - 1].Tok;
+  if (Tok->is(tok::semi)) {
+Tok = Tok->getPreviousNonComment();
+if (!Tok)
+  return false;
+  }
+  if (Tok->isNot(tok::r_brace)) {
+if (Tok->isNot(tok::r_paren) || !Tok->MatchingParen)
+  return false;
+auto BeforeParent = Tok->MatchingParen->getPreviousNonComment();
+return BeforeParent && BeforeParent->is(TT_DoWhile);
+  }
+
+  for (auto Prev = Tok->getPreviousNonComment();
+   Prev && Prev->is(tok::r_brace);
+   Prev = Tok->getPreviousNonComment()) {
+Tok = Prev;
+  }
+  return Tok->NewlinesBefore > 0;
+}();
+
+if (DontAlignThisComment) {

owenca wrote:

```suggestion
};

if (I > 0 && C.NewlinesBefore == 0 &&
DontAlignThisComment(Changes[I - 1].Tok)) {
```

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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

2023-10-20 Thread Owen Pan via cfe-commits
=?utf-8?q?Björn_Schäpers?= 
Message-ID:
In-Reply-To: 



@@ -1118,16 +1121,39 @@ void WhitespaceManager::alignTrailingComments() {
   }
 }
 
-// We don't want to align namespace end comments.
-const bool DontAlignThisComment =
-I > 0 && C.NewlinesBefore == 0 &&
-Changes[I - 1].Tok->is(TT_NamespaceRBrace);
-if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
-DontAlignThisComment) {
+// We don't want to align comments which end a scope, which are here
+// identified by most closing braces.
+const bool DontAlignThisComment = [&] {
+  if (I == 0 || C.NewlinesBefore > 0)
+return false;
+  const auto *Tok = Changes[I - 1].Tok;
+  if (Tok->is(tok::semi)) {
+Tok = Tok->getPreviousNonComment();
+if (!Tok)
+  return false;
+  }
+  if (Tok->isNot(tok::r_brace)) {
+if (Tok->isNot(tok::r_paren) || !Tok->MatchingParen)
+  return false;
+auto BeforeParent = Tok->MatchingParen->getPreviousNonComment();
+return BeforeParent && BeforeParent->is(TT_DoWhile);
+  }
+
+  for (auto Prev = Tok->getPreviousNonComment();
+   Prev && Prev->is(tok::r_brace);
+   Prev = Tok->getPreviousNonComment()) {
+Tok = Prev;
+  }

owenca wrote:

```suggestion
  if (Tok->is(tok::r_paren)) {
// Back up past the parentheses and a `TT_DoWhile` that may precede.
Tok = Tok->MatchingParen;
if (!Tok)
  return false;
Tok = Tok->getPreviousNonComment();
if (!Tok)
  return false;
if (Tok->is(TT_DoWhile)) {
  Tok = Tok->getPreviousNonComment();
  if (!Tok)
return false;
}
  }
  if (Tok->isNot(tok::r_brace))
return false;
  while (Tok->Previous && Tok->Previous->is(tok::r_brace))
Tok = Tok->Previous;
```
Because we should also cover `}(); //` for lambdas.

FWIW, I don't think we need to use `getPreviousNonComment()` when looking for 
consecutive closing braces unless we want to handle something like `} /* foo */ 
} //`.

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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

2023-10-20 Thread Owen Pan via cfe-commits
=?utf-8?q?Bj=C3=B6rn_Sch=C3=A4pers?= 
Message-ID:
In-Reply-To: 



@@ -1118,16 +1121,39 @@ void WhitespaceManager::alignTrailingComments() {
   }
 }
 
-// We don't want to align namespace end comments.
-const bool DontAlignThisComment =
-I > 0 && C.NewlinesBefore == 0 &&
-Changes[I - 1].Tok->is(TT_NamespaceRBrace);
-if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
-DontAlignThisComment) {
+// We don't want to align comments which end a scope, which are here
+// identified by most closing braces.
+const bool DontAlignThisComment = [&] {
+  if (I == 0 || C.NewlinesBefore > 0)
+return false;
+  const auto *Tok = Changes[I - 1].Tok;

owenca wrote:

```suggestion
auto DontAlignThisComment = [](const auto *Tok) {
```

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


[clang] [libc++] Implement ranges::contains (PR #65148)

2023-10-20 Thread via cfe-commits

https://github.com/ZijunZhaoCCK updated 
https://github.com/llvm/llvm-project/pull/65148

>From 02e9afd761228f401df4d9f8dfaaca44ffae0c6e Mon Sep 17 00:00:00 2001
From: zijunzhao 
Date: Thu, 31 Aug 2023 20:08:32 +
Subject: [PATCH 01/16] [libc++] Implement ranges::contains

Differential Revision: https://reviews.llvm.org/D159232
---
 libcxx/include/CMakeLists.txt |   1 +
 libcxx/include/__algorithm/ranges_contains.h  |  60 ++
 libcxx/include/algorithm  |   9 +
 ...obust_against_copying_projections.pass.cpp |   4 +
 .../alg.contains/ranges.contains.pass.cpp | 190 ++
 .../niebloid.compile.pass.cpp |   1 +
 6 files changed, 265 insertions(+)
 create mode 100644 libcxx/include/__algorithm/ranges_contains.h
 create mode 100644 
libcxx/test/std/algorithms/alg.nonmodifying/alg.contains/ranges.contains.pass.cpp

diff --git a/libcxx/include/CMakeLists.txt b/libcxx/include/CMakeLists.txt
index 77a7269121ec142..024aa8959fb7200 100644
--- a/libcxx/include/CMakeLists.txt
+++ b/libcxx/include/CMakeLists.txt
@@ -104,6 +104,7 @@ set(files
   __algorithm/ranges_any_of.h
   __algorithm/ranges_binary_search.h
   __algorithm/ranges_clamp.h
+  __algorithm/ranges_contains.h
   __algorithm/ranges_copy.h
   __algorithm/ranges_copy_backward.h
   __algorithm/ranges_copy_if.h
diff --git a/libcxx/include/__algorithm/ranges_contains.h 
b/libcxx/include/__algorithm/ranges_contains.h
new file mode 100644
index 000..647b7ea34be3421
--- /dev/null
+++ b/libcxx/include/__algorithm/ranges_contains.h
@@ -0,0 +1,60 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+#ifndef _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
+#define _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
+
+#include <__algorithm/in_in_result.h>
+#include <__algorithm/ranges_find.h>
+#include <__config>
+#include <__functional/identity.h>
+#include <__functional/ranges_operations.h>
+#include <__functional/reference_wrapper.h>
+#include <__iterator/concepts.h>
+#include <__iterator/indirectly_comparable.h>
+#include <__iterator/projected.h>
+#include <__ranges/access.h>
+#include <__ranges/concepts.h>
+#include <__utility/move.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+#if _LIBCPP_STD_VER >= 23
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+namespace ranges {
+namespace __contains {
+struct __fn {
+  template  _Sent, class _Type, 
class _Proj = identity>
+requires indirect_binary_predicate, const _Type*>
+  _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr bool
+  operator()(_Iter __first, _Sent __last, const _Type& __value, _Proj __proj = 
{}) const {
+return ranges::find(std::move(__first), std::move(__last), __value, 
std::ref(__proj)) != __last;
+  }
+
+  template 
+requires indirect_binary_predicate, _Proj>, const _Type*>
+  _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr bool
+  operator()(_Range&& __range, const _Type& __value, _Proj __proj = {}) const {
+return ranges::find(ranges::begin(__range), ranges::end(__range), __value, 
std::ref(__proj)) != ranges::end(__range);
+  }
+};
+} // namespace __contains
+inline namespace __cpo {
+inline constexpr auto contains = __contains::__fn{};
+} // namespace __cpo
+} // namespace ranges
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP_STD_VER >= 23
+
+#endif // _LIBCPP___ALGORITHM_RANGES_CONTAINS_H
diff --git a/libcxx/include/algorithm b/libcxx/include/algorithm
index 76e0d22bf73ef85..003bf132b38b4d8 100644
--- a/libcxx/include/algorithm
+++ b/libcxx/include/algorithm
@@ -226,6 +226,14 @@ namespace ranges {
   template
 using copy_backward_result = in_out_result;
 // since C++20
 
+  template S, class T, class Proj = identity>
+requires indirect_binary_predicate, 
const T*>
+constexpr bool ranges::contains(I first, S last, const T& value, Proj proj 
= {});   // since C++23
+
+  template
+requires indirect_binary_predicate, Proj>, const T*>
+constexpr bool ranges::contains(R&& r, const T& value, Proj proj = {});
 // since C++23
+
   template S, weakly_incrementable O>
 requires indirectly_copyable
 constexpr ranges::copy_result ranges::copy(I first, S last, O 
result);// since C++20
@@ -1827,6 +1835,7 @@ template 
 #include <__algorithm/ranges_any_of.h>
 #include <__algorithm/ranges_binary_search.h>
 #include <__algorithm/ranges_clamp.h>
+#include <__algorithm/ranges_contains.h>
 #include <__algorithm/ranges_copy.h>
 #include <__algorithm/ranges_copy_backward.h>
 #include <__algorithm/ranges_copy_if.h>
diff --git 

[clang-tools-extra] [clang-tidy] Support functional cast in bugprone-dangling-handle (PR #69067)

2023-10-20 Thread Congcong Cai via cfe-commits


@@ -33,14 +33,19 @@ handleFrom(const 
ast_matchers::internal::Matcher ,
 
 ast_matchers::internal::Matcher handleFromTemporaryValue(
 const ast_matchers::internal::Matcher ) {
+
+  const auto TemporaryExpr =
+  anyOf(cxxBindTemporaryExpr(),
+cxxFunctionalCastExpr(hasCastKind(CK_ConstructorConversion),
+  
hasSourceExpression(cxxBindTemporaryExpr(;

HerrCai0907 wrote:

Should be  `ignorePareImpCast(cxxBindTemporaryExpr)`

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


[clang] [clang] Implement constexpr bit_cast for vectors (PR #66894)

2023-10-20 Thread Richard Smith via cfe-commits


@@ -140,11 +140,12 @@ void g28(void) {
   typedef short v12i16 __attribute((vector_size(24)));
   typedef long double v2f80 __attribute((vector_size(24)));
   // CHECK: @g28.a = internal global <1 x i64> 
-  // CHECK: @g28.b = internal global <12 x i16> 
-  // CHECK: @g28.c = internal global <2 x x86_fp80> , align 32
+  // @g28.b = internal global <12 x i16> 
+  // @g28.c = internal global <2 x x86_fp80> , align 32
   static v1i64 a = (v1i64)10LL;
-  static v12i16 b = (v12i16)(v2f80){1,2};
-  static v2f80 c = (v2f80)(v12i16){0,0,0,-32768,16383,0,0,0,0,-32768,16384,0};
+  //FIXME: support constant bitcast between vectors of x86_fp80
+  //static v12i16 b = (v12i16)(v2f80){1,2};
+  //static v2f80 c = 
(v2f80)(v12i16){0,0,0,-32768,16383,0,0,0,0,-32768,16384,0};

zygoloid wrote:

Please add some test coverage that we properly diagnose this situation.

I think we'll produce a diagnostic mentioning `bit_cast`, which is probably not 
what we want here. Maybe the simplest thing to do to fix that would be to 
replace `bit_cast` with `bit cast` in all the diagnostics. That seems at least 
as good for the `std::bit_cast` / `__builtin_bit_cast` case, and better for the 
vector cast case.

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


[clang] [clang] Implement constexpr bit_cast for vectors (PR #66894)

2023-10-20 Thread Richard Smith via cfe-commits

https://github.com/zygoloid commented:

Thanks, this looks good to me other than a small test coverage (see comment) / 
diagnostic wording issue.

(For future reference, please don't force-push to PR branches; that makes it 
much harder for your reviewer to see what's changed since their last review and 
can cause github to lose track of comments. See 
https://llvm.org/docs/GitHub.html#updating-pull-requests)

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


[clang] [clang] Implement constexpr bit_cast for vectors (PR #66894)

2023-10-20 Thread Richard Smith via cfe-commits

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


[libunwind] [libunwind][libc++][libc++abi] Add cross-compilation flags to tests (PR #67201)

2023-10-20 Thread Alexander Richardson via cfe-commits


@@ -45,10 +45,10 @@ config.substitutions.append(('%{flags}',
 '-isysroot {}'.format('@CMAKE_OSX_SYSROOT@') if '@CMAKE_OSX_SYSROOT@' else 
''
 ))
 config.substitutions.append(('%{compile_flags}',
-'-nostdinc++ -I %{include} -I %{libcxx}/test/support'
+'@CMAKE_CXX_FLAGS_INIT@ -nostdinc++ -I %{include} -I 
%{libcxx}/test/support'

arichardson wrote:

My original approach was to add a target flag 
(https://github.com/llvm/llvm-project/pull/65517) but @ldionne wasn't keen on 
that approach.

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


[libunwind] [libunwind][libc++][libc++abi] Add cross-compilation flags to tests (PR #67201)

2023-10-20 Thread Alexander Richardson via cfe-commits

arichardson wrote:

Debugging shows that the reason this is failing on the clang-cl bots is that 
the CMAKE_CXX_FLAGS_INIT are using the MSVC syntax but we pass 
--driver-mode=g++ explicitly:

```
lit: C:\ws\src\libcxx\utils\libcxx\test\format.py:55: note: Command 
["'C:/Program Files/LLVM/bin/clang-cl.exe' -xc++ nul -Werror -fsyntax-only 
--driver-mode=g++   /DWIN32 /D_WINDOWS /EHsc -fms-runtime-lib=dll -nostdinc++ 
-I C:/ws/src/build/clang-cl-dll/include/c++/v1 -I 
C:/ws/src/build/clang-cl-dll/include/c++/v1 -I C:/ws/src/libcxx/test/support 
-D_CRT_SECURE_NO_WARNINGS -D_CRT_NONSTDC_NO_WARNINGS 
-D_CRT_STDIO_ISO_WIDE_SPECIFIERS -DNOMINMAX  -std=c++03"] failed with code 1: 
clang-cl: error: no such file or directory: '/DWIN32'
--
  | clang-cl: error: no such file or directory: '/D_WINDOWS'
  | clang-cl: error: no such file or directory: '/EHsc'

```


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


[clang] Fix build warning caused by mixed signed/unsigned compare (PR #69797)

2023-10-20 Thread Andy Kaylor via cfe-commits

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


[clang] Fix build warning caused by mixed signed/unsigned compare (PR #69797)

2023-10-20 Thread Andy Kaylor via cfe-commits

https://github.com/andykaylor created 
https://github.com/llvm/llvm-project/pull/69797

None

>From 856a471b40f19f5fcf6aab7591009555b6a3841f Mon Sep 17 00:00:00 2001
From: Andy Kaylor 
Date: Fri, 20 Oct 2023 12:33:51 -0700
Subject: [PATCH 1/2] Update SimplifyIndVar.cpp

In SimplifyIndvar::replaceFloatIVWithIntegerIV() the return value of 
getFPMantissaWidth() was being cast as an unsigned integer and then compared 
with the number of bits needed to represent an integer that was cast to and 
from a floating-point type. This is a problem because getFPMantissaWidth() 
returns -1 if the type does not have a stable mantissa.

Currently the only type that returns -1 is ppc_fp128, so you'd need a pretty 
big induction variable to cause a problem. However, this problem will be more 
likely to be exposed when we implement support for decimal floating-point types.

Strictly speaking, what we want to know here is the size of the biggest integer 
that can be represented exactly. We could get that information even with an 
unstable mantissa width, but getFPMantissaWidth() won't do it.
---
 llvm/lib/Transforms/Utils/SimplifyIndVar.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp 
b/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp
index 1caf708bcc35254..45cbdd235898b28 100644
--- a/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp
+++ b/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp
@@ -664,7 +664,7 @@ bool 
SimplifyIndvar::replaceFloatIVWithIntegerIV(Instruction *UseInst) {
 MaskBits = SE->getSignedRange(IV).getMinSignedBits();
   else
 MaskBits = SE->getUnsignedRange(IV).getActiveBits();
-  unsigned DestNumSigBits = UseInst->getType()->getFPMantissaWidth();
+  int DestNumSigBits = UseInst->getType()->getFPMantissaWidth();
   if (MaskBits <= DestNumSigBits) {
 for (User *U : UseInst->users()) {
   // Match for fptosi/fptoui of sitofp and with same type.

>From 2524d41a34ccaa3932e5b4ab2876ea02744f6304 Mon Sep 17 00:00:00 2001
From: Andy Kaylor 
Date: Fri, 20 Oct 2023 16:40:26 -0700
Subject: [PATCH 2/2] Fix build warning

This fixes a build warning caused by mixed signed/unsigned compare
---
 llvm/lib/Transforms/Utils/SimplifyIndVar.cpp | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp 
b/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp
index 45cbdd235898b28..a23ac41acaa58aa 100644
--- a/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp
+++ b/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp
@@ -659,11 +659,11 @@ bool 
SimplifyIndvar::replaceFloatIVWithIntegerIV(Instruction *UseInst) {
   Instruction *IVOperand = cast(UseInst->getOperand(0));
   // Get the symbolic expression for this instruction.
   const SCEV *IV = SE->getSCEV(IVOperand);
-  unsigned MaskBits;
+  int MaskBits;
   if (UseInst->getOpcode() == CastInst::SIToFP)
-MaskBits = SE->getSignedRange(IV).getMinSignedBits();
+MaskBits = (int)SE->getSignedRange(IV).getMinSignedBits();
   else
-MaskBits = SE->getUnsignedRange(IV).getActiveBits();
+MaskBits = (int)SE->getUnsignedRange(IV).getActiveBits();
   int DestNumSigBits = UseInst->getType()->getFPMantissaWidth();
   if (MaskBits <= DestNumSigBits) {
 for (User *U : UseInst->users()) {

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


[clang] [analyzer] WebKit checkers: support ref and deref defined on different classes. (PR #68170)

2023-10-20 Thread Ryosuke Niwa via cfe-commits


@@ -44,9 +46,25 @@ bool hasPublicRefAndDeref(const CXXRecordDecl *R) {
 
 namespace clang {
 
-std::optional
-isRefCountable(const CXXBaseSpecifier* Base)
-{
+std::optional
+hasPublicRefInBase(const CXXBaseSpecifier *Base) {
+  assert(Base);
+
+  const Type *T = Base->getType().getTypePtrOrNull();
+  if (!T)
+return std::nullopt;

rniwa wrote:

Hm... this seems like a much more involved refactoring so perhaps we should do 
it in a separate pass? WDYT?

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


[clang] [analyzer] WebKit checkers: support ref and deref defined on different classes. (PR #68170)

2023-10-20 Thread Ryosuke Niwa via cfe-commits


@@ -18,24 +18,26 @@ using namespace clang;
 
 namespace {
 
-bool hasPublicRefAndDeref(const CXXRecordDecl *R) {
+bool hasPublicRefMethod(const CXXRecordDecl *R) {
   assert(R);
   assert(R->hasDefinition());
 
-  bool hasRef = false;
-  bool hasDeref = false;
   for (const CXXMethodDecl *MD : R->methods()) {
 const auto MethodName = safeGetName(MD);
+if (MethodName == "ref" && MD->getAccess() == AS_public)
+  return true;
+  }
+  return false;
+}
 
-if (MethodName == "ref" && MD->getAccess() == AS_public) {
-  if (hasDeref)
-return true;
-  hasRef = true;
-} else if (MethodName == "deref" && MD->getAccess() == AS_public) {
-  if (hasRef)
-return true;
-  hasDeref = true;
-}
+bool hasPublicDerefMethod(const CXXRecordDecl *R) {

rniwa wrote:

Sure, done that.

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


[clang] [analyzer] WebKit checkers: support ref and deref defined on different classes. (PR #68170)

2023-10-20 Thread Ryosuke Niwa via cfe-commits


@@ -70,29 +88,45 @@ std::optional isRefCountable(const CXXRecordDecl* R)
   if (!R)
 return std::nullopt;
 
-  if (hasPublicRefAndDeref(R))
+  bool hasRef = hasPublicRefMethod(R);
+  bool hasDeref = hasPublicDerefMethod(R);
+  if (hasRef && hasDeref)
 return true;
 
   CXXBasePaths Paths;
   Paths.setOrigin(const_cast(R));
 
   bool AnyInconclusiveBase = false;
-  const auto isRefCountableBase =
-  [](const CXXBaseSpecifier* Base, CXXBasePath&) {
-  std::optional IsRefCountable = 
clang::isRefCountable(Base);
-  if (!IsRefCountable) {
-  AnyInconclusiveBase = true;
-  return false;
-  }
-  return (*IsRefCountable) != nullptr;
+  const auto hasPublicRefInBase =
+  [](const CXXBaseSpecifier *Base, CXXBasePath &) {
+auto hasRefInBase = clang::hasPublicRefInBase(Base);
+if (!hasRefInBase) {
+  AnyInconclusiveBase = true;
+  return false;
+}
+return (*hasRefInBase) != nullptr;
   };
 
-  bool BasesResult = R->lookupInBases(isRefCountableBase, Paths,
-  /*LookupInDependent =*/true);
+  hasRef =
+  R->lookupInBases(hasPublicRefInBase, Paths, /*LookupInDependent =*/true);
+  if (AnyInconclusiveBase)
+return std::nullopt;
+
+  const auto hasPublicDerefInBase =
+  [](const CXXBaseSpecifier *Base, CXXBasePath &) {
+auto hasDerefInBase = clang::hasPublicDerefInBase(Base);
+if (!hasDerefInBase) {
+  AnyInconclusiveBase = true;
+  return false;
+}
+return (*hasDerefInBase) != nullptr;
+  };
+  hasDeref = R->lookupInBases(hasPublicDerefInBase, Paths,
+  /*LookupInDependent =*/true);

rniwa wrote:

Fixed.

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


[clang] [RISCV][MC] MC layer support for the experimental zalasr extension (PR #69685)

2023-10-20 Thread Brendan Sweeney via cfe-commits

mehnadnerd wrote:

I've updated it to add regression tests.

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


[clang] [RISCV][MC] MC layer support for the experimental zalasr extension (PR #69685)

2023-10-20 Thread Brendan Sweeney via cfe-commits

https://github.com/mehnadnerd updated 
https://github.com/llvm/llvm-project/pull/69685

>From d412fa8018ff4788c3ed8a1c8018c293be20040f Mon Sep 17 00:00:00 2001
From: brs 
Date: Thu, 19 Oct 2023 17:16:45 -0500
Subject: [PATCH] [RISCV][MC] MC layer support for the experimental zalasr
 extension

---
 .../test/Preprocessor/riscv-target-features.c |  9 ++
 llvm/docs/RISCVUsage.rst  |  3 +
 llvm/lib/Support/RISCVISAInfo.cpp |  1 +
 llvm/lib/Target/RISCV/RISCVFeatures.td|  7 ++
 llvm/lib/Target/RISCV/RISCVInstrInfo.td   |  1 +
 llvm/lib/Target/RISCV/RISCVInstrInfoZalasr.td | 66 ++
 llvm/test/CodeGen/RISCV/attributes.ll |  4 +
 llvm/test/MC/RISCV/attribute-arch.s   |  3 +
 llvm/test/MC/RISCV/rv32zalasr-invalid.s   | 40 
 llvm/test/MC/RISCV/rv32zalasr-valid.s | 70 ++
 llvm/test/MC/RISCV/rv64zalasr-invalid.s   | 28 ++
 llvm/test/MC/RISCV/rv64zalasr-valid.s | 91 +++
 llvm/unittests/Support/RISCVISAInfoTest.cpp   |  1 +
 13 files changed, 324 insertions(+)
 create mode 100644 llvm/lib/Target/RISCV/RISCVInstrInfoZalasr.td
 create mode 100644 llvm/test/MC/RISCV/rv32zalasr-invalid.s
 create mode 100644 llvm/test/MC/RISCV/rv32zalasr-valid.s
 create mode 100644 llvm/test/MC/RISCV/rv64zalasr-invalid.s
 create mode 100644 llvm/test/MC/RISCV/rv64zalasr-valid.s

diff --git a/clang/test/Preprocessor/riscv-target-features.c 
b/clang/test/Preprocessor/riscv-target-features.c
index ffdec34ca615fe3..7ca7c1539627b7b 100644
--- a/clang/test/Preprocessor/riscv-target-features.c
+++ b/clang/test/Preprocessor/riscv-target-features.c
@@ -112,6 +112,7 @@
 // CHECK-NOT: __riscv_smaia {{.*$}}
 // CHECK-NOT: __riscv_ssaia {{.*$}}
 // CHECK-NOT: __riscv_zacas {{.*$}}
+// CHECK-NOT: __riscv_zalasr {{.*$}}
 // CHECK-NOT: __riscv_zfa {{.*$}}
 // CHECK-NOT: __riscv_zfbfmin {{.*$}}
 // CHECK-NOT: __riscv_zicfilp {{.*$}}
@@ -1019,6 +1020,14 @@
 // RUN: -o - | FileCheck --check-prefix=CHECK-ZACAS-EXT %s
 // CHECK-ZACAS-EXT: __riscv_zacas 100{{$}}
 
+// RUN: %clang --target=riscv32 -menable-experimental-extensions \
+// RUN: -march=rv32i_zalasr1p0 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZALASR-EXT %s
+// RUN: %clang --target=riscv64 -menable-experimental-extensions \
+// RUN: -march=rv64i_zalasr1p0 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZALASR-EXT %s
+// CHECK-ZALASR-EXT: __riscv_zalasr 100{{$}}
+
 // RUN: %clang --target=riscv32-unknown-linux-gnu \
 // RUN: -march=rv32izfa -x c -E -dM %s \
 // RUN: -o - | FileCheck --check-prefix=CHECK-ZFA-EXT %s
diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index 6812efaeb36e0c1..f9a7d4633e0a8dc 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -197,6 +197,9 @@ The primary goal of experimental support is to assist in 
the process of ratifica
 ``experimental-zacas``
   LLVM implements the `1.0-rc1 draft specification 
`_.
 
+``experimental-zalasr``
+  LLVM implements the `most recent specification 
`_.
+
 ``experimental-zfbfmin``, ``experimental-zvfbfmin``, ``experimental-zvfbfwma``
   LLVM implements assembler support for the `0.8.0 draft specification 
`_.
 
diff --git a/llvm/lib/Support/RISCVISAInfo.cpp 
b/llvm/lib/Support/RISCVISAInfo.cpp
index 22208e2e0c2950b..847a2c6f37656ba 100644
--- a/llvm/lib/Support/RISCVISAInfo.cpp
+++ b/llvm/lib/Support/RISCVISAInfo.cpp
@@ -168,6 +168,7 @@ static const RISCVSupportedExtension 
SupportedExperimentalExtensions[] = {
 {"ssaia", RISCVExtensionVersion{1, 0}},
 
 {"zacas", RISCVExtensionVersion{1, 0}},
+{"zalasr", RISCVExtensionVersion{1, 0}},
 
 {"zfbfmin", RISCVExtensionVersion{0, 8}},
 
diff --git a/llvm/lib/Target/RISCV/RISCVFeatures.td 
b/llvm/lib/Target/RISCV/RISCVFeatures.td
index 979bc0ea8c7d065..b011fb4eb4421f0 100644
--- a/llvm/lib/Target/RISCV/RISCVFeatures.td
+++ b/llvm/lib/Target/RISCV/RISCVFeatures.td
@@ -708,6 +708,13 @@ def HasStdExtZacas : 
Predicate<"Subtarget->hasStdExtZacas()">,
AssemblerPredicate<(all_of FeatureStdExtZacas),
"'Zacas' (Atomic Compare-And-Swap 
Instructions)">;
 
+def FeatureStdExtZalasr
+: SubtargetFeature<"experimental-zalasr", "HasStdExtZalasr", "true",
+   "'Zalasr' (Load-Acquire and Store-Release 
Instructions)">;
+def HasStdExtZalasr : Predicate<"Subtarget->hasStdExtZalasr()">,
+   AssemblerPredicate<(all_of FeatureStdExtZalasr),
+   "'Zalasr' (Load-Acquire and Store-Release 
Instructions)">;
+
 
//===--===//
 // Vendor extensions
 
//===--===//

[clang] [clang][tidy] Ensure rewriter has the correct CWD (PR #67839)

2023-10-20 Thread Jan Svoboda via cfe-commits

jansvoboda11 wrote:

> Clang part looks fine. For a clang-tidy part, is there a way to test this 
> part ? What changes because we use now a absolute build directory. I'm 
> missing some tests for that part.

So the clang-tidy part is necessary to keep the 
`clang-tidy/infrastructure/clang-tidy-run-with-database.cpp` test passing. It 
uses compilation database that has entries like this:

```json
{
  "directory": "/b",
  "command": "clang++ -o test.o ../b/c.cpp",
  "file": "/b/c.cpp"
}
```

I think this already provides good enough code coverage for this PR. What do 
you think?

What I'd like to get clarified in this PR is which directory to use as the CWD.
Is using `ClangTidyContext::getCurrentBuildDirectory()` okay, or do we need to 
look somewhere else?

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


[libunwind] [libunwind][libc++][libc++abi] Add cross-compilation flags to tests (PR #67201)

2023-10-20 Thread via cfe-commits

EricWF wrote:

We also don't want to make our test suite flags beholden to changes CMake 
chooses to make.

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


[libunwind] [libunwind][libc++][libc++abi] Add cross-compilation flags to tests (PR #67201)

2023-10-20 Thread via cfe-commits

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


[libunwind] [libunwind][libc++][libc++abi] Add cross-compilation flags to tests (PR #67201)

2023-10-20 Thread via cfe-commits


@@ -45,10 +45,10 @@ config.substitutions.append(('%{flags}',
 '-isysroot {}'.format('@CMAKE_OSX_SYSROOT@') if '@CMAKE_OSX_SYSROOT@' else 
''
 ))
 config.substitutions.append(('%{compile_flags}',
-'-nostdinc++ -I %{include} -I %{libcxx}/test/support'
+'@CMAKE_CXX_FLAGS_INIT@ -nostdinc++ -I %{include} -I 
%{libcxx}/test/support'

EricWF wrote:

I don't think this makes sense. The flags you use to build the library may not 
be the flags our users use when using it.


I think the test suite should handle its flags manually, and we should find 
another route to get you what you want here.



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


[clang] Support target names with dots in more utilities (PR #65812)

2023-10-20 Thread Dan McGregor via cfe-commits

dankm wrote:

Hm. I have "fixup" commits in this branch, should I rebase those, or can we 
squash merge as-is?

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


[libunwind] [libunwind][libc++][libc++abi] Add cross-compilation flags to tests (PR #67201)

2023-10-20 Thread Alexander Richardson via cfe-commits

https://github.com/arichardson updated 
https://github.com/llvm/llvm-project/pull/67201

>From 6d650b781080d46ccae02793529cf63b18859f3f Mon Sep 17 00:00:00 2001
From: Alex Richardson 
Date: Wed, 6 Sep 2023 11:41:56 -0700
Subject: [PATCH 1/4] [libunwind][libc++][libc++abi] Add cross-compilation
 flags to tests

There is currently only limited support for passing target-specific
flags (e.g. -mabi= or -march=) to the testsuites if you don't have a
compiler (or wrapper script) that defaults to the expected flags.
However, some targets (e.g. RISC-V) may require additional flags beyond
the basic --target= that is already added by the current infrastructure.

When cross-compiling with CMake, the recommended approach is to define
a toolchain file that specifies the necessary flags needed to compile for
a given target. There are two interesting variables here that we should
also be passing when building the test binaries:
- CMAKE_CXX_FLAGS_INIT defines the flags we need for compilation jobs
   and will specify flags such as -mabi= and -march=
- CMAKE_EXE_LINKER_FLAGS_INIT defines the linker flags that are needed to
  cross-compile for a given target.
When not cross-compiling these variables will generally be empty.
---
 libcxx/test/configs/apple-libc++-backdeployment.cfg.in| 4 ++--
 libcxx/test/configs/apple-libc++-shared.cfg.in| 4 ++--
 libcxx/test/configs/ibm-libc++-shared.cfg.in  | 4 ++--
 libcxx/test/configs/llvm-libc++-mingw.cfg.in  | 4 ++--
 libcxx/test/configs/llvm-libc++-shared-clangcl.cfg.in | 4 ++--
 libcxx/test/configs/llvm-libc++-shared-gcc.cfg.in | 4 ++--
 .../configs/llvm-libc++-shared-no-vcruntime-clangcl.cfg.in| 4 ++--
 libcxx/test/configs/llvm-libc++-shared.cfg.in | 4 ++--
 libcxx/test/configs/llvm-libc++-static-clangcl.cfg.in | 4 ++--
 libcxx/test/configs/llvm-libc++-static.cfg.in | 4 ++--
 libcxxabi/test/configs/apple-libc++abi-backdeployment.cfg.in  | 4 ++--
 libcxxabi/test/configs/apple-libc++abi-shared.cfg.in  | 4 ++--
 libcxxabi/test/configs/ibm-libc++abi-shared.cfg.in| 4 ++--
 libcxxabi/test/configs/llvm-libc++abi-merged.cfg.in   | 4 ++--
 libcxxabi/test/configs/llvm-libc++abi-mingw.cfg.in| 4 ++--
 libcxxabi/test/configs/llvm-libc++abi-shared-clangcl.cfg.in   | 4 ++--
 libcxxabi/test/configs/llvm-libc++abi-shared.cfg.in   | 4 ++--
 libcxxabi/test/configs/llvm-libc++abi-static-clangcl.cfg.in   | 4 ++--
 libcxxabi/test/configs/llvm-libc++abi-static.cfg.in   | 4 ++--
 libunwind/test/configs/apple-libunwind-backdeployment.cfg.in  | 4 ++--
 libunwind/test/configs/ibm-libunwind-shared.cfg.in| 4 ++--
 libunwind/test/configs/llvm-libunwind-merged.cfg.in   | 4 ++--
 libunwind/test/configs/llvm-libunwind-mingw.cfg.in| 4 ++--
 libunwind/test/configs/llvm-libunwind-shared.cfg.in   | 4 ++--
 libunwind/test/configs/llvm-libunwind-static.cfg.in   | 4 ++--
 25 files changed, 50 insertions(+), 50 deletions(-)

diff --git a/libcxx/test/configs/apple-libc++-backdeployment.cfg.in 
b/libcxx/test/configs/apple-libc++-backdeployment.cfg.in
index b471c02709c060f..374ad38247f9f1f 100644
--- a/libcxx/test/configs/apple-libc++-backdeployment.cfg.in
+++ b/libcxx/test/configs/apple-libc++-backdeployment.cfg.in
@@ -45,10 +45,10 @@ config.substitutions.append(('%{flags}',
 '-isysroot {}'.format('@CMAKE_OSX_SYSROOT@') if '@CMAKE_OSX_SYSROOT@' else 
''
 ))
 config.substitutions.append(('%{compile_flags}',
-'-nostdinc++ -I %{include} -I %{libcxx}/test/support'
+'@CMAKE_CXX_FLAGS_INIT@ -nostdinc++ -I %{include} -I 
%{libcxx}/test/support'
 ))
 config.substitutions.append(('%{link_flags}',
-'-nostdlib++ -L %{lib} -lc++'
+'@CMAKE_EXE_LINKER_FLAGS_INIT@ -nostdlib++ -L %{lib} -lc++'
 ))
 config.substitutions.append(('%{exec}',
 '%{executor} --execdir %T --env 
DYLD_LIBRARY_PATH="%{cxx-runtime-root}:%{abi-runtime-root}:%{unwind-runtime-root}"
 -- '
diff --git a/libcxx/test/configs/apple-libc++-shared.cfg.in 
b/libcxx/test/configs/apple-libc++-shared.cfg.in
index af1926e3859b9e5..0c664ad2cf65fa3 100644
--- a/libcxx/test/configs/apple-libc++-shared.cfg.in
+++ b/libcxx/test/configs/apple-libc++-shared.cfg.in
@@ -13,10 +13,10 @@ config.substitutions.append(('%{flags}',
 '-isysroot {}'.format('@CMAKE_OSX_SYSROOT@') if '@CMAKE_OSX_SYSROOT@' else 
''
 ))
 config.substitutions.append(('%{compile_flags}',
-'-nostdinc++ -I %{include} -I %{libcxx}/test/support'
+'@CMAKE_CXX_FLAGS_INIT@ -nostdinc++ -I %{include} -I 
%{libcxx}/test/support'
 ))
 config.substitutions.append(('%{link_flags}',
-'-nostdlib++ -L %{lib} -lc++'
+'@CMAKE_EXE_LINKER_FLAGS_INIT@ -nostdlib++ -L %{lib} -lc++'
 ))
 config.substitutions.append(('%{exec}',
 '%{executor} --execdir %T --env DYLD_LIBRARY_PATH=%{lib} -- '
diff --git a/libcxx/test/configs/ibm-libc++-shared.cfg.in 

[clang-tools-extra] Update stdckdint.h and make it available in pre-C23 modes. (PR #69649)

2023-10-20 Thread via cfe-commits

https://github.com/ZijunZhaoCCK updated 
https://github.com/llvm/llvm-project/pull/69649

>From 0c57e45f6ee16e43cc6388b1ca6beb88bbc7b925 Mon Sep 17 00:00:00 2001
From: zijunzhao 
Date: Thu, 19 Oct 2023 22:23:03 +
Subject: [PATCH 1/3] Update stdckdint.h and make it available in pre-C23
 modes.

Update some tests and docs.
---
 clang/docs/ReleaseNotes.rst| 2 +-
 clang/lib/Headers/stdckdint.h  | 4 
 clang/test/C/C2x/n2359.c   | 5 -
 clang/test/C/C2x/n2683.c   | 1 +
 clang/test/C/C2x/n2683_2.c | 1 +
 clang/test/Headers/stdckdint.c | 7 +--
 6 files changed, 8 insertions(+), 12 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index fc8caf9221b9d29..d0de52a5bf122f4 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -177,7 +177,7 @@ C23 Feature Support
 - Clang now supports ``N3007 Type inference for object definitions``.
 
 - Clang now supports  which defines several macros for 
performing
-  checked integer arithmetic.
+  checked integer arithmetic. And it is also exposed in pre-C23 modes.
 
 Non-comprehensive list of changes in this release
 -
diff --git a/clang/lib/Headers/stdckdint.h b/clang/lib/Headers/stdckdint.h
index 22972d78d9077a4..77290b260ff3bd4 100644
--- a/clang/lib/Headers/stdckdint.h
+++ b/clang/lib/Headers/stdckdint.h
@@ -21,9 +21,6 @@
 
 /* C23 7.20.1 Defines several macros for performing checked integer 
arithmetic*/
 
-#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L
-#define __STDC_VERSION_STDCKDINT_H__ 202311L
-
 // Both A and B shall be any integer type other than "plain" char, bool, a bit-
 // precise integer type, or an enumerated type, and they need not be the same.
 
@@ -38,7 +35,6 @@
 #define ckd_add(R, A, B) __builtin_add_overflow((A), (B), (R))
 #define ckd_sub(R, A, B) __builtin_sub_overflow((A), (B), (R))
 #define ckd_mul(R, A, B) __builtin_mul_overflow((A), (B), (R))
-#endif
 
 #endif /* __STDC_HOSTED__ */
 #endif /* __STDCKDINT_H */
diff --git a/clang/test/C/C2x/n2359.c b/clang/test/C/C2x/n2359.c
index dc38bab43c9db8d..0a1b801e505e146 100644
--- a/clang/test/C/C2x/n2359.c
+++ b/clang/test/C/C2x/n2359.c
@@ -33,8 +33,3 @@
 #error "__STDC_VERSION_STDINT_H__ not defined"
 // expected-error@-1 {{"__STDC_VERSION_STDINT_H__ not defined"}}
 #endif
-
-#include 
-#ifndef __STDC_VERSION_STDCKDINT_H__
-#error "__STDC_VERSION_STDCKDINT_H__ not defined"
-#endif
diff --git a/clang/test/C/C2x/n2683.c b/clang/test/C/C2x/n2683.c
index 0c666c5fd8782ba..a785d46c063c2cc 100644
--- a/clang/test/C/C2x/n2683.c
+++ b/clang/test/C/C2x/n2683.c
@@ -1,4 +1,5 @@
 // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 3
+// RUN: %clang_cc1 -triple=x86_64 -verify -ffreestanding -std=c2x %s
 // RUN: %clang_cc1 -triple=x86_64 -verify -ffreestanding -std=c23 %s
 
 /* WG14 N2683: Clang 18
diff --git a/clang/test/C/C2x/n2683_2.c b/clang/test/C/C2x/n2683_2.c
index 247f6de8fe4bfe1..867d6b876cf0d9d 100644
--- a/clang/test/C/C2x/n2683_2.c
+++ b/clang/test/C/C2x/n2683_2.c
@@ -1,4 +1,5 @@
 // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 3
+// RUN: %clang_cc1 -triple=x86_64 -emit-llvm -o - -std=c2x %s | FileCheck %s
 // RUN: %clang_cc1 -triple=x86_64 -emit-llvm -o - -std=c23 %s | FileCheck %s
 
 #include 
diff --git a/clang/test/Headers/stdckdint.c b/clang/test/Headers/stdckdint.c
index 896c740360065b6..7774cecfa7c3317 100644
--- a/clang/test/Headers/stdckdint.c
+++ b/clang/test/Headers/stdckdint.c
@@ -1,12 +1,15 @@
 // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 3
+// RUN: %clang_cc1 -triple=x86_64 -emit-llvm -verify -std=c99 %s -o - | 
FileCheck %s
+// RUN: %clang_cc1 -triple=x86_64 -emit-llvm -verify -std=c11 %s -o - | 
FileCheck %s
+// RUN: %clang_cc1 -triple=x86_64 -emit-llvm -verify -std=c17 %s -o - | 
FileCheck %s
+// RUN: %clang_cc1 -triple=x86_64 -emit-llvm -verify -std=c2x %s -o - | 
FileCheck %s
 // RUN: %clang_cc1 -triple=x86_64 -emit-llvm -verify -std=c23 %s -o - | 
FileCheck %s
 
 // expected-no-diagnostics
 
+#include 
 #include 
 
-_Static_assert(__STDC_VERSION_STDCKDINT_H__ == 202311L, "");
-
 // CHECK-LABEL: define dso_local zeroext i1 @test_ckd_add(
 // CHECK-SAME: ) #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:

>From 4e2fd920121b15e014a6146c6c6672973bae4443 Mon Sep 17 00:00:00 2001
From: zijunzhao 
Date: Thu, 19 Oct 2023 22:23:03 +
Subject: [PATCH 2/3] Update stdckdint.h and make it available in pre-C23
 modes.

Update some tests and docs.
---
 clang/docs/ReleaseNotes.rst   | 2 +-
 clang/lib/Headers/stdckdint.h | 4 
 2 files changed, 5 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d0de52a5bf122f4..1b1f25ae244ef9f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -177,7 +177,7 @@ C23 Feature Support
 - Clang 

[clang-tools-extra] [clangd] Fix RawStringLiteral being available to C and C++ versions prior to C++11 (PR #69775)

2023-10-20 Thread via cfe-commits

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


[clang-tools-extra] [clangd] Fix RawStringLiteral being available to C and C++ versions prior to C++11 (PR #69775)

2023-10-20 Thread via cfe-commits

https://github.com/robozati updated 
https://github.com/llvm/llvm-project/pull/69775

>From c644be1d123769395bed6ea069a45c051e3fc66d Mon Sep 17 00:00:00 2001
From: robozati <139823421+roboz...@users.noreply.github.com>
Date: Fri, 20 Oct 2023 17:23:21 -0300
Subject: [PATCH 1/2] Fix RawStringLiteral being available to C and C++
 versions prior to C++11

---
 .../refactor/tweaks/RawStringLiteral.cpp   |  8 +++-
 .../unittests/tweaks/RawStringLiteralTests.cpp | 18 ++
 2 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
index f5021b820f38d7f..82c908b494790cb 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
@@ -43,6 +43,12 @@ class RawStringLiteral : public Tweak {
 
 REGISTER_TWEAK(RawStringLiteral)
 
+static bool isFeatureAvailable(const Tweak::Selection ) {
+  // Raw strings are available only for C++11 or later versions, and they are
+  // not available for C.
+  return Inputs.AST->getASTContext().getLangOpts().CPlusPlus11;
+}
+
 static bool isNormalString(const StringLiteral , SourceLocation Cursor,
   SourceManager ) {
   // All chunks must be normal ASCII strings, not u8"..." etc.
@@ -76,7 +82,7 @@ bool RawStringLiteral::prepare(const Selection ) {
   if (!N)
 return false;
   Str = dyn_cast_or_null(N->ASTNode.get());
-  return Str &&
+  return Str && isFeatureAvailable(Inputs) &&
  isNormalString(*Str, Inputs.Cursor, Inputs.AST->getSourceManager()) &&
  needsRaw(Str->getBytes()) && canBeRaw(Str->getBytes());
 }
diff --git 
a/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
index 4bc304559705031..0e96dfbe2e376bc 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
@@ -36,6 +36,24 @@ literal)")cpp";
   EXPECT_EQ(apply(Input), Output);
 }
 
+TEST_F(RawStringLiteralTest, TestC) {
+  Context = File;
+  FileName = "TestTU.c";
+  ExtraArgs = {"-xc"}; // raw strings are unavailable in C
+  EXPECT_UNAVAILABLE(R"c(
+const char* a = "^f^o^o^\^n^";
+  )c");
+}
+
+TEST_F(RawStringLiteralTest, TestCpp98) {
+  Context = File;
+  ExtraArgs = {"-std=c++98"}; // raw strings are unavailable
+  // in versions prior to C++11
+  EXPECT_UNAVAILABLE(R"cpp(
+const char* a = "^f^o^o^\^n^";
+  )cpp");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang

>From e5923e038d38c4ea49834f7a417a1294d58bcfc5 Mon Sep 17 00:00:00 2001
From: robozati <139823421+roboz...@users.noreply.github.com>
Date: Fri, 20 Oct 2023 19:03:17 -0300
Subject: [PATCH 2/2] Fix tests sometimes failing

---
 .../clangd/unittests/tweaks/RawStringLiteralTests.cpp | 8 ++--
 1 file changed, 2 insertions(+), 6 deletions(-)

diff --git 
a/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
index 0e96dfbe2e376bc..2681b8c815dbae3 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
@@ -40,18 +40,14 @@ TEST_F(RawStringLiteralTest, TestC) {
   Context = File;
   FileName = "TestTU.c";
   ExtraArgs = {"-xc"}; // raw strings are unavailable in C
-  EXPECT_UNAVAILABLE(R"c(
-const char* a = "^f^o^o^\^n^";
-  )c");
+  EXPECT_UNAVAILABLE(R"c(const char *a = ^"^f^o^o^\^n^";)c");
 }
 
 TEST_F(RawStringLiteralTest, TestCpp98) {
   Context = File;
   ExtraArgs = {"-std=c++98"}; // raw strings are unavailable
   // in versions prior to C++11
-  EXPECT_UNAVAILABLE(R"cpp(
-const char* a = "^f^o^o^\^n^";
-  )cpp");
+  EXPECT_UNAVAILABLE(R"cpp(const char *a = ^"^f^o^o^\^n^";)cpp");
 }
 
 } // namespace

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


[clang] [OpenMP][mlir] Add translation for `if` in `omp.teams` (PR #69404)

2023-10-20 Thread via cfe-commits

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


[clang-tools-extra] [OpenMP][mlir] Add translation for `if` in `omp.teams` (PR #69404)

2023-10-20 Thread via cfe-commits

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


[clang] [OpenMP][mlir] Add translation for `if` in `omp.teams` (PR #69404)

2023-10-20 Thread via cfe-commits

https://github.com/shraiysh updated 
https://github.com/llvm/llvm-project/pull/69404

>From cf9e3e16a8b6f56e76c725b6244154b825cc8cc0 Mon Sep 17 00:00:00 2001
From: Shraiysh Vaishay 
Date: Tue, 17 Oct 2023 19:59:11 -0500
Subject: [PATCH 1/2] [OpenMP][mlir] Add translation for `if` in `omp.teams`

This patch adds translation for `if` clause on `teams` construct in
OpenMP Dialect.
---
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  |  8 +++-
 mlir/test/Target/LLVMIR/openmp-teams.mlir | 48 +++
 2 files changed, 54 insertions(+), 2 deletions(-)

diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index e3dc68a1b8b7d72..025f102f0fbf809 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -666,7 +666,7 @@ convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
,
 LLVM::ModuleTranslation ) {
   using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
   LogicalResult bodyGenStatus = success();
-  if (op.getIfExpr() || !op.getAllocatorsVars().empty() || op.getReductions())
+  if (!op.getAllocatorsVars().empty() || op.getReductions())
 return op.emitError("unhandled clauses for translation to LLVM IR");
 
   auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP) {
@@ -689,9 +689,13 @@ convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
,
   if (Value threadLimitVar = op.getThreadLimit())
 threadLimit = moduleTranslation.lookupValue(threadLimitVar);
 
+  llvm::Value *ifExpr = nullptr;
+  if (Value ifExprVar = op.getIfExpr())
+ifExpr = moduleTranslation.lookupValue(ifExprVar);
+
   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
   builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createTeams(
-  ompLoc, bodyCB, numTeamsLower, numTeamsUpper, threadLimit));
+  ompLoc, bodyCB, numTeamsLower, numTeamsUpper, threadLimit, ifExpr));
   return bodyGenStatus;
 }
 
diff --git a/mlir/test/Target/LLVMIR/openmp-teams.mlir 
b/mlir/test/Target/LLVMIR/openmp-teams.mlir
index 87ef90223ed704a..cc12dff6df1e376 100644
--- a/mlir/test/Target/LLVMIR/openmp-teams.mlir
+++ b/mlir/test/Target/LLVMIR/openmp-teams.mlir
@@ -235,3 +235,51 @@ llvm.func 
@omp_teams_num_teams_and_thread_limit(%numTeamsLower: i32, %numTeamsUp
 // CHECK: define internal void [[OUTLINED_FN]](ptr {{.+}}, ptr {{.+}})
 // CHECK: call void @duringTeams()
 // CHECK: ret void
+
+// -
+
+llvm.func @beforeTeams()
+llvm.func @duringTeams()
+llvm.func @afterTeams()
+
+// CHECK-LABEL: @teams_if
+// CHECK-SAME: (i1 [[ARG:.+]])
+llvm.func @teams_if(%arg : i1) {
+// CHECK-NEXT: call void @beforeTeams()
+llvm.call @beforeTeams() : () -> ()
+// CHECK: [[NUM_TEAMS_UPPER:%.+]] = select i1 [[ARG]], i32 0, i32 1
+// CHECK: [[NUM_TEAMS_LOWER:%.+]] = select i1 [[ARG]], i32 0, i32 1
+// CHECK: call void @__kmpc_push_num_teams_51(ptr {{.+}}, i32 {{.+}}, i32 
[[NUM_TEAMS_LOWER]], i32 [[NUM_TEAMS_UPPER]], i32 0)
+// CHECK: call void {{.+}} @__kmpc_fork_teams({{.+}})
+omp.teams if(%arg) {
+llvm.call @duringTeams() : () -> ()
+omp.terminator
+}
+// CHECK: call void @afterTeams()
+llvm.call @afterTeams() : () -> ()
+llvm.return
+}
+
+// -
+
+llvm.func @beforeTeams()
+llvm.func @duringTeams()
+llvm.func @afterTeams()
+
+// CHECK-LABEL: @teams_if_with_num_teams
+// CHECK-SAME: (i1 [[CONDITION:.+]], i32 [[NUM_TEAMS_LOWER:.+]], i32 
[[NUM_TEAMS_UPPER:.+]], i32 [[THREAD_LIMIT:.+]])
+llvm.func @teams_if_with_num_teams(%condition: i1, %numTeamsLower: i32, 
%numTeamsUpper: i32, %threadLimit: i32) {
+// CHECK: call void @beforeTeams()
+llvm.call @beforeTeams() : () -> ()
+// CHECK: [[NUM_TEAMS_UPPER_NEW:%.+]] = select i1 [[CONDITION]], i32 
[[NUM_TEAMS_UPPER]], i32 1
+// CHECK: [[NUM_TEAMS_LOWER_NEW:%.+]] = select i1 [[CONDITION]], i32 
[[NUM_TEAMS_LOWER]], i32 1
+// CHECK: call void @__kmpc_push_num_teams_51(ptr {{.+}}, i32 {{.+}}, i32 
[[NUM_TEAMS_LOWER_NEW]], i32 [[NUM_TEAMS_UPPER_NEW]], i32 [[THREAD_LIMIT]])
+// CHECK: call void {{.+}} @__kmpc_fork_teams({{.+}})
+omp.teams if(%condition) num_teams(%numTeamsLower: i32 to %numTeamsUpper: 
i32) thread_limit(%threadLimit: i32) {
+llvm.call @duringTeams() : () -> ()
+omp.terminator
+}
+// CHECK: call void @afterTeams()
+llvm.call @afterTeams() : () -> ()
+llvm.return
+}

>From f1487f630506bc116597eacaeba4d05bb02d3b35 Mon Sep 17 00:00:00 2001
From: Shraiysh Vaishay 
Date: Fri, 20 Oct 2023 16:54:51 -0500
Subject: [PATCH 2/2] Added comment about default values.

---
 mlir/test/Target/LLVMIR/openmp-teams.mlir | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/mlir/test/Target/LLVMIR/openmp-teams.mlir 
b/mlir/test/Target/LLVMIR/openmp-teams.mlir
index cc12dff6df1e376..973d2ed395eb0d0 100644
--- a/mlir/test/Target/LLVMIR/openmp-teams.mlir
+++ 

[clang-tools-extra] [OpenMP][mlir] Add translation for `if` in `omp.teams` (PR #69404)

2023-10-20 Thread via cfe-commits

https://github.com/shraiysh updated 
https://github.com/llvm/llvm-project/pull/69404

>From cf9e3e16a8b6f56e76c725b6244154b825cc8cc0 Mon Sep 17 00:00:00 2001
From: Shraiysh Vaishay 
Date: Tue, 17 Oct 2023 19:59:11 -0500
Subject: [PATCH 1/2] [OpenMP][mlir] Add translation for `if` in `omp.teams`

This patch adds translation for `if` clause on `teams` construct in
OpenMP Dialect.
---
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  |  8 +++-
 mlir/test/Target/LLVMIR/openmp-teams.mlir | 48 +++
 2 files changed, 54 insertions(+), 2 deletions(-)

diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index e3dc68a1b8b7d72..025f102f0fbf809 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -666,7 +666,7 @@ convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
,
 LLVM::ModuleTranslation ) {
   using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
   LogicalResult bodyGenStatus = success();
-  if (op.getIfExpr() || !op.getAllocatorsVars().empty() || op.getReductions())
+  if (!op.getAllocatorsVars().empty() || op.getReductions())
 return op.emitError("unhandled clauses for translation to LLVM IR");
 
   auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP) {
@@ -689,9 +689,13 @@ convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
,
   if (Value threadLimitVar = op.getThreadLimit())
 threadLimit = moduleTranslation.lookupValue(threadLimitVar);
 
+  llvm::Value *ifExpr = nullptr;
+  if (Value ifExprVar = op.getIfExpr())
+ifExpr = moduleTranslation.lookupValue(ifExprVar);
+
   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
   builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createTeams(
-  ompLoc, bodyCB, numTeamsLower, numTeamsUpper, threadLimit));
+  ompLoc, bodyCB, numTeamsLower, numTeamsUpper, threadLimit, ifExpr));
   return bodyGenStatus;
 }
 
diff --git a/mlir/test/Target/LLVMIR/openmp-teams.mlir 
b/mlir/test/Target/LLVMIR/openmp-teams.mlir
index 87ef90223ed704a..cc12dff6df1e376 100644
--- a/mlir/test/Target/LLVMIR/openmp-teams.mlir
+++ b/mlir/test/Target/LLVMIR/openmp-teams.mlir
@@ -235,3 +235,51 @@ llvm.func 
@omp_teams_num_teams_and_thread_limit(%numTeamsLower: i32, %numTeamsUp
 // CHECK: define internal void [[OUTLINED_FN]](ptr {{.+}}, ptr {{.+}})
 // CHECK: call void @duringTeams()
 // CHECK: ret void
+
+// -
+
+llvm.func @beforeTeams()
+llvm.func @duringTeams()
+llvm.func @afterTeams()
+
+// CHECK-LABEL: @teams_if
+// CHECK-SAME: (i1 [[ARG:.+]])
+llvm.func @teams_if(%arg : i1) {
+// CHECK-NEXT: call void @beforeTeams()
+llvm.call @beforeTeams() : () -> ()
+// CHECK: [[NUM_TEAMS_UPPER:%.+]] = select i1 [[ARG]], i32 0, i32 1
+// CHECK: [[NUM_TEAMS_LOWER:%.+]] = select i1 [[ARG]], i32 0, i32 1
+// CHECK: call void @__kmpc_push_num_teams_51(ptr {{.+}}, i32 {{.+}}, i32 
[[NUM_TEAMS_LOWER]], i32 [[NUM_TEAMS_UPPER]], i32 0)
+// CHECK: call void {{.+}} @__kmpc_fork_teams({{.+}})
+omp.teams if(%arg) {
+llvm.call @duringTeams() : () -> ()
+omp.terminator
+}
+// CHECK: call void @afterTeams()
+llvm.call @afterTeams() : () -> ()
+llvm.return
+}
+
+// -
+
+llvm.func @beforeTeams()
+llvm.func @duringTeams()
+llvm.func @afterTeams()
+
+// CHECK-LABEL: @teams_if_with_num_teams
+// CHECK-SAME: (i1 [[CONDITION:.+]], i32 [[NUM_TEAMS_LOWER:.+]], i32 
[[NUM_TEAMS_UPPER:.+]], i32 [[THREAD_LIMIT:.+]])
+llvm.func @teams_if_with_num_teams(%condition: i1, %numTeamsLower: i32, 
%numTeamsUpper: i32, %threadLimit: i32) {
+// CHECK: call void @beforeTeams()
+llvm.call @beforeTeams() : () -> ()
+// CHECK: [[NUM_TEAMS_UPPER_NEW:%.+]] = select i1 [[CONDITION]], i32 
[[NUM_TEAMS_UPPER]], i32 1
+// CHECK: [[NUM_TEAMS_LOWER_NEW:%.+]] = select i1 [[CONDITION]], i32 
[[NUM_TEAMS_LOWER]], i32 1
+// CHECK: call void @__kmpc_push_num_teams_51(ptr {{.+}}, i32 {{.+}}, i32 
[[NUM_TEAMS_LOWER_NEW]], i32 [[NUM_TEAMS_UPPER_NEW]], i32 [[THREAD_LIMIT]])
+// CHECK: call void {{.+}} @__kmpc_fork_teams({{.+}})
+omp.teams if(%condition) num_teams(%numTeamsLower: i32 to %numTeamsUpper: 
i32) thread_limit(%threadLimit: i32) {
+llvm.call @duringTeams() : () -> ()
+omp.terminator
+}
+// CHECK: call void @afterTeams()
+llvm.call @afterTeams() : () -> ()
+llvm.return
+}

>From f1487f630506bc116597eacaeba4d05bb02d3b35 Mon Sep 17 00:00:00 2001
From: Shraiysh Vaishay 
Date: Fri, 20 Oct 2023 16:54:51 -0500
Subject: [PATCH 2/2] Added comment about default values.

---
 mlir/test/Target/LLVMIR/openmp-teams.mlir | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/mlir/test/Target/LLVMIR/openmp-teams.mlir 
b/mlir/test/Target/LLVMIR/openmp-teams.mlir
index cc12dff6df1e376..973d2ed395eb0d0 100644
--- a/mlir/test/Target/LLVMIR/openmp-teams.mlir
+++ 

[clang-tools-extra] [clangd] Fix RawStringLiteral being available to C and C++ versions prior to C++11 (PR #69775)

2023-10-20 Thread via cfe-commits

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


[clang-tools-extra] [clangd] Fix RawStringLiteral being available to C and C++ versions prior to C++11 (PR #69775)

2023-10-20 Thread via cfe-commits

robozati wrote:

Tests are randomly failing, let me get what is wrong.

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


[clang] Support target names with dots in more utilities (PR #65812)

2023-10-20 Thread Dan McGregor via cfe-commits

dankm wrote:

No _good_ particular reason. I got hung up on the formatting issues then ran 
out of steam, and busy with $job. I just ran clang-format on this change and it 
came up clean.

And now that I've done that the only reason I have left is I'm unable to merge 
my own changes. Would you mind, @jh7370?

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


[clang] [OpenMP][mlir] Add translation for `if` in `omp.teams` (PR #69404)

2023-10-20 Thread via cfe-commits

https://github.com/shraiysh updated 
https://github.com/llvm/llvm-project/pull/69404

>From cf9e3e16a8b6f56e76c725b6244154b825cc8cc0 Mon Sep 17 00:00:00 2001
From: Shraiysh Vaishay 
Date: Tue, 17 Oct 2023 19:59:11 -0500
Subject: [PATCH] [OpenMP][mlir] Add translation for `if` in `omp.teams`

This patch adds translation for `if` clause on `teams` construct in
OpenMP Dialect.
---
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  |  8 +++-
 mlir/test/Target/LLVMIR/openmp-teams.mlir | 48 +++
 2 files changed, 54 insertions(+), 2 deletions(-)

diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index e3dc68a1b8b7d72..025f102f0fbf809 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -666,7 +666,7 @@ convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
,
 LLVM::ModuleTranslation ) {
   using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
   LogicalResult bodyGenStatus = success();
-  if (op.getIfExpr() || !op.getAllocatorsVars().empty() || op.getReductions())
+  if (!op.getAllocatorsVars().empty() || op.getReductions())
 return op.emitError("unhandled clauses for translation to LLVM IR");
 
   auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP) {
@@ -689,9 +689,13 @@ convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
,
   if (Value threadLimitVar = op.getThreadLimit())
 threadLimit = moduleTranslation.lookupValue(threadLimitVar);
 
+  llvm::Value *ifExpr = nullptr;
+  if (Value ifExprVar = op.getIfExpr())
+ifExpr = moduleTranslation.lookupValue(ifExprVar);
+
   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
   builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createTeams(
-  ompLoc, bodyCB, numTeamsLower, numTeamsUpper, threadLimit));
+  ompLoc, bodyCB, numTeamsLower, numTeamsUpper, threadLimit, ifExpr));
   return bodyGenStatus;
 }
 
diff --git a/mlir/test/Target/LLVMIR/openmp-teams.mlir 
b/mlir/test/Target/LLVMIR/openmp-teams.mlir
index 87ef90223ed704a..cc12dff6df1e376 100644
--- a/mlir/test/Target/LLVMIR/openmp-teams.mlir
+++ b/mlir/test/Target/LLVMIR/openmp-teams.mlir
@@ -235,3 +235,51 @@ llvm.func 
@omp_teams_num_teams_and_thread_limit(%numTeamsLower: i32, %numTeamsUp
 // CHECK: define internal void [[OUTLINED_FN]](ptr {{.+}}, ptr {{.+}})
 // CHECK: call void @duringTeams()
 // CHECK: ret void
+
+// -
+
+llvm.func @beforeTeams()
+llvm.func @duringTeams()
+llvm.func @afterTeams()
+
+// CHECK-LABEL: @teams_if
+// CHECK-SAME: (i1 [[ARG:.+]])
+llvm.func @teams_if(%arg : i1) {
+// CHECK-NEXT: call void @beforeTeams()
+llvm.call @beforeTeams() : () -> ()
+// CHECK: [[NUM_TEAMS_UPPER:%.+]] = select i1 [[ARG]], i32 0, i32 1
+// CHECK: [[NUM_TEAMS_LOWER:%.+]] = select i1 [[ARG]], i32 0, i32 1
+// CHECK: call void @__kmpc_push_num_teams_51(ptr {{.+}}, i32 {{.+}}, i32 
[[NUM_TEAMS_LOWER]], i32 [[NUM_TEAMS_UPPER]], i32 0)
+// CHECK: call void {{.+}} @__kmpc_fork_teams({{.+}})
+omp.teams if(%arg) {
+llvm.call @duringTeams() : () -> ()
+omp.terminator
+}
+// CHECK: call void @afterTeams()
+llvm.call @afterTeams() : () -> ()
+llvm.return
+}
+
+// -
+
+llvm.func @beforeTeams()
+llvm.func @duringTeams()
+llvm.func @afterTeams()
+
+// CHECK-LABEL: @teams_if_with_num_teams
+// CHECK-SAME: (i1 [[CONDITION:.+]], i32 [[NUM_TEAMS_LOWER:.+]], i32 
[[NUM_TEAMS_UPPER:.+]], i32 [[THREAD_LIMIT:.+]])
+llvm.func @teams_if_with_num_teams(%condition: i1, %numTeamsLower: i32, 
%numTeamsUpper: i32, %threadLimit: i32) {
+// CHECK: call void @beforeTeams()
+llvm.call @beforeTeams() : () -> ()
+// CHECK: [[NUM_TEAMS_UPPER_NEW:%.+]] = select i1 [[CONDITION]], i32 
[[NUM_TEAMS_UPPER]], i32 1
+// CHECK: [[NUM_TEAMS_LOWER_NEW:%.+]] = select i1 [[CONDITION]], i32 
[[NUM_TEAMS_LOWER]], i32 1
+// CHECK: call void @__kmpc_push_num_teams_51(ptr {{.+}}, i32 {{.+}}, i32 
[[NUM_TEAMS_LOWER_NEW]], i32 [[NUM_TEAMS_UPPER_NEW]], i32 [[THREAD_LIMIT]])
+// CHECK: call void {{.+}} @__kmpc_fork_teams({{.+}})
+omp.teams if(%condition) num_teams(%numTeamsLower: i32 to %numTeamsUpper: 
i32) thread_limit(%threadLimit: i32) {
+llvm.call @duringTeams() : () -> ()
+omp.terminator
+}
+// CHECK: call void @afterTeams()
+llvm.call @afterTeams() : () -> ()
+llvm.return
+}

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


[clang-tools-extra] [OpenMP][mlir] Add translation for `if` in `omp.teams` (PR #69404)

2023-10-20 Thread via cfe-commits

https://github.com/shraiysh updated 
https://github.com/llvm/llvm-project/pull/69404

>From cf9e3e16a8b6f56e76c725b6244154b825cc8cc0 Mon Sep 17 00:00:00 2001
From: Shraiysh Vaishay 
Date: Tue, 17 Oct 2023 19:59:11 -0500
Subject: [PATCH] [OpenMP][mlir] Add translation for `if` in `omp.teams`

This patch adds translation for `if` clause on `teams` construct in
OpenMP Dialect.
---
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  |  8 +++-
 mlir/test/Target/LLVMIR/openmp-teams.mlir | 48 +++
 2 files changed, 54 insertions(+), 2 deletions(-)

diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index e3dc68a1b8b7d72..025f102f0fbf809 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -666,7 +666,7 @@ convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
,
 LLVM::ModuleTranslation ) {
   using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
   LogicalResult bodyGenStatus = success();
-  if (op.getIfExpr() || !op.getAllocatorsVars().empty() || op.getReductions())
+  if (!op.getAllocatorsVars().empty() || op.getReductions())
 return op.emitError("unhandled clauses for translation to LLVM IR");
 
   auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP) {
@@ -689,9 +689,13 @@ convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase 
,
   if (Value threadLimitVar = op.getThreadLimit())
 threadLimit = moduleTranslation.lookupValue(threadLimitVar);
 
+  llvm::Value *ifExpr = nullptr;
+  if (Value ifExprVar = op.getIfExpr())
+ifExpr = moduleTranslation.lookupValue(ifExprVar);
+
   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
   builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createTeams(
-  ompLoc, bodyCB, numTeamsLower, numTeamsUpper, threadLimit));
+  ompLoc, bodyCB, numTeamsLower, numTeamsUpper, threadLimit, ifExpr));
   return bodyGenStatus;
 }
 
diff --git a/mlir/test/Target/LLVMIR/openmp-teams.mlir 
b/mlir/test/Target/LLVMIR/openmp-teams.mlir
index 87ef90223ed704a..cc12dff6df1e376 100644
--- a/mlir/test/Target/LLVMIR/openmp-teams.mlir
+++ b/mlir/test/Target/LLVMIR/openmp-teams.mlir
@@ -235,3 +235,51 @@ llvm.func 
@omp_teams_num_teams_and_thread_limit(%numTeamsLower: i32, %numTeamsUp
 // CHECK: define internal void [[OUTLINED_FN]](ptr {{.+}}, ptr {{.+}})
 // CHECK: call void @duringTeams()
 // CHECK: ret void
+
+// -
+
+llvm.func @beforeTeams()
+llvm.func @duringTeams()
+llvm.func @afterTeams()
+
+// CHECK-LABEL: @teams_if
+// CHECK-SAME: (i1 [[ARG:.+]])
+llvm.func @teams_if(%arg : i1) {
+// CHECK-NEXT: call void @beforeTeams()
+llvm.call @beforeTeams() : () -> ()
+// CHECK: [[NUM_TEAMS_UPPER:%.+]] = select i1 [[ARG]], i32 0, i32 1
+// CHECK: [[NUM_TEAMS_LOWER:%.+]] = select i1 [[ARG]], i32 0, i32 1
+// CHECK: call void @__kmpc_push_num_teams_51(ptr {{.+}}, i32 {{.+}}, i32 
[[NUM_TEAMS_LOWER]], i32 [[NUM_TEAMS_UPPER]], i32 0)
+// CHECK: call void {{.+}} @__kmpc_fork_teams({{.+}})
+omp.teams if(%arg) {
+llvm.call @duringTeams() : () -> ()
+omp.terminator
+}
+// CHECK: call void @afterTeams()
+llvm.call @afterTeams() : () -> ()
+llvm.return
+}
+
+// -
+
+llvm.func @beforeTeams()
+llvm.func @duringTeams()
+llvm.func @afterTeams()
+
+// CHECK-LABEL: @teams_if_with_num_teams
+// CHECK-SAME: (i1 [[CONDITION:.+]], i32 [[NUM_TEAMS_LOWER:.+]], i32 
[[NUM_TEAMS_UPPER:.+]], i32 [[THREAD_LIMIT:.+]])
+llvm.func @teams_if_with_num_teams(%condition: i1, %numTeamsLower: i32, 
%numTeamsUpper: i32, %threadLimit: i32) {
+// CHECK: call void @beforeTeams()
+llvm.call @beforeTeams() : () -> ()
+// CHECK: [[NUM_TEAMS_UPPER_NEW:%.+]] = select i1 [[CONDITION]], i32 
[[NUM_TEAMS_UPPER]], i32 1
+// CHECK: [[NUM_TEAMS_LOWER_NEW:%.+]] = select i1 [[CONDITION]], i32 
[[NUM_TEAMS_LOWER]], i32 1
+// CHECK: call void @__kmpc_push_num_teams_51(ptr {{.+}}, i32 {{.+}}, i32 
[[NUM_TEAMS_LOWER_NEW]], i32 [[NUM_TEAMS_UPPER_NEW]], i32 [[THREAD_LIMIT]])
+// CHECK: call void {{.+}} @__kmpc_fork_teams({{.+}})
+omp.teams if(%condition) num_teams(%numTeamsLower: i32 to %numTeamsUpper: 
i32) thread_limit(%threadLimit: i32) {
+llvm.call @duringTeams() : () -> ()
+omp.terminator
+}
+// CHECK: call void @afterTeams()
+llvm.call @afterTeams() : () -> ()
+llvm.return
+}

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


[PATCH] D158561: [-Wunsafe-buffer-usage] Add AST info to the unclaimed DRE debug notes for analysis

2023-10-20 Thread Ziqing Luo via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa4323586fcbb: [-Wunsafe-buffer-usage] Add AST info to the 
unclaimed DRE debug notes for… (authored by ziqingluo-90).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158561/new/

https://reviews.llvm.org/D158561

Files:
  clang/lib/Analysis/UnsafeBufferUsage.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/lit.local.cfg
  
clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/warn-unsafe-buffer-usage-debug-unclaimed.cpp
  clang/utils/analyze_safe_buffer_debug_notes.py

Index: clang/utils/analyze_safe_buffer_debug_notes.py
===
--- /dev/null
+++ clang/utils/analyze_safe_buffer_debug_notes.py
@@ -0,0 +1,39 @@
+import sys
+from collections import OrderedDict
+
+class Trie:
+def __init__(self, name):
+self.name = name
+self.children = OrderedDict()
+self.count = 1
+
+def add(self, name):
+if name in self.children:
+self.children[name].count += 1
+else:
+self.children[name] = Trie(name)
+return self.children[name]
+
+def print(self, depth):
+if depth > 0:
+print('|', end="")
+for i in range(depth):
+print('-', end="")
+if depth > 0:
+print(end=" ")
+print(self.name, '#', self.count)
+for key, child in self.children.items():
+child.print(depth + 1)
+
+
+Root = Trie("Root")
+
+if __name__ == "__main__":
+for line in sys.stdin:
+words = line.split('==>')
+words = [word.strip() for word in words]
+MyTrie = Root;
+for word in words:
+MyTrie = MyTrie.add(word)
+
+Root.print(0)
Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/warn-unsafe-buffer-usage-debug-unclaimed.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/warn-unsafe-buffer-usage-debug-unclaimed.cpp
@@ -0,0 +1,49 @@
+// RUN: %clang_cc1 -Wno-unused-value -Wunsafe-buffer-usage -fsafe-buffer-usage-suggestions \
+// RUN:-mllvm -debug-only=SafeBuffers \
+// RUN:-std=c++20 -verify=expected %s
+
+// RUN: %clang_cc1 -Wno-unused-value -Wunsafe-buffer-usage -fsafe-buffer-usage-suggestions \
+// RUN:-mllvm -debug-only=SafeBuffers \
+// RUN:-std=c++20 %s  \
+// RUN:2>&1 | grep 'The unclaimed DRE trace:' \
+// RUN: | sed 's/^The unclaimed DRE trace://' \
+// RUN: | %analyze_safe_buffer_debug_notes \
+// RUN: | FileCheck %s
+
+// This debugging facility is only available in debug builds.
+//
+// REQUIRES: asserts
+// REQUIRES: shell
+
+void test_unclaimed_use(int *p) { // expected-warning{{'p' is an unsafe pointer used for buffer access}}
+  p++;   //  expected-note{{used in pointer arithmetic here}} \
+ expected-note{{safe buffers debug: failed to produce fixit for 'p' : has an unclaimed use\n \
+ The unclaimed DRE trace: DeclRefExpr, UnaryOperator(++), CompoundStmt}}
+  *((p + 1) + 1); // expected-warning{{unsafe pointer arithmetic}}  \
+ expected-note{{used in pointer arithmetic here}}			\
+		 expected-note{{safe buffers debug: failed to produce fixit for 'p' : has an unclaimed use\n \
+  The unclaimed DRE trace: DeclRefExpr, ImplicitCastExpr(LValueToRValue), BinaryOperator(+), ParenExpr, BinaryOperator(+), ParenExpr, UnaryOperator(*), CompoundStmt}}
+  p -= 1; // expected-note{{used in pointer arithmetic here}} \
+		 expected-note{{safe buffers debug: failed to produce fixit for 'p' : has an unclaimed use\n \
+  The unclaimed DRE trace: DeclRefExpr, BinaryOperator(-=), CompoundStmt}}
+  p--;// expected-note{{used in pointer arithmetic here}} \
+ 		 expected-note{{safe buffers debug: failed to produce fixit for 'p' : has an unclaimed use\n \
+  The unclaimed DRE trace: DeclRefExpr, UnaryOperator(--), CompoundStmt}}
+  p[5] = 5;   // expected-note{{used in buffer access here}}
+}
+
+// CHECK: Root # 1
+// CHECK: |- DeclRefExpr # 4
+// CHECK: |-- UnaryOperator(++) # 1
+// CHECK: |--- CompoundStmt # 1
+// CHECK: |-- ImplicitCastExpr(LValueToRValue) # 1
+// CHECK: |--- BinaryOperator(+) # 1
+// CHECK: | ParenExpr # 1
+// CHECK: |- BinaryOperator(+) # 1
+// CHECK: |-- ParenExpr # 1
+// CHECK: |--- UnaryOperator(*) # 1
+// CHECK: | CompoundStmt # 1
+// CHECK: |-- BinaryOperator(-=) # 1
+// CHECK: |--- CompoundStmt # 1
+// CHECK: |-- UnaryOperator(--) # 1
+// CHECK: |--- CompoundStmt # 1
Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/lit.local.cfg
===
--- /dev/null
+++ 

[clang] a432358 - [-Wunsafe-buffer-usage] Add AST info to the unclaimed DRE debug notes for analysis

2023-10-20 Thread via cfe-commits

Author: ziqingluo-90
Date: 2023-10-20T14:27:14-07:00
New Revision: a4323586fcbb20f39f00d5d1bc4a94a1aeea15c4

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

LOG: [-Wunsafe-buffer-usage] Add AST info to the unclaimed DRE debug notes for 
analysis

- For a better understand of what the unsupported cases are, we add
  more information to the debug note---a string of ancestor AST nodes
  of the unclaimed DRE. For example, an unclaimed DRE p in an
  expression `*(p++)` will result in a string starting with
  `DRE ==> UnaryOperator(++) ==> Paren ==> UnaryOperator(*)`.

- To find out the most common patterns of those unsupported use cases,
  we add a simple script to build a prefix tree over those strings and
  count each prefix. The script reads input line by line, assumes a
  line is a list of words separated by `==>`s, and builds a prefix tree
  over those lists.

Reviewed by: t-rasmud (Rashmi Mudduluru), NoQ (Artem Dergachev)

Differential revision: https://reviews.llvm.org/D158561

Added: 
clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/lit.local.cfg

clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/warn-unsafe-buffer-usage-debug-unclaimed.cpp
clang/utils/analyze_safe_buffer_debug_notes.py

Modified: 
clang/lib/Analysis/UnsafeBufferUsage.cpp

Removed: 




diff  --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 49cfa7c0d3e3b27..e332a3609290aac 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -8,7 +8,9 @@
 
 #include "clang/Analysis/Analyses/UnsafeBufferUsage.h"
 #include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/StmtVisitor.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Lex/Preprocessor.h"
@@ -22,6 +24,52 @@ using namespace llvm;
 using namespace clang;
 using namespace ast_matchers;
 
+#ifndef NDEBUG
+namespace {
+class StmtDebugPrinter
+: public ConstStmtVisitor {
+public:
+  std::string VisitStmt(const Stmt *S) { return S->getStmtClassName(); }
+
+  std::string VisitBinaryOperator(const BinaryOperator *BO) {
+return "BinaryOperator(" + BO->getOpcodeStr().str() + ")";
+  }
+
+  std::string VisitUnaryOperator(const UnaryOperator *UO) {
+return "UnaryOperator(" + UO->getOpcodeStr(UO->getOpcode()).str() + ")";
+  }
+
+  std::string VisitImplicitCastExpr(const ImplicitCastExpr *ICE) {
+return "ImplicitCastExpr(" + std::string(ICE->getCastKindName()) + ")";
+  }
+};
+
+// Returns a string of ancestor `Stmt`s of the given `DRE` in such a form:
+// "DRE ==> parent-of-DRE ==> grandparent-of-DRE ==> ...".
+static std::string getDREAncestorString(const DeclRefExpr *DRE,
+ASTContext ) {
+  std::stringstream SS;
+  const Stmt *St = DRE;
+  StmtDebugPrinter StmtPriner;
+
+  do {
+SS << StmtPriner.Visit(St);
+
+DynTypedNodeList StParents = Ctx.getParents(*St);
+
+if (StParents.size() > 1)
+  return "unavailable due to multiple parents";
+if (StParents.size() == 0)
+  break;
+St = StParents.begin()->get();
+if (St)
+  SS << " ==> ";
+  } while (St);
+  return SS.str();
+}
+} // namespace
+#endif /* NDEBUG */
+
 namespace clang::ast_matchers {
 // A `RecursiveASTVisitor` that traverses all descendants of a given node "n"
 // except for those belonging to a 
diff erent callable of "n".
@@ -2589,11 +2637,15 @@ void clang::checkUnsafeBufferUsage(const Decl *D,
 #ifndef NDEBUG
 auto AllUnclaimed = Tracker.getUnclaimedUses(it->first);
 for (auto UnclaimedDRE : AllUnclaimed) {
-  Handler.addDebugNoteForVar(
-  it->first, UnclaimedDRE->getBeginLoc(),
- ("failed to produce fixit for '" + 
it->first->getNameAsString() +
-  "' : has an unclaimed use"));
-  }
+std::string UnclaimedUseTrace =
+getDREAncestorString(UnclaimedDRE, D->getASTContext());
+
+Handler.addDebugNoteForVar(
+it->first, UnclaimedDRE->getBeginLoc(),
+("failed to produce fixit for '" + it->first->getNameAsString() +
+ "' : has an unclaimed use\nThe unclaimed DRE trace: " +
+ UnclaimedUseTrace));
+}
 #endif
 it = FixablesForAllVars.byVar.erase(it);
   } else if (it->first->isInitCapture()) {

diff  --git 
a/clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/lit.local.cfg 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/lit.local.cfg
new file mode 100644
index 000..07bac415a1a64c0
--- /dev/null
+++ 

[libunwind] [libunwind][AIX] static_cast the value from getLR() to avoid the warning from -Wconversion (PR #69767)

2023-10-20 Thread via cfe-commits

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


[libunwind] [libunwind][AIX] static_cast the value from getLR() to avoid the warning from -Wconversion (PR #69767)

2023-10-20 Thread via cfe-commits

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


[libunwind] [libunwind][AIX] static_cast the value from getLR() to avoid the warning from -Wconversion (PR #69767)

2023-10-20 Thread via cfe-commits

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


[clang-tools-extra] [clangd] Fix RawStringLiteral being available to C and C++ versions prior to C++11 (PR #69775)

2023-10-20 Thread via cfe-commits

https://github.com/robozati updated 
https://github.com/llvm/llvm-project/pull/69775

>From c644be1d123769395bed6ea069a45c051e3fc66d Mon Sep 17 00:00:00 2001
From: robozati <139823421+roboz...@users.noreply.github.com>
Date: Fri, 20 Oct 2023 17:23:21 -0300
Subject: [PATCH 1/2] Fix RawStringLiteral being available to C and C++
 versions prior to C++11

---
 .../refactor/tweaks/RawStringLiteral.cpp   |  8 +++-
 .../unittests/tweaks/RawStringLiteralTests.cpp | 18 ++
 2 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
index f5021b820f38d7f..82c908b494790cb 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
@@ -43,6 +43,12 @@ class RawStringLiteral : public Tweak {
 
 REGISTER_TWEAK(RawStringLiteral)
 
+static bool isFeatureAvailable(const Tweak::Selection ) {
+  // Raw strings are available only for C++11 or later versions, and they are
+  // not available for C.
+  return Inputs.AST->getASTContext().getLangOpts().CPlusPlus11;
+}
+
 static bool isNormalString(const StringLiteral , SourceLocation Cursor,
   SourceManager ) {
   // All chunks must be normal ASCII strings, not u8"..." etc.
@@ -76,7 +82,7 @@ bool RawStringLiteral::prepare(const Selection ) {
   if (!N)
 return false;
   Str = dyn_cast_or_null(N->ASTNode.get());
-  return Str &&
+  return Str && isFeatureAvailable(Inputs) &&
  isNormalString(*Str, Inputs.Cursor, Inputs.AST->getSourceManager()) &&
  needsRaw(Str->getBytes()) && canBeRaw(Str->getBytes());
 }
diff --git 
a/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
index 4bc304559705031..0e96dfbe2e376bc 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
@@ -36,6 +36,24 @@ literal)")cpp";
   EXPECT_EQ(apply(Input), Output);
 }
 
+TEST_F(RawStringLiteralTest, TestC) {
+  Context = File;
+  FileName = "TestTU.c";
+  ExtraArgs = {"-xc"}; // raw strings are unavailable in C
+  EXPECT_UNAVAILABLE(R"c(
+const char* a = "^f^o^o^\^n^";
+  )c");
+}
+
+TEST_F(RawStringLiteralTest, TestCpp98) {
+  Context = File;
+  ExtraArgs = {"-std=c++98"}; // raw strings are unavailable
+  // in versions prior to C++11
+  EXPECT_UNAVAILABLE(R"cpp(
+const char* a = "^f^o^o^\^n^";
+  )cpp");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang

>From 0ece5387802ca2ab922da32abb092c6b07e097d5 Mon Sep 17 00:00:00 2001
From: robozati <139823421+roboz...@users.noreply.github.com>
Date: Fri, 20 Oct 2023 18:21:29 -0300
Subject: [PATCH 2/2] Make tests more readable

---
 .../clangd/unittests/tweaks/RawStringLiteralTests.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git 
a/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
index 0e96dfbe2e376bc..8a3738fb7e2fa4f 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
@@ -41,7 +41,7 @@ TEST_F(RawStringLiteralTest, TestC) {
   FileName = "TestTU.c";
   ExtraArgs = {"-xc"}; // raw strings are unavailable in C
   EXPECT_UNAVAILABLE(R"c(
-const char* a = "^f^o^o^\^n^";
+const char* a = "foo\n";
   )c");
 }
 
@@ -50,7 +50,7 @@ TEST_F(RawStringLiteralTest, TestCpp98) {
   ExtraArgs = {"-std=c++98"}; // raw strings are unavailable
   // in versions prior to C++11
   EXPECT_UNAVAILABLE(R"cpp(
-const char* a = "^f^o^o^\^n^";
+const char* a = "foo\n";
   )cpp");
 }
 

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


[clang] [clang] [unittest] Add a test for Generic_GCC::GCCVersion::Parse (PR #69078)

2023-10-20 Thread Martin Storsjö via cfe-commits

mstorsjo wrote:

> ```c
> #if !defined(LLVM_BUILD_SHARED_LIBS)
> ```
> 
> is not great but is not too bad. `-DBUILD_SHARED_LIBS=on` modes are slow to 
> execute tests and are not used often for Release builds.

I went ahead and relanded this now, in 
538b7ba2aacd6e400ee63c4f9ff1c2543ae69a90, with `#if 
!defined(LLVM_BUILD_LLVM_DYLIB) && !defined(LLVM_BUILD_SHARED_LIBS)`. Not 
great, but probably the least bad compromise.

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


[clang] 538b7ba - Reland [clang] [unittest] Add a test for Generic_GCC::GCCVersion::Parse (#69078)

2023-10-20 Thread Martin Storsjö via cfe-commits

Author: Martin Storsjö
Date: 2023-10-20T23:34:28+03:00
New Revision: 538b7ba2aacd6e400ee63c4f9ff1c2543ae69a90

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

LOG: Reland [clang] [unittest] Add a test for Generic_GCC::GCCVersion::Parse 
(#69078)

This adds actual test cases for all the cases that are listed in a code
comment in the implementation of this function; having such test
coverage eases doing further modifications to the function.

This relands b4b35a5d2b4ee26bf79b8a92715dd200f3f9cc49. This time,
the new test is excluded if building with dylibs or shared libraries
enabled, as the clang::toolchains::Generic_GCC class is marked
LLVM_LIBRARY_VISIBILITY, giving it hidden visibility in such builds,
making it unreferencable outside of the dylib/shared library.

Added: 
clang/unittests/Driver/GCCVersionTest.cpp

Modified: 
clang/unittests/Driver/CMakeLists.txt

Removed: 




diff  --git a/clang/unittests/Driver/CMakeLists.txt 
b/clang/unittests/Driver/CMakeLists.txt
index e37c158d7137a88..752037f78fb147d 100644
--- a/clang/unittests/Driver/CMakeLists.txt
+++ b/clang/unittests/Driver/CMakeLists.txt
@@ -9,6 +9,7 @@ set(LLVM_LINK_COMPONENTS
 add_clang_unittest(ClangDriverTests
   DistroTest.cpp
   DXCModeTest.cpp
+  GCCVersionTest.cpp
   ToolChainTest.cpp
   ModuleCacheTest.cpp
   MultilibBuilderTest.cpp

diff  --git a/clang/unittests/Driver/GCCVersionTest.cpp 
b/clang/unittests/Driver/GCCVersionTest.cpp
new file mode 100644
index 000..88c26dfe814e3ff
--- /dev/null
+++ b/clang/unittests/Driver/GCCVersionTest.cpp
@@ -0,0 +1,59 @@
+//===- unittests/Driver/GCCVersionTest.cpp --- GCCVersion parser tests 
===//
+//
+// 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
+//
+//===--===//
+//
+// Unit tests for Generic_GCC::GCCVersion
+//
+//===--===//
+
+#include "../../lib/Driver/ToolChains/Gnu.h"
+#include "gtest/gtest.h"
+
+// The Generic_GCC class is hidden in dylib/shared library builds, so
+// this test can only be built if neither of those configurations are
+// enabled.
+#if !defined(LLVM_BUILD_LLVM_DYLIB) && !defined(LLVM_BUILD_SHARED_LIBS)
+
+using namespace clang;
+using namespace clang::driver;
+
+namespace {
+
+struct VersionParseTest {
+  std::string Text;
+
+  int Major, Minor, Patch;
+  std::string MajorStr, MinorStr, PatchSuffix;
+};
+
+const VersionParseTest TestCases[] = {
+{"5", 5, -1, -1, "5", "", ""},
+{"4.4", 4, 4, -1, "4", "4", ""},
+{"4.4-patched", 4, 4, -1, "4", "4", "-patched"},
+{"4.4.0", 4, 4, 0, "4", "4", ""},
+{"4.4.x", 4, 4, -1, "4", "4", ""},
+{"4.4.2-rc4", 4, 4, 2, "4", "4", "-rc4"},
+{"4.4.x-patched", 4, 4, -1, "4", "4", ""},
+{"not-a-version", -1, -1, -1, "", "", ""},
+};
+
+TEST(GCCVersionTest, Parse) {
+  for (const auto  : TestCases) {
+auto V = toolchains::Generic_GCC::GCCVersion::Parse(TC.Text);
+EXPECT_EQ(V.Text, TC.Text);
+EXPECT_EQ(V.Major, TC.Major);
+EXPECT_EQ(V.Minor, TC.Minor);
+EXPECT_EQ(V.Patch, TC.Patch);
+EXPECT_EQ(V.MajorStr, TC.MajorStr);
+EXPECT_EQ(V.MinorStr, TC.MinorStr);
+EXPECT_EQ(V.PatchSuffix, TC.PatchSuffix);
+  }
+}
+
+} // end anonymous namespace
+
+#endif



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


[clang-tools-extra] [clangd] Fix RawStringLiteral being available to C and C++ versions prior to C++11 (PR #69775)

2023-10-20 Thread via cfe-commits

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


[clang-tools-extra] Fix RawStringLiteral being available to C and C++ versions prior to C++11 (PR #69775)

2023-10-20 Thread via cfe-commits

https://github.com/robozati created 
https://github.com/llvm/llvm-project/pull/69775

The `RawStringLiteral` code action runs both on C and C++ versions prior to 
C++11, where this feature is unavailable.

This patch adds a condition to check if the context is running a version equal 
or greater than C++11 and adds tests for failing in the wrong versions.

Fixes https://github.com/clangd/clangd/issues/1795.

>From c644be1d123769395bed6ea069a45c051e3fc66d Mon Sep 17 00:00:00 2001
From: robozati <139823421+roboz...@users.noreply.github.com>
Date: Fri, 20 Oct 2023 17:23:21 -0300
Subject: [PATCH] Fix RawStringLiteral being available to C and C++ versions
 prior to C++11

---
 .../refactor/tweaks/RawStringLiteral.cpp   |  8 +++-
 .../unittests/tweaks/RawStringLiteralTests.cpp | 18 ++
 2 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
index f5021b820f38d7f..82c908b494790cb 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/RawStringLiteral.cpp
@@ -43,6 +43,12 @@ class RawStringLiteral : public Tweak {
 
 REGISTER_TWEAK(RawStringLiteral)
 
+static bool isFeatureAvailable(const Tweak::Selection ) {
+  // Raw strings are available only for C++11 or later versions, and they are
+  // not available for C.
+  return Inputs.AST->getASTContext().getLangOpts().CPlusPlus11;
+}
+
 static bool isNormalString(const StringLiteral , SourceLocation Cursor,
   SourceManager ) {
   // All chunks must be normal ASCII strings, not u8"..." etc.
@@ -76,7 +82,7 @@ bool RawStringLiteral::prepare(const Selection ) {
   if (!N)
 return false;
   Str = dyn_cast_or_null(N->ASTNode.get());
-  return Str &&
+  return Str && isFeatureAvailable(Inputs) &&
  isNormalString(*Str, Inputs.Cursor, Inputs.AST->getSourceManager()) &&
  needsRaw(Str->getBytes()) && canBeRaw(Str->getBytes());
 }
diff --git 
a/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
index 4bc304559705031..0e96dfbe2e376bc 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/RawStringLiteralTests.cpp
@@ -36,6 +36,24 @@ literal)")cpp";
   EXPECT_EQ(apply(Input), Output);
 }
 
+TEST_F(RawStringLiteralTest, TestC) {
+  Context = File;
+  FileName = "TestTU.c";
+  ExtraArgs = {"-xc"}; // raw strings are unavailable in C
+  EXPECT_UNAVAILABLE(R"c(
+const char* a = "^f^o^o^\^n^";
+  )c");
+}
+
+TEST_F(RawStringLiteralTest, TestCpp98) {
+  Context = File;
+  ExtraArgs = {"-std=c++98"}; // raw strings are unavailable
+  // in versions prior to C++11
+  EXPECT_UNAVAILABLE(R"cpp(
+const char* a = "^f^o^o^\^n^";
+  )cpp");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang

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


[clang] [Driver] Hook up Haiku PowerPC support (PR #69134)

2023-10-20 Thread Brad Smith via cfe-commits

brad0 wrote:

Ping.

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


[clang] [Windows] Add git-clang-format wrapper bat file (PR #69228)

2023-10-20 Thread Owen Pan via cfe-commits

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


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


[libclc] [AMDGPU][MachineScheduler] Alternative way to control excess RP. (PR #68004)

2023-10-20 Thread Jeffrey Byrnes via cfe-commits

https://github.com/jrbyrnes commented:

Just have a few questions about implementation details -- at a higher level, 
seems like we are trading one heuristic for another w.r.t flagging regions as 
ExcessRP -- so I'm curious about the relative performance.

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


[clang] [AMDGPU][MachineScheduler] Alternative way to control excess RP. (PR #68004)

2023-10-20 Thread Jeffrey Byrnes via cfe-commits

https://github.com/jrbyrnes commented:

Just have a few questions about implementation details -- at a higher level, 
seems like we are trading one heuristic for another w.r.t flagging regions as 
ExcessRP -- so I'm curious about the relative performance.

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


[libclc] [AMDGPU][MachineScheduler] Alternative way to control excess RP. (PR #68004)

2023-10-20 Thread Jeffrey Byrnes via cfe-commits


@@ -894,10 +894,22 @@ void GCNSchedStage::setupNewBlock() {
 
 void GCNSchedStage::finalizeGCNRegion() {
   DAG.Regions[RegionIdx] = std::pair(DAG.RegionBegin, DAG.RegionEnd);
-  DAG.RescheduleRegions[RegionIdx] = false;

jrbyrnes wrote:

Why was this removed?

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


[libclc] [AMDGPU][MachineScheduler] Alternative way to control excess RP. (PR #68004)

2023-10-20 Thread Jeffrey Byrnes via cfe-commits


@@ -959,16 +970,6 @@ void GCNSchedStage::checkScheduling() {
   << DAG.MinOccupancy << ".\n");
   }
 
-  unsigned MaxVGPRs = ST.getMaxNumVGPRs(MF);
-  unsigned MaxSGPRs = ST.getMaxNumSGPRs(MF);
-  if (PressureAfter.getVGPRNum(false) > MaxVGPRs ||
-  PressureAfter.getAGPRNum() > MaxVGPRs ||
-  PressureAfter.getSGPRNum() > MaxSGPRs) {
-DAG.RescheduleRegions[RegionIdx] = true;

jrbyrnes wrote:

Why do we drop the maxNumGPR checks -- these are wavesPerEU aware?

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


[clang-tools-extra] [AMDGPU][MachineScheduler] Alternative way to control excess RP. (PR #68004)

2023-10-20 Thread Jeffrey Byrnes via cfe-commits


@@ -1117,16 +1118,23 @@ bool 
OccInitialScheduleStage::shouldRevertScheduling(unsigned WavesAfter) {
 bool UnclusteredHighRPStage::shouldRevertScheduling(unsigned WavesAfter) {
   // If RP is not reduced in the unclustered reschedule stage, revert to the
   // old schedule.
-  if ((WavesAfter <= PressureBefore.getOccupancy(ST) &&
-   mayCauseSpilling(WavesAfter)) ||
-  GCNSchedStage::shouldRevertScheduling(WavesAfter)) {
-LLVM_DEBUG(dbgs() << "Unclustered reschedule did not help.\n");
-return true;
-  }
+  if (DAG.RegionsWithExcessRP[RegionIdx]) {

jrbyrnes wrote:

Should still revert if occupancy has dropped 
(GCNSchedStage::shouldRevertScheduling)?

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


[clang] [AMDGPU][MachineScheduler] Alternative way to control excess RP. (PR #68004)

2023-10-20 Thread Jeffrey Byrnes via cfe-commits


@@ -702,7 +702,7 @@ bool UnclusteredHighRPStage::initGCNSchedStage() {
   if (!GCNSchedStage::initGCNSchedStage())
 return false;
 
-  if (DAG.RegionsWithHighRP.none() && DAG.RegionsWithExcessRP.none())
+  if (DAG.RegionsWithExcessRP.none())

jrbyrnes wrote:

What about regions that are close to the critical limit?

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


[clang-tools-extra] [AMDGPU][MachineScheduler] Alternative way to control excess RP. (PR #68004)

2023-10-20 Thread Jeffrey Byrnes via cfe-commits

https://github.com/jrbyrnes commented:

Just have a few questions about implementation details -- at a higher level, 
seems like we are trading one heuristic for another w.r.t flagging regions as 
ExcessRP -- so I'm curious about the relative performance.

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


[clang] [Modules] textual headers in submodules never resolve their `use`s (PR #69651)

2023-10-20 Thread Ian Anderson via cfe-commits

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


[clang] 09ec000 - [Modules] textual headers in submodules never resolve their `use`s (#69651)

2023-10-20 Thread via cfe-commits

Author: Ian Anderson
Date: 2023-10-20T13:23:34-07:00
New Revision: 09ec0004eee2d9929d25cf519956cc470ffb33dd

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

LOG: [Modules] textual headers in submodules never resolve their `use`s (#69651)

When an include from a textual header is resolved, the textual header's
submodule is used as the requesting module. The submodule's uses are
resolved, but that doesn't work because only top level modules have
uses, and only the top level module uses are used for checking uses in
Module::directlyUses. ModuleMap::resolveUses to resolve the top level
module instead of the submodule.

Added: 
clang/test/Modules/no-undeclared-includes.c

Modified: 
clang/lib/Lex/ModuleMap.cpp

Removed: 




diff  --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp
index 7fd92bff8048429..eb7cab54386c480 100644
--- a/clang/lib/Lex/ModuleMap.cpp
+++ b/clang/lib/Lex/ModuleMap.cpp
@@ -1398,16 +1398,17 @@ bool ModuleMap::resolveExports(Module *Mod, bool 
Complain) {
 }
 
 bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
-  auto Unresolved = std::move(Mod->UnresolvedDirectUses);
-  Mod->UnresolvedDirectUses.clear();
+  auto *Top = Mod->getTopLevelModule();
+  auto Unresolved = std::move(Top->UnresolvedDirectUses);
+  Top->UnresolvedDirectUses.clear();
   for (auto  : Unresolved) {
-Module *DirectUse = resolveModuleId(UDU, Mod, Complain);
+Module *DirectUse = resolveModuleId(UDU, Top, Complain);
 if (DirectUse)
-  Mod->DirectUses.push_back(DirectUse);
+  Top->DirectUses.push_back(DirectUse);
 else
-  Mod->UnresolvedDirectUses.push_back(UDU);
+  Top->UnresolvedDirectUses.push_back(UDU);
   }
-  return !Mod->UnresolvedDirectUses.empty();
+  return !Top->UnresolvedDirectUses.empty();
 }
 
 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {

diff  --git a/clang/test/Modules/no-undeclared-includes.c 
b/clang/test/Modules/no-undeclared-includes.c
new file mode 100644
index 000..83a654f6ed77539
--- /dev/null
+++ b/clang/test/Modules/no-undeclared-includes.c
@@ -0,0 +1,31 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -fmodules-cache-path=%t -fmodules -fimplicit-module-maps -I 
%t %t/no-undeclared-includes.c -verify
+
+//--- no-undeclared-includes.c
+// expected-no-diagnostics
+#include 
+
+//--- assert.h
+#include 
+
+//--- base.h
+#ifndef base_h
+#define base_h
+
+
+
+#endif /* base_h */
+
+//--- module.modulemap
+module cstd [system] [no_undeclared_includes] {
+  use base
+  module assert {
+textual header "assert.h"
+  }
+}
+
+module base [system] {
+  header "base.h"
+  export *
+}



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


[clang] [clang-format] Skip PP directives when determining brace kind (PR #69473)

2023-10-20 Thread Owen Pan via cfe-commits

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


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


[clang] [clang] Add clang::preferred_type attribute for bitfields (PR #69104)

2023-10-20 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

> but I also see "you got what you asked for!" as being a reasonable defense to 
> that.

That's my thinking indeed, and the reason why I opposed to Aaron's proposal to 
implicitly mark 1-bit bit-fields as `preferred_type(bool)`.

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


[libunwind] [libunwind][AIX] static_cast the value from getLR() to avoid the warning from -Wconversion (PR #69767)

2023-10-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-libunwind

Author: None (xingxue-ibm)


Changes

This PR adds `static_cast` to the value returned from `getLR()` in the AIX 
unwinder to avoid warning if `-Wconversion` is specified for building in 32-bit 
mode.

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


1 Files Affected:

- (modified) libunwind/src/UnwindCursor.hpp (+1-1) 


``diff
diff --git a/libunwind/src/UnwindCursor.hpp b/libunwind/src/UnwindCursor.hpp
index f89c5b2c2f73e33..647a5a9c9d92d91 100644
--- a/libunwind/src/UnwindCursor.hpp
+++ b/libunwind/src/UnwindCursor.hpp
@@ -2404,7 +2404,7 @@ int UnwindCursor::stepWithTBTable(pint_t pc, 
tbtable *TBTable,
 if (!TBTable->tb.saves_lr && registers.getLR()) {
   // This case should only occur if we were called from a signal handler
   // and the signal occurred in a function that doesn't save the LR.
-  returnAddress = registers.getLR();
+  returnAddress = static_cast(registers.getLR());
   _LIBUNWIND_TRACE_UNWINDING("Use saved LR=%p",
  reinterpret_cast(returnAddress));
 } else {

``




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


[libunwind] [libunwind][AIX] static_cast the value from getLR() to avoid the warning from -Wconversion (PR #69767)

2023-10-20 Thread via cfe-commits

https://github.com/xingxue-ibm created 
https://github.com/llvm/llvm-project/pull/69767

This PR adds `static_cast` to the value returned from `getLR()` in the AIX 
unwinder to avoid warning if `-Wconversion` is specified for building in 32-bit 
mode.

>From 2255e2c9a66420bba36bf4ba7f3d8db36d7e4dfc Mon Sep 17 00:00:00 2001
From: Xing Xue 
Date: Fri, 20 Oct 2023 15:54:56 -0400
Subject: [PATCH] Add static_cast for the value from getLR() to avoid the
 warning from -Wconversion when it is in 32-bit mode.

---
 libunwind/src/UnwindCursor.hpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/libunwind/src/UnwindCursor.hpp b/libunwind/src/UnwindCursor.hpp
index f89c5b2c2f73e33..647a5a9c9d92d91 100644
--- a/libunwind/src/UnwindCursor.hpp
+++ b/libunwind/src/UnwindCursor.hpp
@@ -2404,7 +2404,7 @@ int UnwindCursor::stepWithTBTable(pint_t pc, 
tbtable *TBTable,
 if (!TBTable->tb.saves_lr && registers.getLR()) {
   // This case should only occur if we were called from a signal handler
   // and the signal occurred in a function that doesn't save the LR.
-  returnAddress = registers.getLR();
+  returnAddress = static_cast(registers.getLR());
   _LIBUNWIND_TRACE_UNWINDING("Use saved LR=%p",
  reinterpret_cast(returnAddress));
 } else {

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


[clang] [libc++] Fix the behavior of throwing `operator new` under -fno-exceptions (PR #69498)

2023-10-20 Thread via cfe-commits

EricWF wrote:

> We currently support both ways of building the library (-fexceptions and 
> -fno-exceptions). I don't know how widely used the -fno-exceptions variant is 
> used and we could discuss dropping it (and forcing people to always build the 
> library itself with -fexceptions), but IMO this should be a separate change. 
> In practice, I suspect that a lot of folks in the embedded world might be 
> building the library with -fno-exceptions.

My only concern is that this change introduces a bunch of black-magic, which I 
suspect is pretty fragile (but I don't know), and I would like to avoid that if 
possible.



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


[clang] [clang] use relative paths for builtin headers during module compilation (PR #68023)

2023-10-20 Thread Richard Howell via cfe-commits

https://github.com/rmaz updated https://github.com/llvm/llvm-project/pull/68023

>From 5e3c6319c6a98a07dab6571f65ad1320815d76bf Mon Sep 17 00:00:00 2001
From: Richard Howell 
Date: Mon, 2 Oct 2023 11:10:52 -0700
Subject: [PATCH] [clang] add module builtin headers relative to resource dir

When including builtin headers as part of a system module, serialize
them relative to the builtin include dir. To handle later lookup
add a method to provide the correct base directory. This makes it
possible to compile modules including builtin headers with
relative resource dirs.
---
 clang/include/clang/Lex/ModuleMap.h   |  5 -
 clang/lib/Lex/ModuleMap.cpp   |  9 -
 clang/lib/Lex/PPDirectives.cpp|  9 -
 .../Modules/Inputs/builtin-headers/module.modulemap   |  3 +++
 clang/test/Modules/relative-resource-dir.m| 11 +++
 5 files changed, 34 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Modules/Inputs/builtin-headers/module.modulemap
 create mode 100644 clang/test/Modules/relative-resource-dir.m

diff --git a/clang/include/clang/Lex/ModuleMap.h 
b/clang/include/clang/Lex/ModuleMap.h
index fc49742ad4af2c1..545d07c071c40e5 100644
--- a/clang/include/clang/Lex/ModuleMap.h
+++ b/clang/include/clang/Lex/ModuleMap.h
@@ -410,13 +410,16 @@ class ModuleMap {
   }
 
   /// Get the directory that contains Clang-supplied include files.
-  const DirectoryEntry *getBuiltinDir() const {
+  OptionalDirectoryEntryRefDegradesToDirectoryEntryPtr getBuiltinDir() const {
 return BuiltinIncludeDir;
   }
 
   /// Is this a compiler builtin header?
   bool isBuiltinHeader(FileEntryRef File);
 
+  bool shouldImportRelativeToBuiltinIncludeDir(StringRef FileName,
+   Module *Module) const;
+
   /// Add a module map callback.
   void addModuleMapCallbacks(std::unique_ptr Callback) {
 Callbacks.push_back(std::move(Callback));
diff --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp
index e8437572ebf4bf6..b7c1aee8c174dc7 100644
--- a/clang/lib/Lex/ModuleMap.cpp
+++ b/clang/lib/Lex/ModuleMap.cpp
@@ -348,8 +348,8 @@ bool ModuleMap::resolveAsBuiltinHeader(
   if (!File)
 return false;
 
+  Module::Header H = {Header.FileName, Header.FileName, *File};
   auto Role = headerKindToRole(Header.Kind);
-  Module::Header H = {Header.FileName, std::string(Path.str()), *File};
   addHeader(Mod, H, Role);
   return true;
 }
@@ -417,6 +417,13 @@ bool ModuleMap::isBuiltinHeader(FileEntryRef File) {
  isBuiltinHeaderName(llvm::sys::path::filename(File.getName()));
 }
 
+bool ModuleMap::shouldImportRelativeToBuiltinIncludeDir(StringRef FileName,
+Module *Module) const {
+  return LangOpts.BuiltinHeadersInSystemModules && BuiltinIncludeDir &&
+ Module->IsSystem && !Module->isPartOfFramework() &&
+ isBuiltinHeaderName(FileName);
+}
+
 ModuleMap::HeadersMap::iterator ModuleMap::findKnownHeader(FileEntryRef File) {
   resolveHeaderDirectives(File);
   HeadersMap::iterator Known = Headers.find(File);
diff --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index 7899bfa1c4f5842..5d6aa4906b757d9 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -12,6 +12,7 @@
 
//===--===//
 
 #include "clang/Basic/CharInfo.h"
+#include "clang/Basic/DirectoryEntry.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/LangOptions.h"
@@ -21,6 +22,7 @@
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/CodeCompletionHandler.h"
 #include "clang/Lex/HeaderSearch.h"
+#include "clang/Lex/HeaderSearchOptions.h"
 #include "clang/Lex/LexDiagnostic.h"
 #include "clang/Lex/LiteralSupport.h"
 #include "clang/Lex/MacroInfo.h"
@@ -981,7 +983,12 @@ OptionalFileEntryRef Preprocessor::LookupFile(
 // map file.
 if (!FileEnt) {
   if (FID == SourceMgr.getMainFileID() && MainFileDir) {
-Includers.push_back(std::make_pair(std::nullopt, *MainFileDir));
+auto IncludeDir =
+HeaderInfo.getModuleMap().shouldImportRelativeToBuiltinIncludeDir(
+Filename, getCurrentModule())
+? HeaderInfo.getModuleMap().getBuiltinDir()
+: MainFileDir;
+Includers.push_back(std::make_pair(std::nullopt, *IncludeDir));
 BuildSystemModule = getCurrentModule()->IsSystem;
   } else if ((FileEnt = SourceMgr.getFileEntryRefForID(
   SourceMgr.getMainFileID( {
diff --git a/clang/test/Modules/Inputs/builtin-headers/module.modulemap 
b/clang/test/Modules/Inputs/builtin-headers/module.modulemap
new file mode 100644
index 000..78a5b730dc6a925
--- /dev/null
+++ b/clang/test/Modules/Inputs/builtin-headers/module.modulemap
@@ -0,0 +1,3 @@
+module ModuleWithBuiltinHeader 

[clang] [clang] use relative paths for builtin headers during module compilation (PR #68023)

2023-10-20 Thread Richard Howell via cfe-commits


@@ -180,8 +180,9 @@ static void appendSubframeworkPaths(Module *Mod,
 OptionalFileEntryRef ModuleMap::findHeader(
 Module *M, const Module::UnresolvedHeaderDirective ,
 SmallVectorImpl , bool ) {
-  // Search for the header file within the module's home directory.
-  auto Directory = M->Directory;
+  // Search for the header file within the module's home directory
+  // or the builtin include dir if this is a builtin header.
+  auto Directory = Header.HasBuiltinHeader ? BuiltinIncludeDir : M->Directory;

rmaz wrote:

Looks like we don't, no. The header ends up resolved against the resource dir 
as expected:
```


 blob data = 
'ModuleWithBuiltinHeader'
 blob data = 'float.h'
 blob data = 
'/home/llvmbuilddbg.noindex/tools/clang/test/Modules/Output/relative-resource-dir.m.tmp/resource-dir/include/float.h'
  
```

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


[clang-tools-extra] [libc++] Fix the behavior of throwing `operator new` under -fno-exceptions (PR #69498)

2023-10-20 Thread via cfe-commits

EricWF wrote:

I'm tempted to just do the non-conforming thing here (because -fno-exceptions 
is non-conforming), and just assume that when you're building with 
-fno-exceptions, you're not trying to replace the throwing operator new,  and 
you'll be fine if we have the throwing kind call the non-throwing kind. 

Is that totally insane?

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


[clang] [clang] Add clang::preferred_type attribute for bitfields (PR #69104)

2023-10-20 Thread Vlad Serebrennikov via cfe-commits

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

>From 976aa5c8f3d936a15e7123069a49d97ad3bf7a05 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Sun, 15 Oct 2023 13:14:55 +0300
Subject: [PATCH 01/12] [clang] Add clang::debug_info_type attribute

---
 clang/include/clang/Basic/Attr.td | 11 
 clang/include/clang/Basic/AttrDocs.td | 12 +
 .../clang/Basic/DiagnosticSemaKinds.td|  2 ++
 clang/lib/CodeGen/CGDebugInfo.cpp |  2 ++
 clang/lib/Sema/SemaDeclAttr.cpp   | 26 +++
 .../CodeGen/debug-info-debug-info-type.cpp| 14 ++
 6 files changed, 67 insertions(+)
 create mode 100644 clang/test/CodeGen/debug-info-debug-info-type.cpp

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 5c9eb7b8a981037..024421c0583c019 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -107,6 +107,10 @@ def NonBitField : SubsetSubjectisBitField()}],
 "non-bit-field non-static data members">;
 
+def BitField : SubsetSubjectisBitField()}],
+ "bit-field non-static data members">;
+
 def NonStaticCXXMethod : SubsetSubjectisStatic()}],
"non-static member functions">;
@@ -4264,3 +4268,10 @@ def CountedBy : InheritableAttr {
   void setCountedByFieldLoc(SourceRange Loc) { CountedByFieldLoc = Loc; }
   }];
 }
+
+def DebugInfoType: InheritableAttr {
+  let Spellings = [Clang<"debug_info_type">];
+  let Subjects = SubjectList<[BitField], ErrorDiag>;
+  let Args = [TypeArgument<"Type", 1>];
+  let Documentation = [DebugInfoTypeDocumentation];
+}
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 9f9991bdae36155..6cceba1e0e0ad01 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -7219,6 +7219,18 @@ its underlying representation to be a WebAssembly 
``funcref``.
   }];
 }
 
+def DebugInfoTypeDocumentation : Documentation {
+  let Category = DocCatField;
+  let Content = [{
+This attribute allows to alter type of a bitfield in debug information.
+Such a need might arise when bitfield is intended to store an enumeration 
value,
+but has to be specified as having enumeration's underlying type, in order to
+facilitate compiler optimizations. But this also causes underlying type to be
+emitted in debug information, making it hard for debuggers to map bitfield's
+value back to enumeration. This attribute helps with this.
+  }];
+}
+
 def CleanupDocs : Documentation {
   let Category = DocCatType;
   let Content = [{
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index e85cd4d1a1ddc0d..b5c73494df367a6 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3153,6 +3153,8 @@ def err_invalid_branch_protection_spec : Error<
   "invalid or misplaced branch protection specification '%0'">;
 def warn_unsupported_branch_protection_spec : Warning<
   "unsupported branch protection specification '%0'">, 
InGroup;
+def warn_attribute_underlying_type_mismatch : Warning<
+  "underlying type %0 of enumeration %1 doesn't match bitfield type %2">;
 
 def warn_unsupported_target_attribute
 : Warning<"%select{unsupported|duplicate|unknown}0%select{| CPU|"
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index c73a63e12f03aab..85aedd87b21d41e 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1497,6 +1497,8 @@ CGDebugInfo::createBitFieldType(const FieldDecl 
*BitFieldDecl,
 llvm::DIScope *RecordTy, const RecordDecl *RD) 
{
   StringRef Name = BitFieldDecl->getName();
   QualType Ty = BitFieldDecl->getType();
+  if (BitFieldDecl->hasAttr())
+Ty = BitFieldDecl->getAttr()->getType();
   SourceLocation Loc = BitFieldDecl->getLocation();
   llvm::DIFile *VUnit = getOrCreateFile(Loc);
   llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index feb02cad9080e3e..8d58968b7f985c8 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -5910,6 +5910,28 @@ static void handleBuiltinAliasAttr(Sema , Decl *D,
   D->addAttr(::new (S.Context) BuiltinAliasAttr(S.Context, AL, Ident));
 }
 
+static void handleDebugInfoTypeAttr(Sema , Decl *D, const ParsedAttr ) {
+  if (!AL.hasParsedType()) {
+S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
+return;
+  }
+
+  TypeSourceInfo *ParmTSI = nullptr;
+  QualType type = S.GetTypeFromParser(AL.getTypeArg(), );
+  assert(ParmTSI && "no type source info for attribute argument");
+
+  if (type->isEnumeralType()) {
+QualType BitfieldType = 

[clang] [Clang][OHOS] Keep ARM ABI selection logic in sync between Clang and LLVM (PR #68656)

2023-10-20 Thread Brad Smith via cfe-commits

brad0 wrote:

Ping.

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


[clang] [Driver] Corrections for linker flags passed with relocatable linking on OpenBSD (PR #67254)

2023-10-20 Thread Brad Smith via cfe-commits

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


[clang] 1d4601a - [Driver] Corrections for linker flags passed with relocatable linking on OpenBSD (#67254)

2023-10-20 Thread via cfe-commits

Author: Brad Smith
Date: 2023-10-20T15:52:07-04:00
New Revision: 1d4601a1ef84e4ffe2db84d17b53953b25699eef

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

LOG: [Driver] Corrections for linker flags passed with relocatable linking on 
OpenBSD (#67254)

The entry point symbol handling matches our GCC link spec..
```%{!shared:%{!nostdlib:%{!r:%{!e*:-e __start```

Remove usage of -Bdynamic as it is the default for the linker anyway.

Came up in discussion here https://github.com/llvm/llvm-project/pull/65644

Added: 


Modified: 
clang/lib/Driver/ToolChains/OpenBSD.cpp
clang/test/Driver/openbsd.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/OpenBSD.cpp 
b/clang/lib/Driver/ToolChains/OpenBSD.cpp
index 2508ef57f827ccf..e874f245776c4fc 100644
--- a/clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ b/clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -121,6 +121,7 @@ void openbsd::Linker::ConstructJob(Compilation , const 
JobAction ,
   bool Profiling = Args.hasArg(options::OPT_pg);
   bool Pie = Args.hasArg(options::OPT_pie);
   bool Nopie = Args.hasArg(options::OPT_nopie);
+  const bool Relocatable = Args.hasArg(options::OPT_r);
 
   // Silence warning for "clang -g foo.o -o foo"
   Args.ClaimAllArgs(options::OPT_g_Group);
@@ -138,7 +139,7 @@ void openbsd::Linker::ConstructJob(Compilation , const 
JobAction ,
   else if (Arch == llvm::Triple::mips64el)
 CmdArgs.push_back("-EL");
 
-  if (!Args.hasArg(options::OPT_nostdlib) && !Shared) {
+  if (!Args.hasArg(options::OPT_nostdlib) && !Shared && !Relocatable) {
 CmdArgs.push_back("-e");
 CmdArgs.push_back("__start");
   }
@@ -149,10 +150,9 @@ void openbsd::Linker::ConstructJob(Compilation , const 
JobAction ,
   } else {
 if (Args.hasArg(options::OPT_rdynamic))
   CmdArgs.push_back("-export-dynamic");
-CmdArgs.push_back("-Bdynamic");
 if (Shared) {
   CmdArgs.push_back("-shared");
-} else if (!Args.hasArg(options::OPT_r)) {
+} else if (!Relocatable) {
   CmdArgs.push_back("-dynamic-linker");
   CmdArgs.push_back("/usr/libexec/ld.so");
 }

diff  --git a/clang/test/Driver/openbsd.c b/clang/test/Driver/openbsd.c
index c84b54f24fdc24c..713bf350ee188b7 100644
--- a/clang/test/Driver/openbsd.c
+++ b/clang/test/Driver/openbsd.c
@@ -8,7 +8,7 @@
 // RUN: %clang --target=i686-pc-openbsd -pg -pthread -### %s 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PG %s
 // CHECK-PG: "-cc1" "-triple" "i686-pc-openbsd"
-// CHECK-PG: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-Bdynamic" 
"-dynamic-linker" "{{.*}}ld.so" "-nopie" "-o" "a.out" "{{.*}}gcrt0.o" 
"{{.*}}crtbegin.o" "{{.*}}.o" "-lcompiler_rt" "-lpthread_p" "-lc_p" 
"-lcompiler_rt" "{{.*}}crtend.o"
+// CHECK-PG: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-dynamic-linker" 
"{{.*}}ld.so" "-nopie" "-o" "a.out" "{{.*}}gcrt0.o" "{{.*}}crtbegin.o" 
"{{.*}}.o" "-lcompiler_rt" "-lpthread_p" "-lc_p" "-lcompiler_rt" 
"{{.*}}crtend.o"
 
 // Check CPU type for i386
 // RUN: %clang --target=i386-unknown-openbsd -### -c %s 2>&1 \
@@ -34,18 +34,19 @@
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64-LD %s
 // RUN: %clang --target=mips64el-unknown-openbsd -### %s 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64EL-LD %s
-// CHECK-LD-R: "-r"
+// CHECK-LD-R-NOT: "-e"
 // CHECK-LD-R-NOT: "-dynamic-linker"
 // CHECK-LD-R-NOT: "-l
 // CHECK-LD-R-NOT: crt{{[^./\\]+}}.o
+// CHECK-LD-R: "-r"
 // CHECK-LD-S: "-cc1" "-triple" "i686-pc-openbsd"
-// CHECK-LD-S: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-Bdynamic" 
"-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" 
"-L{{.*}}" "-s" "{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" 
"{{.*}}crtend.o"
+// CHECK-LD-S: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-dynamic-linker" 
"{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" "-L{{.*}}" "-s" 
"{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" "{{.*}}crtend.o"
 // CHECK-LD-T: "-cc1" "-triple" "i686-pc-openbsd"
-// CHECK-LD-T: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-Bdynamic" 
"-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" 
"-L{{.*}}" "-t" "{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" 
"{{.*}}crtend.o"
+// CHECK-LD-T: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-dynamic-linker" 
"{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" "-L{{.*}}" "-t" 
"{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" "{{.*}}crtend.o"
 // CHECK-MIPS64-LD: "-cc1" "-triple" "mips64-unknown-openbsd"
-// CHECK-MIPS64-LD: ld{{.*}}" "-EB" "-e" "__start" "--eh-frame-hdr" 
"-Bdynamic" "-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" 
"{{.*}}crtbegin.o" "-L{{.*}}" "{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" 
"{{.*}}crtend.o"
+// CHECK-MIPS64-LD: ld{{.*}}" "-EB" "-e" "__start" 

[clang] [clang] Add clang::preferred_type attribute for bitfields (PR #69104)

2023-10-20 Thread Vlad Serebrennikov via cfe-commits


@@ -3153,6 +3153,12 @@ def err_invalid_branch_protection_spec : Error<
   "invalid or misplaced branch protection specification '%0'">;
 def warn_unsupported_branch_protection_spec : Warning<
   "unsupported branch protection specification '%0'">, 
InGroup;
+def warn_attribute_underlying_type_mismatch : Warning<
+  "underlying type %0 of enumeration %1 doesn't match bit-field type %2">,
+  InGroup;
+def warn_attribute_bool_bitfield_width : Warning<
+  "bit-field that holds a boolean value should have width of 1 instead of %0">,

Endilll wrote:

Makes sense.
I have removed `bool` diagnostic.

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


  1   2   3   4   >